首页 > 解决方案 > 插入表 - 用数组替换列名和值

问题描述

两个数组:

$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

标签: phpmysql

解决方案


要将其编写为带有占位符的准备好的语句,您需要?对每个字段重复,然后使用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

推荐阅读