2009-08-16 76 views
1

我必須做第一個查詢是SELECT * from table WHERE NOT column=0,並使用它的結果做一個foreach循環,如下所示。使用foreach更新基於另一個查詢mysql數據庫中的字段

foreach($results as $result) { 
$nox = $result[field_x]; 
//Use nox for whatever; 
//Then update some fields in SQL; } 

並繼續這樣做,直到完成第一個查詢中的所有項目。

語法是什麼?

+0

耶穌基督不要引誘我,那就太容易蓋上蓋子上的筆記本電腦,現在 – bluedaniel 2009-08-16 23:21:30

回答

1

$sql = "SELECT * FROM `myTable` WHERE `column` = 0"; 

// query the database 
$resource = mysql_query($sql); 

// loop through the results 
while ($result = mysql_fetch_assoc($resource)) { 
    // grab the value 
    $nox = $result['field_x']; // you should use quotes here, btw 

    // make your modifications; 
    ++$nox; // or whatever 

    // build the query 
    $sql = sprintf(
     "UPDATE `myTable` SET `field_x` = %d WHERE `id` = %d" 
     , $nox 
     , $result['id'] 
    ); 

    // run the query 
    mysql_query($sql); 
} 
+0

好,謝謝,我真的不是懶惰或愚蠢,我只是懶惰,經過漫長的一天後,你會覺得很蠢! – bluedaniel 2009-08-16 23:25:29

+0

基本我知道,但開始將是: $ query =「SELECT * FROM table WHERE NOT field_x = 0」; $ results = mysql_query($ query); 對不對? – bluedaniel 2009-08-16 23:31:57

+0

nope - 我已經在上面添加了正確的語法。 – nickf 2009-08-16 23:46:59

0

你只使用一個簡單的update命令:

update tbl set field = '$value' where id = $id 

在PHP-ESE:

$sql = 'update tbl set field = \'' . 
     mysql_real_escape_string($value) . '\' where id = ' . $id; 
mysql_query($sql); 
3

除非你有一些在PHP強大的處理做了你最可能做的是,在一個單一的,multi-table UPDATE

例如:

UPDATE table1 t1 
    JOIN table2 t2 ON t2.id = t1.id 
    SET t1.col = t2.col + 1 
WHERE t1.somecol <> 0 
+0

這真的是廣泛的PHP處理!這就是爲什麼我想確保我的思維方式是好的。不管怎麼說,還是要謝謝你 – bluedaniel 2009-08-16 23:30:23

相關問題