我试图摆脱尾随逗号我的sql statemen使用trim但它似乎无法正常工作
if(isset($_POST['report'])){
//====
$sql = 'INSERT INTO weekly_repo ( hospnme, disease, week, under5, above5, dat) VALUES ';
$week = intval($_POST['current_week']);
$diseases = $_POST['diseases'];
foreach($diseases as $disease){
$sql .= ' ( "' . filterString($_POST['hospital']). '", "' . filterString($disease['disease']) . '", ' . $week . ', ' . intval($disease['under_5']) . ', ' . intval($disease['over_5']) . ', NOW()), ';
}
$sql = trim($sql, '\,');
// ended up doing this
//$sql = substr($sql, 0, strrpos($sql, ',')) . ';';
$stmt = $conn->query($sql);
}
答案 0 :(得分:2)
您不需要逃脱逗号\
。更好的方法可能是构造一个数组然后implode()
:
foreach($diseases as $disease){
$sql[] = ' ( "' . filterString($_POST['hospital']). '", "' . filterString($disease['disease']) . '", ' . $week . ', ' . intval($disease['under_5']) . ', ' . intval($disease['over_5']) . ', NOW()), ';
}
$sql = implode(',', $sql);