我想创建一个可以插入到 SQL 查询中的数组或变量,而不是像下面的代码那样手动执行。
这是否可以通过简单的 php 实现,而不是使用 PDO,只是使用某种技巧来解决这个问题。
您可以看到我手动插入了 10 列和 10 个值,我可以做得更短吗? 所以,我想要一个由 pt1-pt10 组成的变量/数组,另一个由 a[1]-a[10] 组成。
for($j=1;$j<11;$j++) {
$a[$j] = "";
}
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'my_db';
$table = 'jos_answers';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("INSERT into ".$table."(id, title, pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8, pt9, pt10) VALUES ((select id from jos_content where title='$title'),'$title','$a[1]','$a[2]','$a[3]','$a[4]','$a[5]','$a[6]','$a[7]','$a[8]','$a[9]','$a[10]')");
?>
最佳答案
for($j=1;$j<11;$j++) {
$a["pt".$j] = $j;
}
"INSERT into ".$table. "(id, title,".implode(",", array_keys(a)).") VALUES ((select id from jos_content where title='$title'),'$title',".implode(",", array_values(a)).")";
关于php - 使用 php 从 for 循环创建变量并将其插入到 mysql 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23300637/