Hi! Could we please enable some services and cookies to improve your experience and our website?
Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code
<?php
$mysqli->query("create table t (id int primary key unique, stat tinyint default 1)");
// First two blocks use default of
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
echo "mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n";
// Without RETURNING clause.
$stmt = $mysqli->stmt_init();
$stmt->prepare("insert into t (id) values(?)");
$id = 3;
$stmt->bind_param('i',$id);
$stmt->execute();
$stmt->reset();
$id = 3;
try {
$stmt->execute();
echo "This doesn't execute;\n";
} catch (mysqli_sql_exception $e) {
if ($e->getCode() === 1062) {
echo "Without RETURNING: Duplicate id $id\n";
} else {
throw $e; // in case there is any other error
}
}
$stmt->close();
// With RETURNING clause.
$stmt = $mysqli->stmt_init();
$stmt = $mysqli->prepare("insert into t (id) values(?) RETURNING id");
$id = 3;
$stmt->bind_param('i',$id);
$stmt->execute();
$stmt->reset();
$id = 3;
try {
$stmt->execute();
echo "With RETURNING: No exception reported.\n";
} catch (mysqli_sql_exception $e) {
if ($e->getCode() === 1062) {
echo "Duplicate id $id\n";
} else {
throw $e; // in case there is any other error
}
}
$stmt->close();
// Next two blocks use:
mysqli_report(MYSQLI_REPORT_OFF);
echo "\nmysqli_report(MYSQLI_REPORT_OFF);\n";
$stmt = $mysqli->stmt_init();
$stmt->prepare("insert into t (id) values(?)");
$id = 3;
$stmt->bind_param('i',$id);
echo "Without RETURNING: ";
var_dump($stmt->execute());
$stmt->close();
// With RETURNING clause.
$stmt = $mysqli->stmt_init();
$stmt->prepare("insert into t (id) values(?) RETURNING id;");
$id = 3;
$stmt->bind_param('i',$i);
echo "With RETURNING: ";
var_dump($stmt->execute());