php - 如何使用 PHP PDO 在 mysql 中插入未知数量的列

标签 php mysql pdo

目前,我正在使用此代码:PHP PDO 插入数据

try {

    // prepare sql and bind parameters
    $stmt = $conn->prepare("INSERT INTO TABLE (firstname) 
    VALUES (:firstname, :lastname, :email)");
    $stmt->bindParam(':firstname', $firstname);    
    // insert a row
    $firstname = "John";
    $stmt->execute();
    echo "New records created successfully";
    }

而且它工作得很好。

我的问题:我有 5 列,例如:tag1,tag2,tag3,tag4,tag5

这就是我从 API(数组)获取值并回显它们的方法

for ($i=0;$i<count($response["tag"]);$i++    )
{
echo "  ".$response["tag"][$i]["name"]." ";
}

现在,如果数组仅发送 2 个标签值(即:["tag"][0]["name"] 和 ["tag"][1]["name"]

然后我想仅在 tag1 和 tag2 列中插入值

但看起来我无法在插入数据代码中使用 forloop 。我需要一些帮助。

最佳答案

如果这是你必须这样做的方式(而不是标准化)那么像

$data = [];
$binds = [];
for ($i=0;$i<count($response["tag"]);$i++    )
{
    //echo "  ".$response["tag"][$i]["name"]." ";
    $columns[] = "tag".$i;
    $binds[] = ":tag".$i;
}

$sql = 'insert into tableName ('.implode(',',$columns).')'.
        ' values ('.implode(',',$binds).')';
echo $sql;
$stmt = $conn->prepare($sql);
for ($i=0;$i<count($response["tag"]);$i++    )  {
    $stmt->bindParam($binds[i], $response["tag"][i]["name"]);
}

第一个foreach构建一条sql语句,例如

insert into tableName (tag0,tag1) values (:tag0,:tag1)

(调整数据库的表名称等)。第二个 foreach 将传入的值与语句中的每个占位符绑定(bind)。

关于php - 如何使用 PHP PDO 在 mysql 中插入未知数量的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44647696/

相关文章:

php - 避免在 strtotime 为 false 时显示 1970-01-01

php - 表中的单引号中的双引号

php - 禁用 PDO::ATTR_EMULATE_PREPARES 导致 'unknown' 问题

javascript - 用php和mysql链接选择框

php - PDO 页面错误调用非对象上的成员函数 bindValue()

php - Composer 需要特定的拉取请求

mysql - 具有 MySql 异常的 Entity Framework - "The underlying provider failed on Open."- "Reading from the stream has failed."

php - 无法更新数据 : SQL syntax error in my update command

php - 如何从客户端终止 php 连接?

php - DB2如何使用PDO指定连接字符集