我需要将现有项目从 mysql 转换为 mysqli 并使用准备好的语句。
在现有项目中有使用重复变量值的查询。一个这样的例子是: $prev_yr 被使用了 3 次。
$sqlins = "Insert into studentclass (`StudentID`, `ClassID`, `Year`, `Level`, `SNo`, `TermList`, `DateStart`, `DateEnd`)
select StudentID, '$prev_cl', '$prev_yr', '$prev_lvl', '', '123456789', '$prev_yr-01-01', '$prev_yr-12-31' from student Where StudentID in ($ids) ";
有没有比这更好的方法:
$sqlins = "Insert into studentclass (`StudentID`, `ClassID`, `Year`, `Level`, `SNo`, `TermList`, `DateStart`, `DateEnd`)
select StudentID, '?', '?', '?', '', '123456789', '?-01-01', '?-12-31' from student Where StudentID in (?) ";
$stmt = $mysqli->prepare($sqlins);
$stmt->bind_param("ssssss", $prev_cl,$prev_yr,$prev_lvl,$prev_yr,$prev_yr,$ids);
$stmt->execute();
我想知道是否有一种方法可以为所有 3 次绑定 $prev_yr 一次。
因为还有其他查询可能在一个语句中出现 2 次 $prev_lvl、5 次 $prev_yr 等。这个想法是,当多个变量的重复出现在一个语句中变得很多时 - 在 bind_param 中安排它们变得非常混乱。
有什么解决办法吗?谢谢你。
它甚至像那样工作吗,典型的你不会'?-01-01'
在查询中这样做。我已经有大约 4 年没有使用过 Mysqli,因为我现在每天使用的都是 PDO。但据我所知,当你把它送去准备时,它会吐在?
绳子里的人身上。
我会拆分它,实际上没有必要进行选择,因为唯一被选择的是您已经拥有的学生 ID。简单地
$insert = $mysqli->prepare("Insert into studentclass (`StudentID`, `ClassID`, `Year`, `Level`, `SNo`, `TermList`, `DateStart`, `DateEnd`)VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
foreach( $ids AS $id ){
$stmt->bind_param("issssiss", $id, $prev_cl,$prev_yr,$prev_lvl,'', '123456789', $prev_yr.'-01-01',$prev_yr.'-12-31');
$stmt->execute();
}
我无法测试它,所以希望我把所有东西都放在正确的地方。
正如我所说,我认为您不能绑定到Fields
查询的一部分,当然也不能绑定到部分字符串中,除了它进行了不需要的选择。只需确保在循环之前准备插入。
只是为了清楚选择实际上从数据库中获得的唯一东西是这个
select StudentID ... from student Where StudentID in (?)
其余的添加为“假”列,我不知道它的术语。很难阅读原始查询..
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句