->num_rows doesn't work correctly [duplicate] - php

This question already has answers here:
PHP MYSQLI number of rows doesnt work no errors
(3 answers)
Closed 6 years ago.
I don't understand why $amountOfUsers is showing as 0?
This used to work before I moved to the bind_param function... I was only using query() instad of prepare. But this is a lot safer, I just have trouble understand why this doesn't work, and how to fix it.
$stmt = $mysqli->prepare("SELECT id, expire, status, username FROM username WHERE username= ?");
$stmt->bind_param('s', $username);
$stmt->execute();
//Counting results. 0 = Invalid, 1 = Valid
$amountOfUsers = $stmt->num_rows;
The error I am getting is: $amountOfUsers isn't counting the number of results properly.

$stmt = $mysqli->prepare("SELECT id, expire, status, username FROM username WHERE username= ?");
$stmt->bind_param('s', $username);
$stmt->execute();
// Store the result (so you can get the properties, like num_rows)
$stmt->store_result();
// Get the number of rows
$amountOfRows = $stmt->num_rows;
// Bind the result to variables
$stmt->bind_result($id, $expire, $status, $db_username);
// Process the variables
while($stmt->fetch()) {
printf("%d %s %s %s\n", $id, $expire, $status, $db_username);
}

Sometimes things don't go according to plan. Checking result codes and errors available in your library is usually more efficient for troubleshooting than asking strangers, but hopefully this stranger can help... choose one of these patterns:
A:
$result = $stmt->execute();
if (!$result) { /* handle errors */ }
B:
$stmt->execute();
if ($stmt->errno != 0) { /* handle errors */ }
C (for development troubleshooting only, not code you would leave around):
$stmt->execute();
print_r($stmt->error_list);
More info here and associated pages:
http://www.php.net/manual/en/mysqli-stmt.errno.php

I would never in my life understand why php users are so inclined to the number of rows returned.
Especially if used only as a flag... if any data returned!
Why not to take the very returned data and see?
$sql ="SELECT id, expire, status, username FROM username WHERE username= ?s";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if ($row)
{
// do whatever
}
I would never understand an inclination to long and windy codes as well.
Why not to get yourself an abstraction library and get everything in one single line?
$sql = "SELECT id, expire, status, username FROM username WHERE username= ?";
if ($row = $db->getRow($sql))
{
// do whatever
}

Related

Count rows from an SQL statement and store in PHP variable [duplicate]

This question already has answers here:
Prepared Statements - Number of Rows
(4 answers)
Closed 1 year ago.
I have the following SQL code in my PHP file. I want to count the number of rows returned and store it in a variable so I can output it on the page.
I've tried a few solutions I found but none of them worked.
$stmt = $con->prepare('SELECT id, owner_id, hs_name, hs_address FROM hotspots WHERE owner_id = ?');
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
$stmt->bind_result($hsid, $ownerid, $hsname, $hsaddress);
while($stmt->fetch()) {
// print results in loop
}
Any help would be much appreciated.
I fixed this by adding
$stmt->store_result();
$count = $stmt->num_rows;
After the execute, so the entire thing now looks like
$stmt = $con->prepare('SELECT id, owner_id, hs_name, hs_address FROM hotspots WHERE owner_id = ?');
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->bind_result($hsid, $ownerid, $hsname, $hsaddress);
MySQLi provides a nice way of doing this, you can simply use the num_rows property on the statement after it has been executed. This will immediately return the number of rows returned by the statement.
$stmt->execute();
$count = $stmt->num_rows;

"bind_param" returning 0 rows [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I have a query with a parameter to bind stored in the session.
I tested the query on the database and it should return 1 row but it does not!
I tried everything. Its not an issue with the $id because I use it for another query and it is fully working:
$resultReturn = $con->prepare( 'SELECT `returns`.`return_id`, `returns`.`return_status` FROM
`agents` LEFT JOIN `returns` ON `returns`.`agent_id` = `agents`.`id` AND `agents`.`id` = ?');
$resultReturn->bind_param('i', $id);
$resultReturn->execute();
$resultReturn->fetch();
$resultReturn->store_result();
$resultReturn->bind_result($returnID, $returnStatus);
if($resultReturn)
{
echo $resultReturn->num_rows; //zero
while($row = $resultReturn->fetch_row())
{
echo $resultReturn->num_rows; //incrementing by one each time
}
echo $resultReturn->num_rows; // Finally the total count
}
$con -> close();
the first if returns always FALSE; If I set manually the id it works!
Here is my other query at the beginning of the same page (and its perfectly working):
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if (mysqli_connect_errno()) {
exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// We don't have the password or email info stored in sessions so instead we can get the results from the database.
$stmt = $con->prepare('SELECT password, email, role FROM agents WHERE id = ?');
// In this case we can use the account ID to get the account info.
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($password, $email, $role);
$stmt->fetch();
$stmt->close();
It is because I'm using the same connection for multiple queries?
Move fetch() after bind_result().
The correct order should be:
$resultReturn = $con->prepare(/* */);
$resultReturn->bind_param('i', $id);
$resultReturn->execute();
$resultReturn->store_result();
$resultReturn->bind_result($returnID, $returnStatus);
$resultReturn->fetch();

Prepared statement returns no results

I have been chasing my tale with this for a long time. I have not been able to find an issue with this code:
$query = "SELECT * FROM CUSTOMER WHERE username = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
echo $stmt->num_rows." ".$username;`
The CUSTOMER table in my database has three columns: username, pwd, and email. But nonetheless, no results are returned when I assign the $username variable to a value I know exists in the database. I know it exists because this query
$results = $db->query("SELECT * FROM CUSTOMER WHERE username ='$username'");
echo $results->num_rows;
Displays one row, which is what is expected. Can anybody please tell me why my prepared statement will not produce the correct results? I have tried several variations of quoting, not quoting, hardcoding the variable's value, but nothing works. I am on a university server so I have no control over PHP's or MySQL's settings, but I'm not sure that has anything to do with it. It seems like a coding issue, but I can't see anything wrong with the code.
num_rows will be populated only when you execute $stmt->store_result();.
However, 99.99% of the time you do not need to check num_rows. You can simply get the result with get_result() and use it.
$query = "SELECT * FROM CUSTOMER WHERE username = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
foreach($result as $row) {
// ...
}
If you really want to get the num_rows, you can still access this property on the mysqli_result class.
$result = $stmt->get_result();
$result->num_rows;
You've executed the query successfully, but not done anything with the result. After $stmt->execute();, you're looking for $stmt->bind_result($result);.
With this, you'll have access to the user's information in the $result variable.

why iam getting an error related to bind_result in error_log file and how to fix it? [duplicate]

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

Query returning zero rows despite entries existing

I have these prepared statements below. I perform the execute and both return 1, meaning the query was successful, but num_rows is still zero. I don't know why. Any ideas?
$ustmt = $bd->prepare("SELECT * FROM member WHERE username = ?");
$ustmt->bind_param("s", $username);
$astmt = $bd->prepare("SELECT address FROM member WHERE address = ?");
$astmt->bind_param("s", $address);
$sql = $ustmt->execute();
$sql2 = $astmt->execute();
echo($sql2);
echo($sql);
echo($ustmt->num_rows);
echo($astmt->num_rows);
I had forgotten to add store_result(); after I had executed. I have wasted a lot of hours!

Categories