see bottom for the code that worked
I have a page that checks the last time a user pressed a button from the user's current IP address. The code looks like this:
$lastPressQuery = "SELECT MAX(tstamp) AS 'last_press' FROM presses WHERE ip = $ipNum";
$lastPressResult = mysqli_query($conn, $lastPressQuery);
$lastPressRow = mysqli_fetch_assoc($lastPressResult);
( $ipNum
is converted using ip2long)
This code works as intended. However, in line with best practices, I would like to change this to a prepared statement. This is the code I wrote for the prepared statement:
$lastPressQuery = $conn -> prepare("SELECT MAX(tstamp) AS 'last_press' FROM presses WHERE ip = ?");
$lastPressQuery -> bind_param("i", $ipNum);
$lastPressResult = $lastPressQuery -> execute();
$lastPressRow = mysqli_fetch_assoc($lastPressResult);
This does not work. execute()
returns false.
I have tried leaving the IP address as a string, leaving $ip
as a string and putting apostrophes around it or the question mark, checking ipNum
for mistakes, and entering the query it should create directly into SQL (which works). A later prepared statement to INSERT
data works fine. What is causing this prepared statement to fail?
EDIT: I finally got this to work. The code that succeeded is:
$lastPressQuery = $conn -> prepare("SELECT MAX(tstamp) AS 'last_press' FROM presses WHERE ip = ?");
$lastPressQuery -> bind_param("i", $ipNum);
$lastPressQuery -> execute();
$lastPressResult = $lastPressQuery -> get_result();
You are passing the prepared statement object, not the result, try
$lastPressResult = $lastPressResult -> execute();
$lastPressRow = mysqli_fetch_assoc($lastPressResult);
The code that succeeded is:
$lastPressQuery = $conn -> prepare("SELECT MAX(tstamp) AS 'last_press' FROM presses WHERE ip = ?");
$lastPressQuery -> bind_param("i", $ipNum);
$lastPressQuery -> execute();
$lastPressResult = $lastPressQuery -> get_result();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.