开发者

PHP PDO can't update records in foreach loop

开发者 https://www.devze.com 2023-03-24 00:46 出处:网络
Script searchs through DB and fix broken links. Search and replace functionality works fin开发者_JAVA技巧e, but when trying to save updated data scripts wrights only first raw. I\'m stucked! I can use

Script searchs through DB and fix broken links. Search and replace functionality works fin开发者_JAVA技巧e, but when trying to save updated data scripts wrights only first raw. I'm stucked! I can use simple mysql_query commands to update data, but needs PDO...

header('Content-Type: text/html; charset=UTF-8');
error_reporting(E_ALL);
echo "Welcome";
$mysql = new PDO('mysql:host=localhost;dbname=db_name;charset=UTF-8','user','12345');
if (!$mysql) die('Can\'t connect');

$tables = array(
    'categories',
    'news',
    'pages'
);

function getContent($table) {
    global $mysql;
    $fieldnum = 0;
    $fields = array();  
    $vals = array();
    $st = $mysql->query("SHOW FIELDS FROM `{$table}`"); 
    while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
        $fields[$fieldnum]=$row["Field"];       
        $fieldnum++;
    }
    $totalfields=$fieldnum;
    $res = $mysql->query("SELECT * FROM `{$table}`");
    $sql = "UPDATE `:table` SET :field = ':val' WHERE `:idf` = :id;";       
    while ($row = $res->fetch(PDO::FETCH_NUM)) {
        for ($j=0; $j<$res->columnCount();$j++) {                   
            $rs = str_replace('index.php/','',$row[$j],$m);
            if ($rs && $m>0) {
                if ($table == 'categories')
                $prim= 'cat_id';
                elseif($table == 'news') $prim= 'news_id';
                elseif($table == 'pages') $prim= 'page_id';
                else $prim= $table.'_id';

                            $upd = $mysql->prepare($sql);
                $update = $upd->execute(array(
                ':table'=>$table,
                ':field'=>$fields[$j],
                ':val'=>$rs,
                ':idf'=>$prim,
                ':id'=>$row[0]
                ));             
            }
        }
    }   
}

foreach ($tables as $t) {
    getContent($t);
}

Need help to fix it!


try to fetch all and then go through array and you do not need to use prepare every time - just once see Example #2

....
$res = $mysql->query("SELECT * FROM `{$table}`");
$rows = $res->fetchAll(PDO::FETCH_NUM);
$sql = "UPDATE `:table` SET :field = ':val' WHERE `:idf` = :id;";  
$upd = $mysql->prepare($sql);        
foreach ($rows as $row) {
   foreach ($row as $col_name => $value) {          
......


prepare outside the loop! you are loosing its value this way, also try $upd->debugDumpParams(); and binding before execution, maybe the values u r binding is not right.

0

精彩评论

暂无评论...
验证码 换一张
取 消