From PHP to MySQL bind_param() bool error

Davoda 1 :

I cannot fint the error nor could find ideas from the internet. The database has key, userIP, and date. the code segment is:

$last = $conn->query("SELECT LAST_INSERT_ID();");
if (strcmp($last, "<empty string>") == 0) {
    $index = 0;
} else {
    $index = $last + 1;
}

$stmt = $conn->prepare("INSERT INTO Users (key, userIP, date) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $key, $ip, $date);

$key = $index;
$ip = $_SERVER['REMOTE_ADDR'];
$date = date('Y-m-d H:i:s');

The idea is that I save the last "key" and add 1 to it. Tho it doesn't seems to work if the db is empty. I was looking over it for hours so I have ran out on ideas.

Barmar :

You need to fetch the results of the query.

$result = $conn->query("SELECT LAST_INSERT_ID();");
$row = $result->fetch_row();
$last = $row[0];
if ($last == "") {
    $index = 0;
} else {
    $index = $last + 1;
}

But you don't need to perform a query for this, there's a built-in function for it:

$last = $conn->insert_id;

Another problem is that key is a reserved word, so you need to quote it with backticks.

$stmt = $conn->prepare("INSERT INTO Users (`key`, userIP, date) VALUES (?, ?, ?)");

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=216836&siteId=1