MYSQLI fetch array results in alert box - javascript

I am trying to put mysqli results in alert box. it just show "Already Scanned".
below is the code:
echo '<script language="javascript">';
$new_query = mysqli_query($connection, "SELECT * FROM `table` WHERE `id` = '$id' LIMIT 1");
while ($row = mysqli_fetch_array($new_query))
{
echo 'alert("Already Scanned");
location.href="javascript:history.back()"';
}
echo '</script>';
how can i put MYSQLI fetch array results in alert box?

From your comments, I have understood that this is what you want:
Replace the echo command on line 8 with this:
echo 'alert("ID: ' + $row["id"] + ', name: ' + $row["name"] + ', mobile: ' + $row["mobile"] + '"); location.href="javascript:history.back()"';
This will display all the data you desire to display in the alert box. I understand that this is probably what you want to do right now. Correct me if you wished to do something else.
It isn't the prettiest solution, though.

Related

I have a single div and it needs to be duplicated dynamically

I have a single div and a unknown number(say n) of rows of data. i need to show that data on my html cards
and these cards are to be generated dynamically by the output value(n).
say if i have 10 rows of data.my div element needs to be created 10 times and each row data is to be displayed on each div
by the way i am using PHP for backend.
here is my codes
This is my div
<div class="row">
<div class="column">
<div class="card">
<h1><?php echo"$value"; ?></h1>
<h3><?php<?php echo"$description";?></h3>
</div>
</div>
</div>
and this is my php code
<?php
$conn=new mysqli("localhost","root","","programmingpioneers");
if(!$conn)
{
echo "connection_failed";
}
else{
//echo "sucess";
}
$query= "select title,description from problems where difficulty='hard'";
$result=mysqli_query($conn,$query);
$row=mysqli_fetch_array($result);
if (mysqli_query($conn, $query))
{
echo "sucess<br>";
while ($row=mysqli_fetch_array($result)) {
$title=$row[0];
$description=$row[1];
echo "$title <br> $description";
}
}
else {
echo "Error: " . $query . "<br>" . mysqli_error($conn);
}
?>
if i try to but my div inside
echo"$title <br>$description";
it is throwing the following error
Parse error: syntax error, unexpected 'row' (T_STRING), expecting ';' or ',' in C:\xampp\htdocs\myapp\useless.php on line 19
Use loop in the div you want to have again and again.Please check the code if it works for you.
enter image description here
enter image description here
Without having all your data available I'm unable to test it, but this should be the correct way of doing it. I left comments in the code and removed a bunch of syntax errors that you made:
<?php
// Create MySQLi object
$conn = new mysqli("localhost","root","","programmingpioneers");
// Verify MySQL connection
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
// Query
$query = "SELECT title,description FROM problems WHERE difficulty = 'hard'";
// Run query
if($result = $conn->query($query)) {
// Loop through query results
while ($row = $result->fetch_assoc()){
echo "<div class='row'>";
echo "<div class='column'>";
echo "<div class='card'>";
echo "<h1>". $row['title'] ."</h1>";
echo "<h3>". $row['description'] ."</h3>";
echo "</div></div></div>";
}
// Output query errors
} else {
echo "Failed to select title, description: (" . $conn->errno . ") " . $conn->error;
}
// Close the MySQLi connection
$conn->close();
?>

visually show counter from id in MySQL

I have a database with 100 rows. I have a button that shuffle those id's and print out 3 random ids.
HTML
<form method="post">
<button>Shuffle</button>
</form>
PHP
$sql = "SELECT id, description FROM fantasies_original ORDER BY RAND ( ) LIMIT 3";
$res = $mysqli->query($sql);
//print($res);
if ($res->num_rows > 0) {
// output data of each row
while($row = $res->fetch_assoc()) {
echo "Store Number: " . $row["id"]. "<br>" .
"Description: " . $row["description"]. "<br><br>";
}
} else {
echo "0 results";
}
I would like to visualize the counter. So when I press the button I can see the number of the id there is loop through in the database. I have been looking everywhere to find a library that could do the job.
Does anybody knows a library or have a suggestion how to do that?

Updating MySQL Database with checkboxes and PHP

I am trying to update a MySQL database with checkboxes and PHP. I have read a lot of code examples online and read many questions on here but I seem to be stuck at the last hurdle.
My code first queries MySQL to bring back a list of users and then a checkbox (which is either 0 or 1 in MySQL) next to each one, indicating whether or not the user is completed.
What I am wanting to do is when the checkbox is checked, for that to update the MySQL database and update the column with 1, or if it is unchecked, for it to change the column to 2.
Here is my code so far:
HTML Snippet (Checkboxes):
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Firstname'] . "</td>";
echo "<td>" . $row['Surname'] . "</td>";
echo "<td>" . $row['Department'] . "</td>";
echo "<td>" . $row['RequestedBy'] . "</td>";
echo "<td>" . $row['StartDate'] . "</td>";
echo "<td class='tbl-chk'> <input type='checkbox' name='WSCompleted' value='"; echo $row['ID'] . "'" ; if ($row['WSCompleted']=='1') { echo "checked='checked'";} echo "/></td>";
Here is my jQuery that successfully retrieves the values and IDs and then posts them:
$(document).ready(function(){
$('input[name=WSCompleted]').click(function(){
var wsCompleted = $(this).is(':checked') ? 1 : 0;
var wsCompletedID = $(this).attr('value');
$.ajax({
type: "POST",
url: "/usr-handler.php",
data: {id: wsCompletedID, wsCompleted: wsCompleted},
success: function(){
$('div.success').fadeIn();
}
});
return true;
});
});
And finally here is a snippet of my PHP:
$wsCompleted = $_POST['wsCompleted'];
$id = $_POST['wsCompletedID'];
$query = "UPDATE newusers SET WSCompleted = '$wsCompleted' WHERE id = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
I am setting the value of the checkbox to what is actually the row ID in MySQL, then I can use the checkbox value to select the correct row in MySQL, and update it.
The problem I am having is that currently, how the code is, I get the following response from FireBug:
Unidentified index: WSCompletedID
After looking online it was suggested to change:
$id = $_POST['wsCompletedID'];
To:
$id = (ISSET($_POST['wsCompletedID']));
But doing so clears the error message, but then doesn't actually update the value on MySQL.
If I manually set the $id to something, the update works, but obviously that isn't right as it would only ever update the ID I have chosen it to.
I am completely stumped as to what is causing the problem. I have tried finding out online but cannot get anywhere with it.
Any help is greatly appreciated.
Thank you
You are loading data here in your javascript AJAX code
data: {id: wsCompletedID, wsCompleted: wsCompleted},
This will create the following $_POST array
id => whatever was in wsCompletedID
wsCompleted => whatever was in wsCompleted
So your PHP code should be looking for $_POST['id'] and $_POST['wsCompleted'] as these are the names you have given in your data:...
$wsCompleted = $_POST['wsCompleted'];
$id = $_POST['id'];
$query = "UPDATE newusers SET WSCompleted = '$wsCompleted' WHERE id = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
HOWEVER: Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared statement and parameterized statements

Change button text from "Like" to "Liked" when clicked

I am creating a forum where users are able to like and unlike posts and comments. The challenge I'm facing is that I would like the text of the like button to change without reloading the page. How can I go about differentiating between the buttons on the page and change individual button-texts from "Like" to "Liked" and vice versa? The buttons are, at the moment created and show like this:
<?php
$result3=mysqli_query($link, "SELECT * FROM cs_comments WHERE post_id = $postID");
while($row3 = mysqli_fetch_assoc($result3)){
$commentID=$row3['comment_id'];
$memberID=$row3['member_id'];
$likes=$row3['likes'];
$content= $row3['content'];
$anonymous=$row3['anonymous'];
if($anonymous=='1')
$name='Anonym';
else{
$result4= mysqli_query($link, "SELECT firstname, lastname FROM cs_members WHERE member_id = $memberID");
$row4=mysqli_fetch_assoc($result4);
$name = '' . $row4['firstname'] . " " . $row4['lastname'] . '';
}
$result5=mysqli_query($link,"SELECT * FROM cs_likes WHERE comment_id=$commentID AND member_id={$_SESSION['memberID']}");
if(mysqli_num_rows($result5)!=0)
$liked="unlike";
else
$liked="like";
echo '<div class="post_container">';
echo ' <div class="info_header">';
echo ' <div class="info_name">' . $name . '</div>';
echo ' <div class="info_group"></div>';
echo ' </div>';
echo ' <div class="post_content">';
echo $content;
echo ' </div>';
echo ' <div class="post_footer">';
echo ' <div class="like_button"><button onclick="likeComment('. $commentID . ')">' . $liked . '(' . $likes . ')</button></div>';
echo ' </div>';
echo '</div>';
}
mysqli_close($link);
?>
Javascript for onclick-event:
function likeComment(id) {
$.ajax({
url: '/resources/phpScript/like.php',
type: 'POST',
data: {comment_id:id},
success: function(data) {
console.log(data); // Inspect this in your console
}
});
Like.php
<?php
session_start();
include "./db-connect.php";
$memberID= $_SESSION['memberID'];
if(isset($_POST['post_id'])){
$postID=mysqli_real_escape_string($link,$_POST['post_id']);
$sqlCheck="SELECT * from cs_likes WHERE post_id = $postID AND member_id = $memberID";
$sqlInsert="INSERT INTO cs_likes (post_id, member_id) VALUES ('$postID','$memberID')";
$sqlDelete="DELETE FROM cs_likes WHERE post_id= $postID AND member_id = $memberID";
}
elseif(isset($_POST['comment_id'])){
$commentID=mysqli_real_escape_string($link,$_POST['comment_id']);
$sqlCheck="SELECT * from cs_likes WHERE comment_id = $commentID AND member_id = $memberID";
$sqlInsert="INSERT INTO cs_likes (comment_id, member_id) VALUES ('$commentID','$memberID')";
$sqlDelete="DELETE FROM cs_likes WHERE comment_id= $commentID AND member_id = $memberID";
}
else
echo "Something went wrong";
$checkResult=mysqli_query($link, $sqlCheck);
if(mysqli_num_rows($checkResult)==0)
$result=mysqli_query($link,$sqlInsert);
else
$result=mysqli_query($link,$sqlDelete);
?>
Any help is appreciated!
So I found the solution! I have little to no experience with javascript, which is why this may have been too simple of a question for anyone to find out what I was after!
This is what I did:
I simply sent the element clicked by adding this to the function call on click:
echo ' <div class="like_button"><button onclick="likePost('. $postID . ',this)">' . $liked . '</button></div>';
I then added this tiny bit to my function:
function likePost(id, elem) {
if(elem.innerHTML== "like")
elem.innerHTML="unlike";
else
elem.innerHTML="like";
I still want to thank everyone who made and effort to try understanding what I was asking.

How can I specify a specific value in a column retrieved via php?

I would like to add an if statement regarding the 'type' column. Is there something after the .attr('type') which will allow me to specify a particular value for type?
$.get("map_process.php", function (data) {
$(data).find("marker").each(function () {
var name = $(this).attr('name');
var address = '<p>'+ $(this).attr('address') +'</p>';
var type = $(this).attr('type');
So $(this).attr('type'); is loading all the rows in my tables 'type' column value. eg:
Table
Name, Address, Type*
Name1, Address1, TypeA,
Name2, Address2, TypeB,
Name3, Address3, TypeA,
etc
How can I 'get access' to what actually the value of the 'type' column; eg. $(this).attr('type').<something>('TypeA');
Is this possible?
Edit2: map_process.php end
// Select all the rows in the markers table
$query = "SELECT * FROM markers";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo 'description="' . parseToXML($row['description']) . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
You have two options:
(1) If you have full control over the ajax page you are calling, the best solution would be to:
"send the selected checkbox value into map_process.php and get the
selected value from table and update the markers again in Map." –
Krish R
//jQuery
var cbVal = "TYPEA"; //Assign with checkbox value's associated string
$.get("map_process.php?checkboxval=" + cbVal, function (data)
{
//do something with the data returned
});
//PHP
$query = "SELECT * FROM markers where type = '".$_GET["checkboxval"]."'";
(2) If you don't have control over the source of the ajax call (for example from a third party source), OR you want to return all markers every time, consider using the jQuery Filter method.
//jQuery
var cbVal = "TYPEA"; //Assign with checkbox value's associated string
$(data).filter(function(index,val)
{
return $(val).attr('type') === cbVal;
}).each(function ()
{
//do something with the data returned
});
See the example for option (2) on this JSFiddle

Categories

Resources