我有桌子:平台
在此表格列中:1。first_scan_date,2。next_scan_date 3. scan_frequency
现在,我从基于Web的公式得到了这样的数组:
Array
(
[scan_freq1] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
)
[first_scan_date1] => Array
(
[0] => 0000-00-00
[1] => 0000-00-00
[2] => 0000-00-00
[3] => 0000-00-00
)
[next_scan_date1] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
)
)
如何使用来自PHP数组的内容在数据库中更新?我想我需要像foreach一样的smth,但不知道......
UPDATE平台(first_scan_date,next_scan_date,scan_frequency)VALUES(?,?,?)......
帮助?
答案 0 :(得分:1)
尝试以下方式
$cnt = count($arr['scan_freq1']);
for($i=0;$i<$cnt;$i++){
echo $arr['scan_freq1'][$i];
echo $arr['first_scan_date1'][$i];
echo $arr['next_scan_date1'][$i];
//now you have three values make query and update into db
$db->prepare(
"UPDATE `platforms` SET `first_scan_date`=?, `next_scan_date`=?,
`scan_frequency`= ? WHERE platformtype='os'"
)->execute(array($arr['first_scan_date1'][$i],$arr['next_scan_date1'][$i],$arr['scan_freq1'][$i]));
}
答案 1 :(得分:1)
我会循环遍历数组,准备一个字符串,插入一个查询中,如下所示:
$sql = "INSERT INTO table (first_scan_date,next_scan_date,scan_frequency)
VALUES ('0000-00-00','0000-00-00',1),('0000-00-00','0000-00-00',1),('0000-00-00','0000-00-00',1)
ON DUPLICATE KEY UPDATE first_scan_date=VALUES(first_scan_date),next_scan_date=VALUES(next_scan_date),scan_frequency=VALUES(scan_frequency);";
你可以这样做:
$freq = $arr['scan_freq1'];
$date1 = $arr['first_scan_date1'];
$date2 = $arr['next_scan_date1'];
foreach ($date1 as $key => $value){
$row[] = "('".$value."','".$date2[$key]."',".$freq[$key].")";
}
$list = implode(',', $row);
$sql = "INSERT INTO table (first_scan_date,next_scan_date,scan_frequency)
VALUES ".$list."
ON DUPLICATE KEY UPDATE first_scan_date=VALUES(first_scan_date),next_scan_date=VALUES(next_scan_date),scan_frequency=VALUES(scan_frequency);";
答案 2 :(得分:0)
这可能会晚了,但可能会在现在或将来对某人有所帮助,我相信这是实现此目标的最短途径
public function update($table,$values,$where_clause)
{
foreach ($values as $key => $val)
{
$valstr[] = $key." = '$val'";
}
$update_query = 'UPDATE '.$table.' SET '.implode(', ', $valstr)
." WHERE ".$where_clause;
return $update_query;
}
在一个codeigniters核心文件中找到它,它只是循环遍历所有值 将它们存储在数组中,然后将其转换为字符串,并将其添加到查询中,where子句排在最后。.我希望这对某人有帮助