mysqli prepare for update query failed

96 views Asked by At

The following code fails on prepare:

$query = "UPDATE `table` SET `col` = ? WHERE `id` = ?";
if (!($stmt = $mysqli->prepare($query))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
//^^^ PREPARE fails
$stmt->bind_param("si", $val,$id);
if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

I get this: Warning: mysqli::prepare() [mysqli.prepare]: Couldn't fetch mysqli... What am I doing wrong in the code above? I checked the syntax documentation, but if I try to pas the query as an sql I do get a syntax error. Is there a good debugging tool for mysqli syntax errors?

1

There are 1 answers

1
Hasib Mahmud On

You can do the following.

try{
$dbh = new PDO('mysql:host=localhost;dbname=database_name', $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = $dbh->prepare("UPDATE table SET col= ? WHERE id= ?");
$query->bindParam(1, $val);
$query->bindParam(2, $id);
$query->execute();

if (!$query)
 {
  echo "Execution failed";
 }
$query = null;
$dbh = null;
}catch (Exception $ex){
 echo $ex;
}

Hope this will work for you.