-1

I have a prepared statement which I want to execute but I cant understand why is it not working:

$sales_date = date("'Y-m-d H:i:s'");
$cus_id = 1;

$stmt = $db->prepare("INSERT INTO devices (serial_imei,serial_no,type_id,created_date,cus_id,sales_date) VALUES (?,?,?,?,?,?)");
$stmt->bind_param('23fgh455', '234fgh234', 66, $sales_date, $cus_id, $sales_date);
$stmt->execute();
$stmt->close();

Maybe there is something wrong that I cant detect at the moment?!

Dharman
  • 26,923
  • 21
  • 73
  • 125
rtzr
  • 23
  • 6
  • 1
    Are you getting any error message? – Alexey R. May 06 '20 at 16:40
  • Try adding some error handling https://www.php.net/manual/en/mysqli.error.php to check what it complains about. – M. Eriksson May 06 '20 at 16:40
  • 1
    If you look at the [manual about bind_param()](https://www.php.net/manual/en/mysqli-stmt.bind-param.php), you can see that the first argument should be a string with the data types and then the values. Example: `$stmt->bind_param('ssisis', '23fgh455', ...);` – M. Eriksson May 06 '20 at 16:46
  • @MagnusEriksson I tried setting the data types but doesn't work, http error 500 – rtzr May 06 '20 at 16:56
  • @MagnusEriksson I am checking for connection failure but the problem doesn't seem to be there. However, I didn't know how to handle errors in this case for the prepared statement execution. – rtzr May 06 '20 at 16:58
  • @AlexeyR. http error 500 – rtzr May 06 '20 at 16:58
  • You need to check your web servers error log to find the exact error message. You should also post the table schema so we can see what columns the table have, what data types it expects and if any column are required (not allowing null) or we won't have the full picture. – M. Eriksson May 06 '20 at 17:01
  • _"I am checking for connection failure"_ - Connection failure is only one possible issue. The `prepare()` could also fail so you should check for that as well. There are examples in the link I posted. If a prepare fails, it will return a boolean (false) and your next line `$stmt->bind_param(..)` will fail (since you can't use a boolean as an object) – M. Eriksson May 06 '20 at 17:06

1 Answers1

3

First parameter of "bind_param" must be types of binded variables: https://www.php.net/manual/en/mysqli-stmt.bind-param.php

In your case that seems to be "string, string, int, string, int, string", making the correct bind_param call to be:

$stmt->bind_param('ssisis', '23fgh455', '234fgh234', 66, $sales_date, $cus_id, $sales_date);
Kavacky
  • 48
  • 5