OOP Mysqli num_rows allways return 0 - php

I'm trying to count the rows returned from the database. When i run this code this will give me return of 1 row which contains a username and password but when i try to count the rows it allways give back zero even tho database is actually returning rows.
$row_count =$stmt -> num_rows only returns 0.
$stmt = $mysqli -> prepare
("SELECT username, password FROM members WHERE username=? AND password=?");
$stmt -> bind_param("ss", $username, $password);
$stmt -> execute();
$stmt -> bind_result($returned_username, $returned_password);
$stmt->fetch();
$row_count = $stmt -> num_rows;
echo $row_count;
echo $returned_username;
echo "<br />";
echo $returned_password;
$stmt -> close();
$mysqli ->close();

Use $stmt->store_result(); before getting the num_rows.
More info: http://php.net/manual/en/mysqli-stmt.num-rows.php

Try this:
$stmt = $mysqli -> prepare
("SELECT username, password FROM members WHERE username=? AND password=?");
$stmt -> bind_param("ss", $username, $password);
$stmt -> execute();
$stmt -> store_result(); //You need to store the results first
$stmt -> bind_result($returned_username, $returned_password);
$stmt->fetch();
$row_count = $stmt -> num_rows;
echo $row_count;
echo $returned_username;
echo "<br />";
echo $returned_password;
$stmt -> close();
$mysqli ->close();

Related

Nested prepared statements and free_result

Can someone explain why free_result after a while loop on a nested prepared statement causes bind_result to not update values as intended?
$stmt = $mysqli -> prepare("select col1 from table1 inner join ...");
$stmt -> bind_param("i", $id);
$stmt -> bind_result($col1);
$stmt -> execute() or die();
$stmt -> store_result();
$stmt2 = $mysqli -> prepare("select col2, col3 from table2 where col4 = ?");
$stmt2 -> bind_param("i", $col1);
$stmt2 -> bind_result($col2, $col3);
while ($stmt -> fetch()) {
$stmt2 -> execute() or die();
$stmt2 -> store_result();
while ($stmt2 -> fetch()) {
echo $col2 .",";
}
$stmt2 -> free_result(); // <== Works fine without this line
echo "---";
}
$stmt -> close();
$stmt2 -> close();
If I remove free_result, I get the expected output, let's say:
1,2,---3,4,5,---6,7,---
If I leave it, the last result of the first run on the parent loop repeats like so:
1,2,---2,2,2,---2,2,---
I can't find the answer in the docs ... It seems counter-intuitive since the results are retained instead of being freed.
Here's an executable example
As stated in the documentation for bind_result():
All columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch().
If you move the bind_result() call to the appropriate place it will work:
$stmt = $mysqli->prepare("select col1 from table1");
$stmt->execute();
$stmt->bind_result($col1);
$stmt->store_result();
$stmt2 = $mysqli->prepare("select col2, col3 from table2 where col4 = ?");
$stmt2->bind_param("i", $col1);
while ($stmt->fetch()) {
$stmt2->execute();
$stmt2->bind_result($col2, $col3);
$stmt2->store_result();
while ($stmt2->fetch()) {
echo $col2 .",";
}
$stmt2->free_result();
echo "---";
}
$stmt->close();
$stmt2->close();
The reason for this is that mysqli_stmt::free_result() asks mysqlnd to free up all result variables. The references are released, but neither the variables nor their values are not destroyed by PHP. They are just unbound.
You can either stop using mysqli_stmt::free_result() (which you probably should do anyway) or bind the result variables after every execution.

number of rows in database - prepared statements - php

I can't seem to work out how to retrieve number of rows from the database using my query, whenever I run the query It just returns zero even though it's in my database
$username = $_POST['username'];
$hash = password_verify($password, $passwordcheck);
if($stmt = $conn -> prepare("SELECT username, email, password FROM users WHERE (username = ? OR email = ?) AND password = ?"))
{
$stmt -> bind_param("sss", $username, $username, $hash);
$stmt -> execute();
$stmt -> bind_result($checkedUsername, $checkedEmail, $checkedPassword);
$stmt -> fetch();
$numberofrows = $stmt->num_rows;
$stmt -> close();
}
echo '# rows: '.$numberofrows;
Can anyone give me any hints? Can't see to wrap my head around it, thanks.
Btw, the $hash has already been queried prior to this statement.
Posting this as a community wiki:
add $stmt->store_result(); after your execute()
As I assume you have used password_hash() on the password you store in the database. Then you should not be using it in a search criteria. Re-hashing the same string will not generate the same hash using password_hash() as it will use a different SALT each time its run Thats why its the recommended hashing tool.
So you need to do something like this
$username = $_POST['username'];
$stmt = $conn->prepare("SELECT username, email, password
FROM users WHERE (username = ? OR email = ?)")
if($stmt) {
$stmt->bind_param("ss", $username, $username);
$stmt->execute();
// As per #fred-ii- comment
$stmt->store_result();
$stmt->bind_result($checkedUsername, $checkedEmail, $checkedPassword);
$stmt->fetch();
echo '# rows: ' . $stmt->num_rows;
if ( password_verify($_POST['password'], $checkedPassword) ) {
// password is correct
} else {
// password is NOT correct
}
$stmt -> close();
}

Not Getting Any Results with Query

I am having getting my query to display results, I have ran the exact same query locally in mySQL and I get the desired result but when it is executed through the following code nothing happens.
$JobID = '3214.GF.010.J45.TEA';
$ProjectID = '3214';
$conn = new mysqli ($server,$username,$password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br>";
$stmt = $conn->prepare('Select jmpPartShortDescription, ujmpLevel, ujmpRoom, jmpClosed from Inf_Jobs');
//$stmt->bind_param('ss',$JobID,$ProjectID);
$stmt -> bind_result($Description,$Level,$Room,$Closed);
$stmt -> fetch();
$stmt -> close();
$conn -> close();
echo $Description .$Level .$Room .$Closed;
I cannot understand why I get no results I am getting the Connected Successfully message but no actual values are returned.
You need to execute() a prepared statement to make it do anything.
$stmt = $conn->prepare('Select jmpPartShortDescription, ujmpLevel, ujmpRoom, jmpClosed from Inf_Jobs');
//$stmt->bind_param('ss',$JobID,$ProjectID);
$stmt->execute(); // <- this is what does the work
$stmt -> bind_result($Description,$Level,$Room,$Closed);
$stmt -> fetch();

MySQLi Query prepare and retrieving results

I've gone through quite a number of stackoverflow threads and I simply can't get it right to retrieve the results after preparing a query. I've tried a number of different solutions and none seem to be able to fetch the associative array after I execute the query
$mysqli = new MySQLi('localhost', 'root', '', 'prac2');
$query = $mysqli-> prepare("SELECT * FROM `user` WHERE username=? and password=?");
$query-> bind_param('ii', $username, $password);
if($query-> execute()) {
$query->store_result();
if ($query -> num_rows > 0) {
$result = $mysqli->query($query);
$r = $result -> fetch_array(MYSQLI_ASSOC)['userid'];
$_SESSION['userid'] = $r;
}
}
I've established that sometimes its a case of result containing a boolean for success but I'm still not certain what exactly I'm doing wrong.
UPDATED:
Okay the bind_param works now, but the fetch_assoc keeps giving me the error "Call to a member function fetch_assoc() on a non-object", I even test the result to ensure that it returns true.
$mysqli = new MySQLi('localhost', 'root', '', 'prac2');
$query = $mysqli->prepare("SELECT * FROM user WHERE username=? and password=?");
echo $mysqli->error;
$query-> bind_param('ss', $username, $password);
if($query->execute()) {
$result = $query -> store_result();
if($result) {
while($row = $result -> fetch_assoc()){
echo $row['userid'];
$_SESSION['userid'] = $row['userid'];
}
}
}
Usernames and password are strings and it should be 's' denoting that corresponding variable has type string. I don't see how usernames and passwords are integers. Bind Param Types
$query-> bind_param('ss', $username, $password);
Inside bind_param for string you should use s. I mean try ss instead of ii.

Prepared statement is returning empty results, possible syntax error

When I execute the prepared statement the results are returned empty. If I copy and paste the statement into phpMyAdmin it executes properly. $_SESSION['userGroup'] has been checked and confirmed to contain the proper value but $systems remains undefined.
Am I missing something?
$stmt = $mysqli -> prepare("SELECT `Systems` FROM `groups` WHERE `GroupID` = ?");
echo $mysqli -> error;
$stmt -> bind_param('i', $_SESSION['userGroup']);
$stmt -> execute();
$stmt -> store_result();
$stmt -> bind_result($systems);
Am I missing something?
you are missing documentation and/or tutorial to learn from.
Where you can learn the proper syntax that should include
$stmt -> fetch();
Just try
$stmt -> bind_param('i', $_SESSION['userGroup']);
$stmt -> execute();
$stmt -> bind_result($systems);
$stmt -> fetch();

Categories