FIndng the exact value in a table in PHP Issue [duplicate] - php

I have this code.
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s',$username);
//$username = $_POST["username"];
$username ="netsgets";
$stmt->execute();
$stmt->store_result();
var_dump(stmt['likedFour']);
According to table UserData, likeFour should equal 'empty'. For some reason, var_dump(stmt['likedFour']); is returning the string 's'. Why is this?
Edit (this is what you told me to do but it is not working):
when I run this the script stops at the var_dump.
require "conn.php";
echo "debug 1";
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s',$username);
//$username = $_POST["username"];
$username ="netsgets";
$stmt->execute();
$row = $stmt->fetch_assoc();
var_dump($row['likedFour']);

Why does var_dump(stmt['likedFour']); return 's':
Because you're missing the dollar sign before stmt, so PHP thinks you're trying to access the constant stmt instead of the variable $stmt. Since you haven't defined that constant, it will fall back to assuming you're trying to access the string "stmt". For strings, indices must be numeric so PHP should be throwing you an "Illegal string offset" warning but will try to fix it for you by casting 'likedFour' to an integer (which will be 0).
Therefore, var_dump(stmt['likedFour']) means the exact same thing as var_dump("stmt"[0]) to PHP, which is why you're getting the output "s": the first character from "stmt".
How to get the result you actually want:
You first need to retrieve the resulting rows from your query. $stmt is the mysqli_stmt object that you use to execute the query and retrieve the results, it is not actually the result itself.
To save yourself headaches in the future, always check whether your query even executed successfully before trying to retrieve the results. Then fetch the row of data:
$success = $stmt->execute();
if (!$success) {
echo $stmt->error;
} else if ($stmt->num_rows == 0) {
echo 'No results matching that username';
} else {
$result = $stmt->get_result();
$row = $result->fetch_assoc();
var_dump($row['likedFour']);
}
If you don't know how many rows will be returned, loop through them just to be safe:
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
var_dump($row['likedFour']);
}

Related

php oop statement->execute returns boolean

so I have the following method:
public function checkLogin($username){
$sql_login=$this->dbc->prepare("SELECT username FROM credentials WHERE username=?");
$sql_login->bind_param("s", $username);
$stmt=$sql_login->execute();
$result = $stmt->get_result();
return $result;
}
By doing a var_dump (and removing $result = $stmt->get_result();) I can see that $stmt is passing a boolean.
I'm new to OOP in php. I'm thinking that get_result() function should get the result of the $stmt execution.
What am I doing wrong please ?
$result = $stmt->get_result(); converts a mysqli::statement object into a mysqli::result object, it does not return any rows from the resultset
You are also using the returned value from $sql_login->execute(); which is in fact just a boolean instead of the statement object called $sql_login in your case i.e. $result = $sql_login->get_result();
So you need to add something to actually fetch the row that was returned by the query, for example $row = $result->fetch_assoc(); like this
public function checkLogin($username){
$sql_login=$this->dbc->prepare("SELECT username
FROM credentials
WHERE username=?");
$sql_login->bind_param("s", $username);
$sql_login->execute();
$result = $sql_login->get_result();
$row = $result->fetch_assoc(); // fetch the row as an assoc array
return $row;
}

All values = 's' in table in PHP error

I have this code.
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s',$username);
//$username = $_POST["username"];
$username ="netsgets";
$stmt->execute();
$stmt->store_result();
var_dump(stmt['likedFour']);
According to table UserData, likeFour should equal 'empty'. For some reason, var_dump(stmt['likedFour']); is returning the string 's'. Why is this?
Edit (this is what you told me to do but it is not working):
when I run this the script stops at the var_dump.
require "conn.php";
echo "debug 1";
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s',$username);
//$username = $_POST["username"];
$username ="netsgets";
$stmt->execute();
$row = $stmt->fetch_assoc();
var_dump($row['likedFour']);
Why does var_dump(stmt['likedFour']); return 's':
Because you're missing the dollar sign before stmt, so PHP thinks you're trying to access the constant stmt instead of the variable $stmt. Since you haven't defined that constant, it will fall back to assuming you're trying to access the string "stmt". For strings, indices must be numeric so PHP should be throwing you an "Illegal string offset" warning but will try to fix it for you by casting 'likedFour' to an integer (which will be 0).
Therefore, var_dump(stmt['likedFour']) means the exact same thing as var_dump("stmt"[0]) to PHP, which is why you're getting the output "s": the first character from "stmt".
How to get the result you actually want:
You first need to retrieve the resulting rows from your query. $stmt is the mysqli_stmt object that you use to execute the query and retrieve the results, it is not actually the result itself.
To save yourself headaches in the future, always check whether your query even executed successfully before trying to retrieve the results. Then fetch the row of data:
$success = $stmt->execute();
if (!$success) {
echo $stmt->error;
} else if ($stmt->num_rows == 0) {
echo 'No results matching that username';
} else {
$result = $stmt->get_result();
$row = $result->fetch_assoc();
var_dump($row['likedFour']);
}
If you don't know how many rows will be returned, loop through them just to be safe:
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
var_dump($row['likedFour']);
}

Unable to get value from a PDO array

I am fairly new to PHP and have been following the Lynda.com tutorials (although they still use mysql in stead of mysqli or PDO).
I'm having problems with using the data I get from my queries.
I'll use my login page as example, leaving out the connect to db part:
$login_username = trim(htmlspecialchars($_POST['username']));
$password = trim(htmlspecialchars($_POST['password'])); // from login form
$stmt = $db->prepare("SELECT * FROM users
WHERE username = :login_username");
$stmt->bindParam(':login_username', $login_username);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0 && $result = password_verify($password,$result['hashed_password'])) {
$_SESSION['logged_in_id'] = $result['id'];
$_SESSION['logged_in_username'] = $login_username; //this was the only way I could pass the username as I could not get it from $result['username']
$_SESSION['first_name'] = $result['first_name'];
$_SESSION['last_name'] = $result['last_name'];
Nothing gets passed to the session and there are no errors. I also can't echo out the value of $result. If I just try to echo $result, then I just get the value 1
Please help!
Your problem is:
... && $result = password_verify($password,$result['hashed_password'])
Note that $result is an array that contains the row that you just fetched and you are assigning it a new value here; you are overwriting your $result variable so all assignments afterwards will fail.
You probably want something like:
... && password_verify($password,$result['hashed_password'])
Also note that you should not rely on the rowCount() as that is not necessarily what you expect for a SELECT statement.
As you are fetching a row already, you can simply do:
if ($result && password_verify($password,$result['hashed_password']))
If there is no result, the second condition will never be checked so it will not lead to warnings or errors.

PHP How to echo the result of a fetch outside a while-loop

I am new to Object Oriented PHP. Currently I am making a login script and am stuck at fetching & echo'ing the results. This is my script:
$stmt = $db->mysqli->prepare("select User from `users` where User = ? AND Password = ?");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->store_result();
$num = $stmt->num_rows;
$stmt->bind_result($username);
if ( $num !== 1 ) {
echo 'no result';
} else {
echo 'Your username: '. $username ;
}
$stmt->close();
As you can see I am not fetching a result in the script above. I tried using $stmt->fetch() in a while-loop prior to the $num !== 1.
However, the result of the fetching is "stored" as an array (I think), even though inside the while loop you don't use an array (just $username). What I want: echo the result of the select query OUTSIDE a while loop. Just as it is possible in the old fashioned way (assuming there is only 1 result, therefore no while-loop necessary):
$result = mysqli_query( $conn, $query );
$record = mysqli_fetch_array( $result );
echo $record['username'];
You need to accses to object variable:
echo $stmt->User;
Or you can save variable for later:
$user = $stmt->User;
After ending of your loop your $user will hold the value.
You can use $stmt->get_result() to do that, e.g.
$stmt->execute();
$result = $stmt->get_result();
$record = $result->fetch_assoc();
echo $record['username'];
Edit
Another method is to call fetch after bind_result
$stmt->bind_result($username);
$stmt->fetch()
echo $username;
Old fashion way:
print_r($record);
From the php manual: print_r

MySQLi num_rows returns 0

Here's my code
$stmt = $conn->mysqli->stmt_init();
$stmt = $conn->mysqli->prepare('SELECT Username, EmailVerified, Blocked FROM user WHERE Email = ? AND SLANumber = ? AND Password = ?');
$stmt->bind_param('ssb', $_POST['EmailID'], $_POST['SLANumber'], $_POST['Password']);
$stmt->execute();
$stmt->store_result();
$result = $stmt->get_result();
if($result->num_rows == 0){
echo 'No rows found';
}
else{
// Continue processing here
.....
}
The code always echoes No rows found. A day or two before, it was working fine.
As expected, running the query directly gives the desired result.
What's wrong with the code?
Don't use store_result and get_result together in the same statement.
Use store_result method with "num_rows", "bind_result" and "fetch".
For get_result method, use "affected_rows" and "fetch_array". You can still use the "num_rows" property in the income get_result method as shown below.
$stmt->execute();
// $stmt->store_result();
$result = $stmt->get_result();
if(result->num_rows == 0){
...
}
OR
$stmt->execute();
// $stmt->store_result();
$result = $stmt->get_result();
if($stmt->affected_rows == 0){
...
}
To fix your problem remove this line:
$stmt->store_result();
The problem is that you used two methods which are in conflict with each other.
$stmt->store_result();
$result = $stmt->get_result();
Both of these methods fetch the results. store_result() fetches the results internally and stores them in the statement object. I would advise to avoid this method whenever possible. It is difficult to use. get_result() fetches the results and saves them in a separate object. Once the results are fetched from MySQL, they cannot be fetched again. Use only one of these methods at a time.
In your case you first stored the results in mysqli_stmt and then fetched an empty result set into $result. $result will contain 0 rows, because all of the records have already been stored in the statement. To get the number of rows stored there use $stmt->num_rows.
Both mysqli_stmt and mysqli_result classes have the num_rows property. The key is to use the appropriate one.
num_rows is a property of mysqli_stmt, not of a result resource. So you should be doing:
$result = $stmt->get_result();
// Also check strict comparison against int 0,
// to avoid incorrect equality with boolean FALSE
if($stmt->num_rows === 0){
echo 'No rows found';
}

Categories