I tried to count return rows from a query using prepared statements.
Something like this :
$q = "SELECT name, address, contact FROM members";
$stmt = mysqli_prepare ($dbc, $q);
mysqli_stmt_store_result($stmt);
// Get the number of rows returned:
$rows = mysqli_stmt_num_rows($stmt);
echo $rows;
But always I am getting 0 rows when executing this query. I tested it using mysql client ant then I got 6 returned rows.
can anyone tell me what is the wrong with this?
Thank you.
You need to call mysqli_stmt_execute to actually get a result set, before trying to store the results.
$stmt = mysqli_prepare ($dbc, $q);
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
You have to execute the query
$q = "SELECT name, address, contact FROM members";
if ($stmt = mysqli_prepare ($dbc, $q)) {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
// Get the number of rows returned:
$rows = mysqli_stmt_num_rows($stmt);
echo $rows;
mysqli_stmt_free_result($stmt);
mysqli_stmt_close($stmt);
}
You need to call execute() on your statement handle, right now you are only preparing the query.
$q = "SELECT name, address, contact FROM members";
$stmt = mysqli_prepare ($dbc, $q);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
// Get the number of rows returned:
$rows = mysqli_stmt_num_rows($stmt);
echo $rows;
i was concerned whether your table Members actually had records in it. Anyways try
$rows = mysqli_num_rows($stmt);
//or
$rows = mysql_num_rows($stmt);
This has worked out for me and has returned 5 as there were only 5 records in my table.
Related
Up to now I was checking num_rows >0 the following way:
$sql = "SELECT name FROM tbl_criteria WHERE ID =?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("location: /XX");
}else{
mysqli_stmt_bind_param($stmt, "i", $cId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
mysqli_fetch_all($result,MYSQLI_ASSOC);
if($result-> num_rows >0{
echo 'Appear if rows >0';
foreach($result as $row){
echo 'Appear for each result';
}
}
}
So suddenly this is not working anymore. I always get 0 results. I have read that it is important to call mysqli_stmt_store_result() before accessing num_rows otherwise it would usually return 0. I thought that I'm storing the results with $result = mysqli_stmt_get_result($stmt); or am I wrong?
I am hosting my website on a webserver so it could be because of an update as well. A couple of days ago it was working fine.
Your code is not working most likely due to multiple syntax errors you have. I recommend to read How to get the error message in MySQLi?
If you would like to continue using mysqli, then there is no need for this overly complex code. You can simply fetch all results into an array. There's no need to ever use num_rows.
$value = "cId";
$stmt = $conn->prepare("SELECT name FROM tbl_criteria WHERE ID =?");
$stmt->bind_param('s', $value);
$stmt->execute();
$result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
// If no rows were fetched the array will be empty and condition will be false
if ($result) {
echo 'Appear if rows >0';
foreach ($result as $row) {
echo 'Appear for each result';
}
}
This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
Iam getting this error
[07-Sep-2017 11:48:47 UTC] PHP Warning: mysqli_stmt::bind_result():
Number of bind variables doesn't match number of fields in prepared
statement
$stmt = $con->prepare("SELECT * FROM table where Id =?");
$stmt->bind_param("s", $_POST['Id']);
$stmt->execute();
$result = $stmt-> bind_result($Id);
$numRows = $result->num_rows;
if($numRows > 0) {
if($row = $result->fetch_assoc())
{
$Taxname=$row['TaxName'];
$Tid=$row['Id'];
}}
You need to alter your query. Instead of * you need to instead opt for picking out the data you actually want from the database.
For example, if the table table has columns Id,TaxName then you would execute like so:
<?php
$sqlData = array();
$stmt = $con->prepare("SELECT Id,TaxName FROM table where Id =?");
$stmt->bind_param("i", $_POST['Id']); //id is an integer? this should be i instead of s
$stmt->execute();
$stmt->store_result(); //store the result, you missed this
$stmt-> bind_result($Id,$TaxName); //bind_result grabs the results and stores in a variable
$numRows = $stmt->num_rows; //see the correction I made here
if($numRows >0){
while ($stmt->fetch()) { //propper way of looping thru the result set
$sqlData [] = array($Id,$TaxName);
//assoc array would look like:
//$sqlData [] = array("Id" =>$Id,"TaxName" => $TaxName);
}
}
$stmt->close(); //close the connection
?>
Then you would have an array of results that you can use after you've finished with mysqli queries.
Hope this helps you understand it a bit more.
$stmt = $con->prepare("SELECT Id,TaxName FROM table where Id =?");
$stmt->bind_param("s", $_POST['Id']);
$stmt->execute();
$result = $stmt-> bind_result($Id,$TaxName);
$stmt->store_result();
$numRows = $stmt->num_rows;
if($numRows > 0) {
while( $result->fetch_assoc())
{
$newid = $Id;
$newtaxname= $TaxName;
}
print_r($newid)."<br>";
print_r($newtaxname);
}
This code will give you the answer without any warnings.
Reference : http://php.net/manual/en/mysqli-stmt.bind-result.php
mysqli_stmt::bind_result — Binds variables to a prepared statement for
result storage
hope someone can help me.
i have a very simple prepared SELECT statment in PHP:
$query_select = ("SELECT * FROM companies where user_name = ? ");
$stmt = $mysqli->prepare($query_select);
$stmt->bind_param("s", $user_name);
$stmt->execute();
$count = $stmt->num_rows;
in companies table I have several rows with the $user_name i`m trying to query. But i still get 0 rows as a result.
The strange thing is that the non PREPARED version works:
$query = 'SELECT * FROM companies WHERE user_name="'.$user_name.'"';
$result = $mysqli->query($query);
$count= $result->num_rows;
echo "Aantal: ".$count;
So my question is, does anyone know why the prepared version returns ZERO and the non prepared version returns the correct number of rows?
Add this line to your code between execute and num_rows statement.
$stmt->store_result();
You have to store it before counting it.
For mysqli prepared statements, you must take an additional step: storing the result.
Try this:
$query_select = ("SELECT * FROM companies where user_name = ? ");
$stmt = $mysqli->prepare($query_select);
$stmt->bind_param("s", $user_name);
$stmt->execute();
$stmt->store_result(); // <-- new line
$count = $stmt->num_rows;
May be you need to bind the result:
/* bind result variables */
$stmt->bind_result($district);
Full example here
Trying to transition over my old mysql queries to mysqli prepared statements. I've got everything figured out except for one thing. How can I get the query results stored as an array? I used to do this like this:
$sql = "SELECT * FROM Users";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result) {
// do stuff
}
Now I have the following code. In this case, my array is a single record, so I don't need to iterate over it, but I want to hold it as an array so that I can refer to its field names. Also, I will have other queries that will return multiple records, so I'll need to iterat then.
$sql = "SELECT * FROM Users
WHERE (LOWER(first_name)=LOWER(?) && LOWER(last_name)=LOWER(?))";
$stmt = mysqli_stmt_init($link);
$this_user;
if (mysqli_stmt_prepare($stmt, $sql)) {
/* Bind the input parameters to the query */
mysqli_stmt_bind_param($stmt, 'ss', $first_name, $last_name);
/* execute query, store results in an array */
mysqli_stmt_execute($stmt);
$result = mysqli_fetch_array($stmt);
if (mysqli_num_rows($result) == 0) {
mysqli_stmt_close($stmt);
mysqli_close($link);
$tag_result = "failure";
$tag_message = "No matching user found";
echo encodeJSONObj($tag_result, $tag_message);
die();
}
if (mysqli_num_rows($result) > 1) {
mysqli_close($link);
$tag_result = "failure";
$tag_message = "Multiple records found for this user.";
echo encodeJSONObj($tag_result, $tag_message);
die();
}
$this_user = mysqli_fetch_array($result);
/* close statement */
mysqli_stmt_close($stmt);
}
$id = $this_user['id'];
$first_name = $this_user['first_name'];
$last_name = $this_user['last_name'];
// and so on...
Can somebody tell me what I am doing wrong? Thanks!
EDIT: With big thanks to Phil, I've modified my code. However, I still seem to be returning 0 rows even though my input parameters should return exactly 1 row. Here is what I have:
$sql = "SELECT id, first_name, last_name, group_id, email, cell
FROM Users
WHERE (first_name=? && last_name=?)";
$stmt = mysqli_stmt_init($link);
if (mysqli_stmt_prepare($stmt, $sql)) {
/* Bind the input parameters to the query */
mysqli_stmt_bind_param($stmt, 'ss', $first_name, $last_name);
/* execute query, bind result, and fetch value */
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $first_name, $last_name, $group_id, $email, $cell);
mysqli_stmt_fetch($stmt);
if (mysqli_stmt_num_rows($stmt) == 0) {
mysqli_stmt_close($stmt);
mysqli_close($link);
echo "No results returned";
die();
}
...
}
This always outputs No results returned when it should find 1 row and skip right past that block. I've been staring at this for a long time, but I just can't see what I am doing wrong.
Your script contains numerous errors (as mentioned in comments above). Here's a simple step-by-step...
Prepare a statement and bind parameters
$stmt = $link->prepare($sql);
if (!$stmt) {
throw new Exception($link->error, $link->errno);
}
// you can error check this too but it rarely goes wrong
$stmt->bind_param('ss', $first_name, $last_name);
Execute the statement and store the result
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
$stmt->store_result();
Do your number of row checks against $stmt->num_rows...
if ($stmt->num_rows == 0) {
// ...
}
if ($stmt->num_rows > 1) {
// ...
}
Bind and fetch the result
// This relies on the SELECT column ordering.
// You should probably change your SELECT statement to
// SELECT id, first_name, last_name FROM Users...
$stmt->bind_result($id, $first_name, $last_name);
$stmt->fetch();
$stmt->close();
$link->close();
If you want to fetch the single result row as an associative array, try this instead
$result = $stmt->get_result(); // note - this requires the mysqlnd driver
$this_user = $result->fetch_array(MYSQLI_ASSOC);
$result->free();
$stmt->close();
$link->close();
I am receiving a fatal error in my php/mysqli code which states that on line 46:
Fatal error: Call to undefined method mysqli_stmt::fetch_assoc() in ...
I just want to know how can I remove this fatal error?
The line of code it is pointing at is here:
$row = $stmt->fetch_assoc();
ORIGINAL CODE:
$query = "SELECT Username, Email FROM User WHERE User = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$user);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbUser, $dbEmail);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
if ($numrows == 1){
$row = $stmt->fetch_assoc();
$dbemail = $row['Email'];
}
UPDATED CODE:
$query = "SELECT Username, Email FROM User WHERE User = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$user);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbUser, $dbEmail);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
if ($numrows == 1){
$row = $stmt->fetch_assoc();
$dbemail = $row['Email'];
}
The variable $stmt is of type mysqli_stmt, not mysqli_result. The mysqli_stmt class doesn't have a method "fetch_assoc()" defined for it.
You can get a mysqli_result object from your mysqli_stmt object by calling its get_result() method. For this you need the mysqlInd driver installed!
$result = $stmt->get_result();
row = $result->fetch_assoc();
If you don't have the driver installed you can fetch your results like this:
$stmt->bind_result($dbUser, $dbEmail);
while ($stmt->fetch()) {
printf("%s %s\n", $dbUser, $dbEmail);
}
So your code should become:
$query = "SELECT Username, Email FROM User WHERE User = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$user);
// execute query
$stmt->execute();
// bind variables to result
$stmt->bind_result($dbUser, $dbEmail);
//fetch the first result row, this pumps the result values in the bound variables
if($stmt->fetch()){
echo 'result is ' . dbEmail;
}
Change,
$stmt->store_result();
to
$result = $stmt->store_result();
And
Change,
$row = $stmt->fetch_assoc();
to
$row = $result->fetch_assoc();
You have missed this step
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$res = $stmt->get_result(); // you have missed this step
$row = $res->fetch_assoc();
I realized that this code was provided as an answer somewhere on stackoverflow:
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
I tried it to get the number of rows but realized that i didnt need the line $stmt->store_result();, and it didn't get me my number. I used this:
$result = $stmt->get_result();
$num_of_rows = $result->num_rows;
......
$row = $result->fetch_assoc();
$sample = $row['sample'];
It's best to use mysqlnd as Asciiom pointed out. But if you're in a weird situation where you are not allowed to install mysqlnd, it is still possible to get your data into an associative array without it. Try using the code in this answer
Mysqli - Bind results to an Array