dshdb64088 2015-01-12 21:49
浏览 69

使用Mysql多次插入三行

Let's say I have three rows I need to insert for each ID.

ID   -   FOO    -    BAR
0       test1     something
0       test2     something
0       test3     something

12       test1     something
12       test2     something
12       test3     something

34       test1     something
34       test2     something
34       test3     something

Here is my current code

<?php 

$connection = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

$sql = "INSERT INTO books (id,foo,bar) VALUES (?,?,?)";

$statement = $connection->prepare("$sql");

$statement->execute(array("1", "test1", "something"));

At the moment, I am only able to insert 1 row at a time, updating the values in the execute array each time. Is it possible to loop through an insert whilst using some sort of array to insert all my values?

  • 写回答

1条回答 默认 最新

  • doumei3828 2015-01-14 20:30
    关注

    I would suggest using a simple prepared statement with value binding, like so:

    // array with data you want to insert
    $books = array(
        0 => array('id' => 1, 'foo' => 'somefoo1', 'bar' => 'somebar1'),
        1 => array('id' => 2, 'foo' => 'somefoo2', 'bar' => 'somebar2'),
    );
    
    // create PDO connection
    $pdo = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
    
    // create a prepared SQL statement (for multiple executions)
    $stmt = $pdo->prepare('INSERT INTO books (id,foo,bar) VALUES (:id,:foo,:bar)');
    
    // iterate over your data, bind the new values to the prepared statement
    // finally execute = insert
    foreach($books as $book)
    {
        $stmt->bindValue(':id', $book['id']);
        $stmt->bindValue(':foo', $bookm['foo']);
        $stmt->bindValue(':bar', $book['bar']);
        $stmt->execute();
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法