php - 插入表 - 用数组替换列名和值
问题描述
两个数组:
$columns = array('mail', 'phone', 'author', 'title');
$values = array('some mail', 'some phone', 'an author', 'a title');
有没有可能是这样的:
$sql = "insert into actual (" . implode(', ', $columns) . ") values (" . implode(', ', $values) . ")";
$st = $db->prepare($sql);
$st->execute(); // line 23
我试过了,在线上出现语法错误23
。
解决方案
要将其编写为带有占位符的准备好的语句,您需要?
对每个字段重复,然后使用bindParam()
(假设为 mysqli)传递值...
$columns = array('mail', 'phone', 'author', 'title');
$values = array('some mail', 'some phone', 'an author', 'a title');
// Create place holders (need to remove last comma - done in build of SQL)
$valuesPlace = str_repeat("?,", count($values));
$sql = "insert into actual (" . implode(', ', $columns) . ")
values (" . rtrim($valuesPlace, ",") . ")";
$st = $db->prepare($sql);
// Bind a list of string values (big assumption)
$st->bindParam(str_repeat("s", count($values)), ...$values);
$st->execute(); // line 23
推荐阅读
- c# - 更改代码以返回集合而不是单个值
- python - 为什么列表理解在 python 中如此流行?
- android - AWS 放大。使用现有资源
- unity3d - 按钮颜色同时显示
- javascript - 为什么我自定义的 Google Analytics 事件没有触发?
- vba - MS Access Forms 数据表以填充另一个表的下拉列表中的所有匹配记录
- javascript - colorScale 属性适用于 VictoryPie 但不适用于 VictoryLegend
- javascript - 如果在 html/javascript 中为空白,如何跳过 json 字段
- java - 使用 java 订阅精确的在线 webhook
- python-3.x - 如何找出文件中有多少行、多少字和多少个字符?