duanliushua5026 2016-07-30 08:37
浏览 59

从给定的id数组列表及其值更新特定id的特定值

I have a doubt in mysql_query. I want to update the particular value(id's value) for particular id from list of arrays of id and its value.

here is the normal query

update table_name set name='sham', age='18' where id=1
Update table_name set name='ram', age='19' where id=2
Update table_name set name='rani', age='29' where id=3

Instead of above query I want to update these fields in 1 query by passing these values through an array

like update set name=?, age=? where id=?

Can we do it?

What query should be written and how to pass in array to update query

  • 写回答

1条回答 默认 最新

  • dongzhong5967 2016-07-30 12:52
    关注

    Can we do it?

    Yes, it can be done.

    Should you do it?

    No. It's a bad idea. It will be slow and inefficient.

    If you want to use arrays of values to execute a query several times with different values, here is one way to do it with PDO and prepared statements with named placeholders:

    (We assume you already have a working PDO connection in your script: $dbh)

    $values = [
        [
            ':name' => 'sham',
            ':age' => '18',
            ':id' => 1
        ],
        [
            ':name' => 'ram',
            ':age' => '19',
            ':id' => 2
        ],
        [
            ':name' => 'rani',
            ':age' => '29',
            ':id' => 3
        ]
    ];
    $query = "UPDATE some_table SET name = :name, age = :age where id = :id";
    $sth = $dbh->prepare($query);
    foreach ($values as $set) {
        $sth->execute($set);
    }
    

    This code will prepare the query once, and execute it for each set of values in $values.

    Here is the same code with unnamed placeholders (question marks):

    $values = [
        [
            'sham',
            '18',
            1
        ],
        [
            'ram',
            '19',
            2
        ],
        [
            'rani',
            '29',
            3
        ]
    ];
    $query = "UPDATE some_table SET name = ?, age = ? where id = ?";
    $sth = $dbh->prepare($query);
    foreach ($values as $set) {
        $sth->execute($set);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看