我有一个Bash / PHP脚本,它从名为'assess_2012'的表中检索记录,并将需要写入的记录存储在多维数组中名为'assess_2012_err'的表中:
#!/usr/bin/php -q
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$name = "reassess";
$conn = mysqli_connect($host, $user, $pass, $name) OR die ("Could not connect to database: " . mysqli_error($conn) . "\n");
$q = "SELECT su_id, ass_date, ind_d FROM assess_2012";
$r = mysqli_query ($conn, $q);
if ($r) {
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
// Check for errors:
if ($row['ind_d'] == 'Y') {
// Add to the array:
$sql[] = array('su_id' => $row['su_id'], 'err_code' => 1);
}
}
var_dump($sql);
}
else {
// SELECT query failed:
echo "Error: " . mysqli_error($conn) . "\n";
}
?>
'var_dump'看起来像这样(缩短版本 - 实际查询返回数百条记录):
array(1) {
[0]=>
array(2)
["su_id"]=>
string(1) "5"
["err_code"]=>
int(1)
}
[1]=>
array(2) {
["su_id"]=>
string(4) "1492"
["err_code"]=>
int(1)
}
}
我无法弄清楚我是如何使用数组来生成这样的查询:
INSERT INTO assess_2012_err (su_id, err_code) VALUES (5, 1), (1492, 1)
答案 0 :(得分:2)
在将值输入数据库时,使用foreach循环循环数据。
像:
foreach($sql as $key=>$value){
foreach($value as $key_p=>$value_p){
//Implement Query here
//R.g
//$key will have 'su_id'
//$value_p will have 1
}
}
答案 1 :(得分:1)
你最好一个接一个地做,
foreach($sql as $variables)
{
// Insert here:
INSERT INTO asses_2012_err (su_id, err_code) VALUES ($variables['su_id'], $variables['err_code']);
}
要记住一些重要的事情: