PHP PDO无法更新foreach循环中的记录

时间:2011-08-01 08:04:36

标签: php mysql pdo sql-update

脚本搜索数据库并修复损坏的链接。搜索和替换功能工作正常,但在尝试保存更新的数据脚本时,只有第一次生成。我被困了!我可以使用简单的mysql_query命令来更新数据,但需要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);
}

需要帮助解决它!

2 个答案:

答案 0 :(得分:1)

尝试获取all然后遍历数组 并且您不需要每次都使用准备 - 只需查看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) {          
......

答案 1 :(得分:-1)

在循环外准备!你正在以这种方式失去它的价值,也尝试$ upd-&gt; debugDumpParams();并且在执行之前绑定,也许绑定的值不正确。