This question already has answers here:
Row count with PDO
(21 answers)
Closed 6 years ago.
I'm writing a small script to retrieve yarn details from database. I use a ajax live search script to retrieve data from the database the basic while loop function works but I want to handle the empty results by submitting a massage to the results div tag.
I did went through the first post which was made about this matter but it didn't solve my problem that's why I ask this from the stacks community. And my problem is not about getting the row count my problem is why the if command is not working.
So in order to that I use the below PHP script.
$searchString = "SELECT yarnId FROM yarndetails WHERE yarnId LIKE concat('%',:searchStr,'%')";
$dbSql = $dbConnect->prepare($searchString);
$dbSql -> bindParam(':searchStr', $_GET["q"]);
$dbSql -> execute();
$getCount = "SELECT COUNT(*) FROM yarndetails WHERE yarnId LIKE concat('%',:sStr,'%')";
$dbCount = $dbConnect->prepare($getCount);
$dbCount -> bindParam(':sStr', $_GET["q"]);
$dbCount -> execute();
$dataCount = $dbCount -> rowCount();
if($dataCount = 1){
while($row = $dbSql -> fetch(PDO::FETCH_ASSOC)) {
echo $row['yarnId'] . "\n";
}
}else{
echo "No Data";
}
I searched StackOverfllow and found out best way to count the rows is to use that "SELECT count(8).." statement but there's something wrong with it some how the if condition passes through directly to the while loop.
Is there a better way to do this or am I missing something if can help please.
$sql = "SELECT yarnId FROM yarndetails WHERE yarnId LIKE ?";
$stmt = $dbConnect->prepare($sql);
$stmt->execute(['%'.$_GET["q"].'%']);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($data){
echo json_encode($data);
}else{
echo "No Data";
}
Given you are using it for AJAX, the condition is essentially superfluous too, as it should be a no-brainer to tell an empty array in JS. Making the last 5 rows just
echo json_encode($data);
I want to display a drop-down list which pull out database values. My actual code working fine, but here I have to provide the list in the array itself. What i required is, without editing the code, i needed to pull out values from database to this array("state1","state2"....); which is equal to something like this array("$states");
$sql = "SELECT * FROM `States`";
$result = $conn->query($sql);
$i=0;
while($row = $result->fetch_assoc()) {
$t=$row['statename'];
$t[$i]=$row['statenname'];
$i++;
}
$countryArr = array( "INDIA" => array("$t"));
I tried the above code but its listing only one value from database.
Remove this line
$t=$row['statename'];
just keep it to be
$t[$i]=$row['statenname'];
I have create multiple row by using javascript. Now how to save these row in mysql. I already using some type of code, its not working. here my code is
[http://jsfiddle.net/bb2pJ/]
and php code for adding these value.
`
include "config.php";
if(isset($_POST['submit']))
{
foreach ($_POST['code1'] as $key => $value)
{
$code1 = $_POST["code1"][$key];
$product1 = $_POST["product_name1"][$key];
$qty = $_POST["quantity1"][$key];
$rate = $_POST["amount_name1"][$key];
$total = $_POST["total_name1"][$key];
$sql = mysql_query("insert into testing(code,product,qty,rate,total)values('$code1','$product1','$qty1','$rate1','$total1')")or die(mysql_error());
}
}
?>`
From you Js fiddle code, you are trying to post array of values for each field (ie code, proddname, ...).
How are submitting these values? If not passing through ajax post, then you need to declare fields names like code[], product_name[] ... as array for all fields so they will be submitted as array.
Rest code you have writtten above should work by using proper field name like code for code[] ... .
Please put proper spacing between your keywords and values/fieldname in your insert into.. statement.
I am trying to retrieve a single row from a MySQL table using a mysqli statement. I've tried several different iterations of code, subtly changing the structure based on various previous questions from this forum, and others, but can't seem to get any result other than 'null'.
This is part of a larger script which is called via an Ajax request with jQuery. I've included both the PHP and the Javascript below, though I'm fairly confident in the JS being OK (preparing to be told otherwise now...).
Any suggestions as to where I'm going wrong would be very much appreciated as I can't see the wood from the trees anymore, and am just going around in circles.
PHP:
//initiate new mysqli object
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name); //custom subclass, this definitely works as is used in other scripts on the server
//prepares DB query. Query has been tested on phpmyadmin and returns the expected data set
$stmt = $retrieve_link->prepare("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
$stmt->execute(); //no params to bind, so execute straight away
$stmt->bind_result($item);
$stmt->fetch();
$dataset = $item->fetch_row();
$response[0] = $dataset; //returned data forms part of larger dataset
echo json_encode($response); //return the entire dataset to a jquery Ajax request
die;
JS:
//this definitely works as objects have been returned via the 'success' function as the code was being developed
$.ajax({
url : "items/populate-home-page-script.php",
type : "GET",
data : {data:toSend},
dataType : "json",
success : function(data){
alert(data[0]);
},
error : function(jqXHR, textStatus, errorThrown){
alert(textStatus+','+errorThrown);
}
});
return false;
I have also tried using fetch_assoc() and fetch_row() as part of the PHP query, taking direction from the PHP reference material here and here. I have also read through these questions from Stackoverflow this, this, and this, but I still seem to get a return of null for every different code combination I try.
As I've said in a code comment, I know that the link to the DB works as I've used it in other scripts, and in other areas in this script - so there's no reason why this object wouldn't work either. I also know that the query returns the expected data when inputted to phpmyadmin.
The returned data is just a number of strings, any all I would like to do is store around 16 returned datasets to an array, as part of a loop, and then return this array to the Ajax request.
You are using "AuctionMySQLi" which appears to extend the regular Mysqli driver. I'll assume it does this correctly.
You're using prepared statements which is probably an overkill in this case. You could accomplish the same thing with something like this (php 5.3, mysqli + mysqlnd):
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$result = $retrieve_link->query("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
if($result !== false) {
echo json_encode($result->fetch_all());
} else {
echo json_encode(array());
}
$retrieve_link->close();
If you're using an older php version, or mysqlnd is not available, you can also do
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$result = $retrieve_link->query("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
if($result !== false) {
$output = array();
while($row = $result->fetch_assoc()) {
$output[] = $row;
}
echo json_encode($output);
} else {
echo json_encode(array());
}
$retrieve_link->close();
I also understand that you want to limit the number of results. In both cases, a good way of getting it done is to use a LIMIT statement in SQL. This is lower the overhead overall at source. Otherwise you can array_slice to slice the output of result->fetch_all() in solution 1, or $output in solution 2.
Finally, if you insist in using prepared statement read the note at
http://ca2.php.net/manual/en/mysqli-stmt.bind-result.php
and analyze provided example:
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$stmt = $retrieve_link->prepare("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
$stmt->execute();
$stmt->bind_result($itemName, $itemCat, $endDate, $auctionType, $highBidder);
$output = array();
while($stmt->fetch()) {
$output[] = array($itemName, $itemCat, $endDate, $auctionType, $highBidder);
}
echo json_encode($output);
$retrieve_link->close()
It looks to me like you may have some confusion about ->fetch() and ->fetch_row(). You should use one or the other, but not both.
Try this to retrieve your result set:
$stmt->execute();
while ($dataset = $stmt->fetch_row()) {
$response[] = $dataset; //returned data forms part of larger dataset
}
This will append each row of your result set to your $response array.
I have a mysql table with image data in.
I want to retrieve the image data and push into a javascript array.
There are two fields that I want to put into the array and they are image_ref, and image_name
I know I need a 2D array for this and I need to retrive the data from the db using ajax and JSON.
I am not sure how to complete this.
I know I need to call the php page with a JSON ajax call
js:
var imagesArray[];
$.getJSON("get_image_data.php")
.done(function(data) {
/*THIS IS WHERE I NEED HELP---*/
});
get_image_data.php page
include("connect.php");
$query = mysql_query("SELECT * FROM images WHERE live='1' ORDER BY insertDate DESC");
while($row=mysql_fetch_array($query){
echo json_encode(array("a" => $row['image_ref'], "b" => $row['image_name']));
}
I have highlighted where I need help in getting the returned data into the stockImages array.
Can anyone show me the light?
thanks in advance
By calling json_encode() multiple times in your loop, you are creating lots of singular bits of JSON. You should aim at creating and transmitting one transfer object, like this:
include("connect.php");
$query = mysql_query("SELECT * FROM images WHERE live='1' ORDER BY insertDate DESC");
$images = array();
while($row=mysql_fetch_array($query){
$images[] = array("a" => $row['image_ref'], "b" => $row['image_name']);
}
echo json_encode($images);
This will give you one JSON array, through which you can loop in your client side Javascript.
Actually, it is PHP that is wrong, 'cause on JS you will have the array you need directly in "data".
You PHP code should look like:
$query = mysql_query("SELECT * FROM images WHERE live='1' ORDER BY insertDate DESC");
$result = array();
while($row=mysql_fetch_array($query){
$result[] = array("a" => $row['image_ref'], "b" => $row['image_name']);
}
echo(json_encode($result));