且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

一次将值插入到多个 MySQL 表中

更新时间:2022-04-02 08:35:33

看起来您正在使用 mysqli 作为数据库库,因此您可以使用 $db->insert_id() 以检索由该特定数据库句柄的插入操作创建的 LAST id.所以你的查询会变成:

Looks like you're using mysqli as the DB library, so you can use $db->insert_id() to retrieve the LAST id created by an insert operation by that particular DB handle. So your queries would become:

$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$switch'") or die($db->error);
$new_id = $db->insert_id();
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ($new_id, '$title', '$content'") or die($db->error);           
                                                                    ^^^^^^^

您无法在单个查询中真正做到这一点,因为在查询完成之前,mysql 不会为 insert_id 函数提供 ID 值.因此,您必须分 3 个步骤执行此操作:插入、获取 id、再次插入.

You can't really do it in a single query, as mysql does not make the ID value available for the insert_id function until AFTER the query completes. So you do have to do this in a 3 step process: insert, get id, insert again.

数据库过滤的规则(更好地称为转义)是转义用户提供的任何内容.这甚至包括您在其他数据库查询中检索并重新插入的数据.转义并不是真正的安全措施——它是为了确保您放入查询字符串的任何内容都不会破​​坏查询.防止 SQL 注入攻击只是这个的副作用.

The rule for DB filtering (better known as escaping) is to escape ANYTHING that's user-provided. This even includes data you've retrieve in other db queries and are re-inserting. Escaping isn't really there as a security measure - it's there to make sure that whatever you're putting into the query string doesn't BREAK the query. Preventing SQL injection attacks is just a side effect of this.