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