I want to fetch this row and save it into $notescheck, but when I try to do this the $notescheck is empty when I want to echo and there are no errors. With non-prepared statements it works fine.
Code:
if($user_ok == true) {
$sql = "SELECT notescheck FROM users WHERE username=? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$log_username);
$stmt->execute();
$row = $stmt->fetch();
$notescheck = $row[0];
$stmt->close();
}
With non-prepared statement it would look like this:
if($user_ok == true) {
$sql = "SELECT notescheck FROM users WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_row($query);
$notescheck = $row[0];
mysqli_close($conn);
}
This isn't how fetch() works with prepared statements, you're not fetching an array like you think you are. You also need to bind the result of the select into variables, then use those to display. If there are multiple records, you'd use a while($stmt->fetch){ echo $notescheck };
if($user_ok == true) {
$sql = "SELECT notescheck FROM users WHERE username=? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$log_username);
$stmt->execute();
$stmt->bind_result($notescheck);
$stmt->fetch();
$stmt->close();
}
echo $notescheck;
You should check into reading this:
http://php.net/manual/en/mysqli-stmt.fetch.php
Multiple records matching username=x would look like this:
if($user_ok == true) {
$sql = "SELECT notescheck FROM users WHERE username=? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$log_username);
$stmt->execute();
$stmt->bind_result($notescheck);
$stmt->store_result()
while($stmt->fetch()){
echo $notescheck;
}
$stmt->close();
}
Related
In the following code i am trying to fetch only the newest datetime from a sql table full of email adresses (which are all the same) and datetimes, using a prepared statement:
$sql = "SELECT * FROM usertokens WHERE user_mail = ?;";
//Create a prepared statement
$stmt = mysqli_stmt_init($conn);
//prepare prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL failed";
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "s", $email);
//run params
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if ($row = mysqli_fetch_assoc($result)) {
$dt = date_create_from_format('Y-m-d H:i:s', $row['user_date']);
}}
At the moment it fetches only the first entry. How can i select the newest date time(and i do not want to select the lowest entry)? The table would look like this:
:---user_mail---------user_date---------
:-----------------------------------------------
:---some#mail.com----2018-06-06 20:28:16
:---some#mail.com----2018-06-06 20:31:24
:---some#mail.com----2018-06-06 20:33:44
You can use ORDER BY and LIMIT to accomplish this goal:
$sql = "SELECT * FROM usertokens WHERE user_mail = ? ORDER BY user_date DESC LIMIT 1;";
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->store_result();
if ($stmt->affected_rows > 0) {
echo "Exists";
}
Instead of echoing out Exists, I want it to echo out nameData. How can I go about doing that?
First of all, if you want only one row then append LIMIT 1 to your SELECT query, like this:
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
So there are two approaches to display nameData:
Method(1):
First bind the variable $nameData to the prepared statement, and then fetch the result into this bound variable.
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows){
$stmt->bind_result($nameData);
$stmt->fetch();
echo $nameData;
}else{
echo "No result found";
}
Method(2):
First use get_result() method to get the result set from the prepared statement, and then use fetch_array to fetch the result row from the result set.
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
$stmt->bind_param("s", $query);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows){
$row = $result->fetch_array()
echo $row['nameData'];
}else{
echo "No result found";
}
I think you can below code i hope your query is working fine it returns result properly then you can use below code.
$stmt->bind_result($nameData);
if ($stmt->fetch()) {
printf ("%s\n", $nameData);
}
Note that affected_rows won't do anything useful here.
However, nor you don't need num_rows as well (and therefore store_result too)
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->bind_result($nameData);
$stmt->fetch();
echo $nameData;
Considering all that hassle, even without useless functions, you may find PDO a way better approach:
$stmt = $pdo->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->execute($query);
echo->$stmt->fetchColumn();
This is my simple query in php, using mysqli object oriented style:
$query = "SELECT name FROM usertable WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i', $id);
$id= $_GET['id'];
$stmt->execute();
$stmt->bind_result($name);
while($stmt->fetch()){
echo $name." ";
}
$stmt->free_result();
$stmt->close();
This works fine. I obtain the list of name retrieved from the select statement.
Now, inside the while I want use the $name variable as parameter for another query, but mysqli do not allow this, since I have to close the first query and then call the second query.
So I think I have to store the result of the first query and then iterate over the result calling a new query.
I have tried the following:
$query = "SELECT name FROM usertable WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i', $id);
$id= $_GET['id'];
$stmt->execute();
//$stmt->bind_result($name);
$result = $stmt->store_result();
$stmt->free_result();
$stmt->close();
while ($row = $result->fetch_row())
{
echo $row[0]." ";
}
But this does not work. The code inside while is never reached.
N.B.: I want avoid the use of multi_query().
mysqli_stmt::store_result return a boolean. According to the doc it should be something like:
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($name);
while($stmt->fetch()){
//echo $name." ";
// try another statement
$query = "INSERT INTO usertable ...";
$stmt2 = $mysqli->prepare($query);
...
}
$stmt->free_result();
$stmt->close();
If this doesn't work you can fetch all rows first into an array and then looping that array again:
$stmt->execute();
$stmt->bind_result($name);
$names = array();
while($stmt->fetch()){
$names[] = $name;
}
$stmt->free_result();
$stmt->close();
foreach($names as $name) {
$query = "INSERT INTO usertable ...";
$stmt = $mysqli->prepare($query);
...
}
I have solved the problem:
$query = "SELECT name FROM usertable WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i', $id);
$id= $_GET['id'];
$stmt->execute();
$result = $stmt->get_result();
$stmt->free_result();
$stmt->close();
while ($row = $result->fetch_array(MYSQLI_NUM))
{
echo $row[0]." ";
}
Simply using get_result() and fetch_array()
I am trying to find out how to make my code work with prepared statements. I understood the entire process up to where I commented my code. What do I have to do in order to integrate num_rows and the mysqli_query part properly?
function login_check() {
global $connection;
$name = $_POST['name'];
$password = $_POST['password'];
$query = "SELECT id FROM members WHERE name = $name AND password = $password";
$stmt = $connection->prepare($query);
$stmt->bind_param('ss', $name, $password);
$stmt->execute();
$stmt->close();
// $result = mysqli_query($connection, $query);
// $rows = mysqli_num_rows($result);
if($rows > 0){
header('location:../../success.php');
exit;
}
else {
header('location:../../failed.php');
exit;
}
}
What I tried:
$result = mysqli_query($connection, $stmt);
$rows = mysqli_num_rows($result);
Change
$query = "SELECT id FROM members WHERE name = $name AND password = $password";
to
$query = "SELECT `id` FROM `members` WHERE `name` = ? AND `password` = ?";
Adding backticks around table and columns prevents mysql reserved words error.
Remove $stmt->close();
if( $stmt->num_rows > 0 ) {
$stmt->close();
header('location:../../success.php');
exit();
} else {
$stmt->close();
header('location:../../failed.php');
exit();
}
Adding $stmt->close() inside if statement before header is best practice in this case.
Becasue adding it before if statement would result in $stmt->num_rows always returning 0; Adding it after the if statment won't work because exit() would prefent it from executing.
From the documentation:
Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.
trying to convert all my old mysql_* operations into new and, from what i've heard, improved PDO, but this query wont seem to run successfully, I am trying to select all from the table PEOPLE where the username = $username (which has previously been declared $username = $_SESSION['username'];)
$query = "SELECT * FROM people WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
if ($num_rows == 1) {
// ...
}
THE WORKING CODE IS:
$query = "SELECT * FROM people
WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
$user = $stmt->fetchObject();
if ($user) {
//do something
}
$stmt->fetchColumn does not fetch the number of rows; in this case it will fetch the first column from the first row of the result set. Since that will not be equal to 1 generally your test will fail.
In this case there is also no real need to count the number of returned rows because you are expecting either one or zero (if the username does not exist). So you can simply do:
$stmt->execute();
$user = $stmt->fetchObject();
if (!$user) {
// not found
}
else {
echo "User $user->username found!";
}
The if(!$user) test works because if there is no row to fetch $user will be false (see the documentation for fetchObject).
$query = "SELECT * FROM people WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->execute();
while ($row = $stmt->fetchObject()) {
// do stuff
}
Use PDOStatement::rowCount as the num_rows and PDOStatement::fetch(PDO::FETCH_ASSOC) as fetch_assoc equivalent.
You want
if ($stmt->num_rows == 1) {
instead.