使用 PDO 多次 INSERT 到 3 个表中
如何使用通过 for 循环生成 SQL 查询的 PDO 执行 3 个不同的表 INSERT,例如,
我的脚本非常庞大,因此需要将其缩小到代码的主要因素。
$date_sql = '';
for($i = 0; $i < count($_POST['date_range']); $i++)
{
// codez
$date_sql .= " INSERT INTO dates (date_one, date_two) VALUES('" . $_POST['date_range'][$i] . "', '" . $_POST['date_range_end'][$i] . "'); ";
// more codez
}
我有 3 for 循环,与我给出的循环相同,但不同的 $_POST
值和不同的表:months
、年
。它将从 $*_sql
变量生成多行 SQL 查询。
完成 3 个循环后,我将 3 个 sql 变量连接到一个字符串中:
$main_sql = $date_sql . $month_sql . $year_sql;
然后我希望它执行处理它的 SQL 并将值插入到表中,如下所示:
$dbh->beginTransaction();
$sth = $dbh->exec($main_sql);
$dbh->commit();
但这是正确的吗?有效< /em> 这样做的方法?
How can you do a 3 different table INSERTs with the PDO that a SQL query is generated through a for loop, e.g.
My script is well huge so going to narrow it down to the main factors of the code.
$date_sql = '';
for($i = 0; $i < count($_POST['date_range']); $i++)
{
// codez
$date_sql .= " INSERT INTO dates (date_one, date_two) VALUES('" . $_POST['date_range'][$i] . "', '" . $_POST['date_range_end'][$i] . "'); ";
// more codez
}
I have 3 for loops which is same as this loop I've given, but different $_POST
values and different tables: months
, years
. It would generated a multi line SQL query from the $*_sql
variable.
After the 3 loops are done, I join the 3 sql variables into a string:
$main_sql = $date_sql . $month_sql . $year_sql;
Then I want it to execute the SQL that processes it and inserts the values into the tables, like so:
$dbh->beginTransaction();
$sth = $dbh->exec($main_sql);
$dbh->commit();
But is this the right, effective way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更多 PDO 方法是使用准备好的语句。准备好后,您可以多次执行它,只需更改值即可。
The more PDO way of doing this would be to use a prepared statement. After you've prepared it, you can execute it multiple times just changing the values.
您描述的方式将起作用,它将执行三个命令,但由于它们非常小,因此不会对数据库产生太大影响。
另一种方法是格式化一个查询,如下所示:
The way you are descripting will work, it will execute three commands, but since they are very small it will not impact the database that much.
Another way to go would be to format a query that looks like:
不,这不是正确的、首选的和有效的方法。您想查看 PDO 的准备语句:pdo->prepare(),pdoStatement->bindParam(), pdostatement->execute() 和 pdostatement->fetch()一个>
No, this is not the right, preferred and efficient way to do it. You'd like to have a look at PDO's prepared statements: pdo->prepare(), pdoStatement->bindParam(), pdostatement->execute() and pdostatement->fetch()