0

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();
Tumblewood
  • 73
  • 2
  • 7

2 Answers2

1

You are passing the prepared statement object, not the result, try

$lastPressResult = $lastPressResult -> execute();
$lastPressRow = mysqli_fetch_assoc($lastPressResult);
Fran Cerezo
  • 940
  • 3
  • 8
  • 19
  • Thank you for informing me. I've updated my code to match, but `execute()` still returns false when I run this. – Tumblewood Aug 05 '19 at 01:56
  • Paste your CREATE TABLE statement, please, maybe the field is not wide enough or is unsigned. – Fran Cerezo Aug 05 '19 at 02:13
  • I'm not sure what you mean by "field is not wide enough or is unsigned" but I do know that the same query works with mysqli_query() and no preparation. EDIT: I thought earlier that execute was returning false, `echo $lastPressResult;` returns true (or rather, 1). – Tumblewood Aug 05 '19 at 03:28
0

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();
Tumblewood
  • 73
  • 2
  • 7