drbd65446 2019-05-16 04:30
浏览 97

如何使用PHP的PDO对象发送SQL更新查询

I am trying to write a php script to do some search-and-replace operations on the post_content field. However, there's something wrong with my update query.

First I tried doing the update using $db->query(), but it didn't work. I then tried using ::prepare() and ::execute() but again, I didn't have any success.


// Get all the IDs in a PDO querystring
$ids =  $db->query('SELECT ID FROM XXX_posts WHERE post_content LIKE "%item=\"174\"%" AND post_type="page" AND post_title LIKE "%AZ-%"');
// Iterate through the querystring and create an array
$id_array = array();
foreach( $ids as $id) {
        array_push($id_array, $id[0]);
}

// for each id in the array, store post_content into a variable and run some replacements
// then update post_content with the modified content
foreach ( $id_array as $id ) {
        $query = 'SELECT post_content FROM XXX_posts WHERE ID = ';
        $query .= $id;
        $contents = $db->query($query);

        $final_content = "";
        foreach( $contents as $content ) {
                $final_content = $content[0];
        }

        $output=preg_replace('/961,960,959,913,912,911,910,909,908,907/',
                             '8661,8667,8660,8664,8665,8663,8662,8668,8666,8669',
                             $final_content );
        $output=preg_replace('/4566/', '8678', $output);
        $output=preg_replace('/174/', '8656', $output);
        $output=preg_replace('/174/', '8678', $output);
        $statement = 'UPDATE XXX_posts SET post_content = ' . "'" .  $output . "'"  . ' WHERE XXX_posts.ID = ' . $id . ';';
        $update = $db->prepare($statement);
        $update->execute();
}

I would like to simply run the UPDATE query on all 64 post IDs grabbed in the first step of my code.

I appreciate the help.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 求解 yolo算法问题
    • ¥15 虚拟机打包apk出现错误
    • ¥30 最小化遗憾贪心算法上界
    • ¥15 用visual studi code完成html页面
    • ¥15 聚类分析或者python进行数据分析
    • ¥15 三菱伺服电机按启动按钮有使能但不动作
    • ¥15 js,页面2返回页面1时定位进入的设备
    • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
    • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
    • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝