我正在使用mysqli_multi_query
插入用户信息和默认的空个人资料照片,为此有两个表格,"esc_usuarios"
用于个人数据,"esc_usuarios_fotos"
用于照片。
我想要的是,在插入个人数据之后,将此空图像插入与此插入的人的"esc_usuarios_fotos"
表绑定"img_usu_codigo"
中,该人的ID将在{{表"usu_codigo"
中的1}}。
查询:
"esc_usuarios"
答案 0 :(得分:1)
在这里解决一些问题。出于安全原因,您确实应该使用参数化插入。分割出您的插入内容,然后使用insert_id
从您的个人插入内容中获取新创建的ID。像注释中的其他指出的那样包装事务中的所有内容-这将确保您获得所有内容或一无所获。
最后,使用mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
将MySQL错误转换为PHP异常。然后,您可以将所有内容包装在try/catch
块中。祝你好运!
密码:
// Turn MySQL errors into PHP exceptions.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
// Open connection
$connection = new mysqli(...);
// check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Start transaction here
...
/***********************************/
/********** PERSON INSERT **********/
/***********************************/
if ($stmt = $connection->prepare("INSERT INTO `esc_usuarios` ... (?, ?, ...)")) {
/* bind parameters for markers */
$stmt->bind_param("s", $...);
...
/* execute first query */
$stmt->execute();
/* This is the newly created ID */
$id = $connection->insert_id
/***********************************/
/********** PHOTOS INSERT **********/
/***********************************/
if ($stmt = $connection->prepare("INSERT INTO `esc_usuarios_fotos` ... (?, ?)")) {
/* Use that newly created ID here along with other params for your query */
$stmt->bind_param("s", $id);
/* execute query */
$stmt->execute();
}
}
// Commit transaction here
...
}
catch ( Exception $e ) {
// Rollback transaction if the exception is DB related
...
}