php: how to fetch newest datetime from sql database using prepared statement? - php

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;";

Related

Why can't I get data from SQL row using PHP prepared statements?

Connection is good. I can insert into the database, and check if a row exists by checking if results > 0, but I can not select row data. The $email's being tested are in the database.
Ex 1.
require 'connection/connection.php';
$email = "sample#sample.com";
$sql = "SELECT * FROM users WHERE user_email=?"; // SQL with parameters
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$user = $result->fetch_assoc(); // fetch data
echo $user['user_name'];
Ex. 2
$email = "james#james.com";
$sql = "SELECT * FROM users WHERE user_email=?";
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
After inserting an echo after every line one by one, this is as far as it gets. If an echo statement is placed after the next line it will not appear.
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$_SESSION['active_user_id'] = $row['user_id'];
} else {
header("Location: https://example.com/");
exit();
}
The problem was fixed through cPanel. I had to switch from "mysqli" to "nd_mysqli." This fixed the problem right away.
I found the instructions to do this here https://www.plus2net.com/php_tutorial/mysqli_mysqlnd.php
I hope this helps others with the same problem.

PHP MySQLi Parameterized Query not functioning

I am updating my current unprotected queries to parameterized ones to protect from SQL Injection.
I have spent a few hours trying to sort this however cant find the issue, any help much appreciated.
BEFORE (echo $row['storeID'];) works before
$storeName = mysqli_real_escape_string($conn,$_GET['store']);
$query = "SELECT * FROM stores WHERE storeName = '$storeName'";
$results = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($results);
AFTER
$storeName = $_GET['store'];
$stmt = mysqli_prepare($conn, "SELECT * FROM stores WHERE storeName = ?");
mysqli_stmt_bind_param($stmt, "s", $storeName);
mysqli_stmt_execute($stmt);
$row = mysqli_stmt_fetch($stmt);
This echo should work but using statements it does not
echo $row['storeID'];
If you look at the documentation for mysqli_stmt_fetch you'll see this description:
Fetch results from a prepared statement into the bound variables
So if you want to go this route, you'll need to ue mysqli_stmt_bind_result as well:
$storeName = $_GET['store'];
$stmt = mysqli_prepare($conn, "SELECT * FROM stores WHERE storeName = ?");
mysqli_stmt_bind_param($stmt, "s", $storeName);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $col1, $col2, $col3,...);
while (mysqli_stmt_fetch($stmt)) {
// do stuff with $col1, $col2, etc.
}
Now, with each iteration of the loop, the bound result variables are given the value from the result set.
However, I'd strongly suggest moving to PDO, which is far less verbose:
$storeName = $_GET['store'];
$stmt = $db->prepare("SELECT * FROM stores WHERE storeName = ?");
$stmt->execute([$storeName]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// now you have a simple array with all your results
foreach ($rows as $row) {
// do stuff with $row
}
You were missing a call to mysqli_stmt_get_result before fetching the row:
$storeName = $_GET['store'];
$stmt = mysqli_prepare($conn, "SELECT * FROM stores WHERE storeName = ?");
mysqli_stmt_bind_param($stmt, "s", $storeName);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
echo $row['id'];

Binding the same variable more than once for mysqli

I have a site in which I need to rewrite all the SQL to be prepared statements in the MySQLi Prepared format.
Similar to the below
$sql = "SELECT * FROM jobs WHERE Job_Id = ?";
// Prepare statement
$stmt = $dbcon->prepare($sql);
// Bind parameters
$stmt->bind_param('i', $Job_Id);
// Execute statement
$stmt->execute();
// Bind result
$result = $stmt->get_result();
if($result->num_rows >= 1){
while($row = $result->fetch_assoc()){
}
}
I came across this line:
UPDATE jobs SET jobTitle = IF('$jobTitle' = '', jobTitle, '$jobTitle'),
How would this query line be represented in a prepared statement? Surely all the variables would be replaced with ?, but then do I have to re-use the same variable and have more placeholders?

store sql statement in MySQL then run it

Is it possible to store the following SQL statement in MySQL then run it in a prepared statement?
Mysql table:
Table name: mystatements
Columns:id, statements
The following syntax is stored in the statements field:
SELECT id, AES_DECRYPT(secret,'$key') as txtsecret
FROM TABLE_1
Now in php:
first: I do a select query to get my statement
$stmt = $mysqli->prepare("SELECT statements FROM mystatements limit 1");
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$statement.=$row['txtstatement'];
}
second: using the variable ($statement) from the the query above and add it to query below to run the in the prepared statement:
$key='password123';
$stmt = $mysqli->prepare($statement);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['txtsecret'];
}
Also my stored syntax contains AES_DECRYPT(secret,'$key') just to complicate things. is what i'm trying to achieve possible? have I gone about this completely the wrong way?
Ok..
$key='password123';
$sql = str_replace('$key', $key, $statement); //replace $key to correct value
$stmt = $mysqli->prepare($sql);
Result:
SELECT id, AES_DECRYPT(secret,'$key') as txtsecret FROM TABLE_1
to
SELECT id, AES_DECRYPT(secret,'password123') as txtsecret FROM TABLE_1

Prepared statement fetch row returns nothing

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();
}

Categories