num_rows doesn't work with prepared statement [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have a test code where I try to reach my database information. But one script that uses prepared statements does not work, and second without prepared statements works just fine.
$userzzz = "test";
With this script, I get "BAD" as the result
$db = new mysqli("localhost", "root", "", "test");
$stmt = $db->prepare('SELECT * FROM user WHERE username=?');
$stmt->bind_param('s', $userzzz);
$stmt->execute();
echo $stmt->num_rows();
if ($stmt->num_rows > 0){
echo "good";
} else {
echo "bad";
}

From the manual,
The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.
If you use mysqli_stmt_store_result(), mysqli_stmt_num_rows() may be called immediately.
Which means that you'll have to use $stmt->store_result(); after executing, but before accessing the num_rows property.
$stmt = $db->prepare('SELECT * FROM user WHERE username=?');
$stmt->bind_param('s', $userzzz);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows;
if ($stmt->num_rows > 0){
echo "good";
} else {
echo "bad";
}
If you don't do this, the rows won't be buffered into the memory, and there's no way of knowing how many rows actually was returned, until you loop through the entire set of data (by while ($stmt->fetch())).
PHP.net on mysqli_stmt_store_result()

in object oriented mysqli, num_rows is not a function, it's an attribute of the result (stmt). You need $stmt->num_rows; not $stmt->num_rows();
In your second example, you're not using (), you are doing it correctly, hence why it functions in the second but not the first.
$db = new mysqli("localhost", "root", "", "test");
$stmt = $db->prepare('SELECT unique_col FROM user WHERE username=?');
$stmt->bind_param('s', $userzzz);
$stmt->execute();
$stmt->store_result();
$rows = $stmt->num_rows;
if ($rows > 0){
echo "good";
} else {
echo "bad";
}
I also added $stmt->store_result(). It is finicky and num_rows will be 0 unless you store the result before you run $stmt->num_rows;
I'd also use a unique column instead of *, such as id for example.

Well you need to bind the results after you execute, this will work in your case (works for me):
<?php
$userzzz = 'test';
$db = new mysqli("localhost", "root", "", "test");
$stmt = $db->prepare('SELECT * FROM users WHERE username = ?');
$stmt->bind_param('s', $userzzz);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows();
if ($stmt->num_rows() > 0){
echo "good";
} else {
echo "bad";
}
?>

Related

if/else statement in function php not inserting [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
what i want to do is that it checks the input field and after that it will insert the following query or it it gives an error message. My problem is that my query won't insert.
My PHP function that won't work (other file then html file):
function Code($userID) {
require '../conn.php';
$sql = "SELECT `current_uses` FROM `sub_codes` WHERE `content` = '".$_POST['Code']."'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
if ($row['current_uses'] > 0){
$query = "INSERT INTO `partner_subscriptions` (`id`, `user_id`, `sub_id`, `allowed_users`, `start_date`, `end_date`) VALUES (NULL, ?, ?, ?, ?, ?);";
$stmt = $conn->prepare($query);
$_userID = $userID;
$_subID = '99';
$_allowedUsers = '100';
$_startDate = date('Y-m-d');
$sql2 = "SELECT `end_date` FROM `sub_codes` WHERE `content` = '".$_POST['Code']."'";
$result2 = mysqli_query($conn, $sql2);
$row2 = mysqli_fetch_array($result2);
$_endDate = $row2['end_date'];
$stmt->bind_param("sssiiii", $_userID, $_subID, $_allowedUsers, $_startDate, $_endDate);
$stmt->execute();
$lastID = $conn->insert_id;
$stmt->close();
return $lastID;
}else {
echo "Wrong code";
}
}
My html file:
<br/><div class="form-group">
<label title="Required">Free description code:</label>
<input type="text" name="Code" class="form-control" id="Code"/>
</div><br/>
The rest of my PHP file (that i think you need to know):
if (usedmail($_POST['username'])==true) {
$lastID = saveUser($_POST['fnln'], $_POST['username'], password_hash($_POST['password'], PASSWORD_BCRYPT), 0, 0, 1);
$niv = NULL;
if ($_POST['type'] == "3") { // If the partner is an educational institution look for niveau
$niv = NivID($_POST['niv']);
}
Code($lastID, $_POST['Code']);
$path = saveImage();
Contact($lastID);
Image($lastID);
Social($lastID);
Story($lastID);
Skill($lastID);
$orgID = saveOrganisation($lastID, $_POST['organisation'], $path, $_POST['type'], $_POST['branche'], $niv);
updateUser($orgID, $lastID);
}
else {
header('Location: ../../mailerror');
}
every other function works normal except the code function and i don't really know why. I appreciate your help!
Well, for explanation reasons how to use mysqli the right way. First of all, you have to keep control of your code. Always check what happens and catch any mistakes. You don 't do that and that 's the reason you don 't know, why your insert statement is not executed.
Error Handling for the win!
Use the results, which are explained in detail in the manual. Nearly every mysqli method returns a false value, when something went wront. Use it!
$sql = "SELECT current_uses FROM sub_codes WHERE content = ?";
$stmt = mysqli_prepare($connection, $sql);
// Is there a prepared statement?
if (!$stmt) {
die(printf('Something went wrong: %s.', mysqli_error($connection)));
}
// use the mysqli statement (one type definition per used variable)
$result = mysqli_stmt_bind_param($stmt, "s", $_POST['code']);
if (!$result) {
die(printf('Something went wrong: %s.', mysqli_stmt_error($stmt)));
}
// execute the statement
$result = mysqli_stmt_execute($stmt);
if (!$result) {
die(printf('Something went wrong: %s.', mysqli_stmt_error($stmt)));
}
As you can see it is necessary to check what the result of each mysqli function call is to avoid unpredictable behavior of your script. Always keep in mind not to use post variables directly in sql statements. This is a huge mistake and opens your script for several vulnerabilities via sql injection.
Please read one of the many sql injection topics here on stack overflow to understand what sql injection is and how you can prevent it: How can I prevent SQL injection in PHP?
I had to change "sssiiii" to "iiiss" because Every single character of your 'sssiiii' stands for a single value that is bound to the statement.

PHP Mysqli bind_param query not returning results [duplicate]

This question already has answers here:
PHP: Mysqli prepared statement with "select *"
(2 answers)
Closed 6 years ago.
Intro: I'm trying to do a sql-injection proof login on my website, so I'm using mysqli bind param, I've created the query following instructions from the official manual of php.net, unfortunately it doesn't work as expected.
Here is my query code:
//Asign post to variables
$var1 = $_POST["email"];
$var2 = $_POST["pwd"];
if(isset($_POST['submit'])){
//Query SQL
$sql = $mysqli->prepare("SELECT * FROM main WHERE email = ? AND pass = ?");
$sql->bind_param("ss", $var1, $var2);
$sql->execute();
$sql->bind_result($email, $pass, $license);
$sql->fetch();
echo $email;
echo $pass;
echo $license;
}
So, this piece of code should echo the three fields it fetched from my database but it doesn't return anything. My database connection is perfectly fine, because this query was working perfectly without any kind of bind_param.
Summing up, I want to know why it doesn't echo the 3 values i got from the Sql query (they show up as unexistent)
Edit My error was I was doinng "bind_result" instead of "get_rersult" which is much better if you are selecting everything (*)
Edit: sorry I didn't notice you are using mysqli connection
you can use get_result instead of bind_result
$sql = $mysqli->prepare("SELECT * FROM main WHERE email = ? AND pass = ?");
$sql->bind_param("ss", $var1, $var2);
$sql->execute();
$rows = $sql->get_result();
$row = $rows->fetch_assoc();
$email = $row['email'];
$pass = $row['pass'];
$license = $row['license'];

PHP prepared statement with mysql multiple selection doesn't return anything [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
the below php code doesn't return anything while the below one returns value, the only difference is the multiple selection. why is that?
(When I test is in my browser it dosen't shot anything)
I also tried to put the selection between () but doesn't help.
NON Working code:
<?php
$mysqli = new mysqli("x", "w", "y", "z");
$coresite = "Abbasya";
$rowx = "103";
$columnx = "3";
$directionx = "Back";
if($stmt = $mysqli->prepare("SELECT CABOwner, EtisaatTeam FROM CAB WHERE (SiteName=? AND Row=? AND Col=? AND Direction=?)"))
{
$stmt->bind_param("ssss", $coresite, $rowx, $columnx, $directionx);
$stmt->execute();
$stmt->bind_result($cabinet);
while ($stmt->fetch())
{
echo json_encode($cabinet).",";
}
$stmt->close();
}
else{
$mysqli->close();
}
?>
Working Code with one selection:
<?php
$mysqli = new mysqli("x", "w", "y", "z");
$coresite = "Abbasya";
$rowx = "103";
if($stmt = $mysqli->prepare("SELECT DISTINCT Col FROM CAB WHERE (SiteName=? AND Row=?)"))
{
$stmt->bind_param("ss", $coresite, $rowx);
$stmt->execute();
$stmt->bind_result($Col);
while ($stmt->fetch())
{
echo json_encode($Col).",";
}
$stmt->close();
}
else{
$mysqli->close();
}
?>
Since it returns multiple values you need to bind to multiple variables. Like $stmt->bind_result($Col1, $Col2);

SELECT statement not working - mysqli

I'm reaching out after hours of fruitlessly trying to fix a small section of code that just doesnt seem to work regardless of how i try to fetch the value and store.
I will admit I'm not the most experienced and hoping it is a small error on my part that can be easily spotted by someone with more expertise.
All other functions work as expected and fetch all the required value except one, With s the member_id field. This is a linked ID from another table (companies) however in test query the statement works fine.
Whole Code Snippet
<?php
//Error reporting - DEV ONLY
error_reporting(E_ALL);
ini_set('display_errors', 'on');
//New Connection
$mysqli = new mysqli('localhost', 'USER', 'PASSWORD', 'DATABASE');
//Connection Verification
if ($mysqli->connect_errno) {
printf("Connection Failure: %s\n", $mysqli->connect_error);
exit();
}
//Start Session and assign POST values
session_start();
$username = $_POST['username'];
$password1 = $_POST['password'];
//Query prepare, execution and bind
$stmt = $mysqli->prepare("SELECT password FROM user WHERE username='$username'");
$stmt -> execute();
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
/* Close statement */
$stmt -> close();
//Verify password match and direct user according to result
if(password_verify($password1, $result))
{
$stmt = $mysqli->prepare("SELECT member_id FROM user WHERE username='$username'");
$stmt -> execute();
$stmt -> bind_result($company);
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
$_SESSION['company'] = $company;
Header("Location: home.php");
}else{
sleep(5);
Header("Location: index.php");
}
$mysqli->close();
?>
Suspected Issue Code Snippet
if(password_verify($password1, $result))
{
$stmt = $mysqli->prepare("SELECT member_id FROM user WHERE username='$username'");
$stmt -> execute();
$stmt -> bind_result($company);
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
$_SESSION['company'] = $company;
Header("Location: home.php");
}else{
sleep(5);
Header("Location: index.php");
}
Thank you in advance for your help!
EDIT: The issue is, there is no output from:
SELECT member_id FROM user WHERE username='$username
However in a direct query with MySQL it works so feel its a binding issue. this should be bound to $_SESSION['company'].
The other answer is somewhat examplary.
As the question is going to be closed anyway, I'd take a liberty to comment the other answer.
change the name of your second instance of $stmt to something else - $stmtTwo
There is no point in doing that, as previous statement is already closed and cannot interfere in any way.
Would I be writing PHP for 15 years, I would rather suggest to do all the mysql job in one single query, without the need of second statement at all.
add a var_dump($stmtTwo); after binding the result into $company.
That's quite a random poke. Why after binding but not anywhere else?
check your MySQL log for MySQL errors.
For 99% of php users that's mission impossible. Yet it's a matter of only two commands to have the error message right on the screen on the development server.
Is the column member_id in the user table?
That is again a random poke (what about password field?) and it's have to be addressed to the error message discussed in the previous topic anyway. There is no point in asking a programmer for that. One should ask a database, as a way more reliable source.
Add a print output inside it, to show that the password_verify function is working and allowing that code block to execute.
That's the only good point.
Recommendation for using prepared statements is right too, but for some reason it is called "Object style" which is nowhere near the point.
And yes, he finally managed to spot the typo that makes whole question offtopic - fetch() statement is absent.
I suspect that your MySQL is not firing because you're using a PREPARE statement without passing it any values.
Would I be using mysqli myself, I would have known that such a query is all right.
header should be lower case. header() and should be immediately followed by a die or exit command.
Neither is actually true.
Functions in PHP are case insensitive and there is no logic behind this point - so, no manual exit is required.
Stack Overflow is not a code review site either, but nobody cares actually, as one third of answers to those celebrated 10M questions are actually code review answers. So here it goes:
<?php
//Error reporting - ALWAYS PRESENT
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//Error displaying - DEV ONLY
ini_set('display_errors', 'on');
//New Connection
$mysqli = new mysqli('localhost', 'USER', 'PASSWORD', 'DATABASE');
//Start Session
session_start();
//Query prepare, bind, execute and fetch
$stmt = $mysqli->prepare("SELECT member_id, password FROM user WHERE username=?");
mysqli->bind_param("s",$_POST['username']);
$stmt->execute();
$stmt->bind_result($member_id, $db_pass);
$stmt->fetch();
if(password_verify($_POST['password'], $db_pass))
{
$_SESSION['username'] = $_POST['username'];
$_SESSION['company'] = $member_id;
Header("Location: home.php");
}else{
Header("Location: index.php");
}
You have not added a Fetch statement after binding the result:
if(password_verify($password1, $result))
{
$stmt = $mysqli->prepare("SELECT member_id FROM user WHERE username='$username'");
$stmt -> execute();
$stmt -> bind_result($company);
$stmt -> fetch();
/* Close statement */
$stmt -> close();
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
$_SESSION['company'] = $company;
Some extra notes:
You are writing your MySQL incorrectly, it is wide open to compromise.
You are using the old MySQL style approach but with the structure of the newer OOP approach, this is just as much as security risk as original MySQL.
Old - procedural- style:
mysqli_query($link, "SELECT poops FROM bathroom WHERE smell = '$bad' LIMIT 1");
New - Object Orientated style:
mysqli->prepare("SELECT poops FROM bathroom WHERE smell = ? LIMIT 1")
mysqli->bind_param("s",$bad); //the value is placed by reference rather than directly
mysqli->execute;
Also:
header should be immediately followed by a die or exit command.
header("Location:blah.php");
exit;

Assigning a mysql field value to a PHP variable [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am trying to assign the value of the my below database field (sname) to a php variable (name).but I am getting below error.Can someone help
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/a4363282/public_html/pune/upload/upload_file.php on line 6
include './connection.php';
$query = "select * from shops WHERE city='pune' AND Ref=1;
$row = mysql_query($query);
$name=$row['sname'];
echo $name;
You are missing double quote at the end of query, Update this,
include './connection.php';
$query = "select * from shops WHERE city='pune' AND Ref=1";
$row = mysql_query($query);
$name=$row['sname'];
echo $name;
Please update you're code to MySQLi or PDO.
<?php
include './connection.php';
$query = "select * from shops WHERE city='pune' AND Ref=1";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
echo $row['sname'];
}
?>
Avoid using mysql_* statements. Change your code with -
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM shops WHERE city=? AND Ref=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("si", 'pune', 1);
$stmt->execute();
$stmt->bind_result($col1, $col2);
$array = array();
while ($fetch = $stmt->fetch()) {
$array[] = $fetch;
}
print_r($array);
$stmt->close();
}
$mysqli->close();
I don't know what are you trying to do with this code because it's wrong
Attempting to print $result won't allow access to information in the resource
$row = mysql_query($query);
here the $row is resource
so, One of the mysql result functions must be used. so your code would be
include './connection.php';
$query = "select * from shops WHERE city='pune' AND Ref='1'";
$row = mysql_query($query);
while($ansArray = mysql_fetch_assoc($row)){
echo $name = $ansArray['sname'];
}

Categories