2017-04-17 61 views
1

我有一個簡單的PHP代碼:PHP MYSQL更新一些記錄在while循環

$sql= 'SELECT ID, fb_postid, scheduled FROM `posts` WHERE clicks = "" AND fb_postid !="" AND scheduled < NOW() order by ID ASC LIMIT 10;'; 

$result = mysqli_query($link, $sql); 
print_r($result); 

while ($row = mysqli_fetch_assoc($result)) { 
      $clicks=fbcall($fbtoken, $row['fb_postid']); 
      $update="UPDATE `posts` SET `clicks`='".$clicks."' WHERE id='".$row['ID']."'"; 
      $result = mysqli_query($link, $update);  
      print("POSTID: " . $row['fb_postid'] . " - Clicks: " . $clicks ."<br>");  
}; 

MySQL的SELECT會從DB 10行循環遍歷While循環線路,會從功能fbcall「點擊」和那麼應該更新所有10行的值從「點擊」到數據庫。如果我運行沒有更新的代碼,我得到10個結果打印,但如果我用mysqli_update運行,我只得到1行更新。任何人有任何想法爲什麼?

+0

您的代碼很容易受到[** SQL注入攻擊**](HTTPS://en.wikipedia。組織/維基/ SQL_injection)。你應該使用[** mysqli **](https://secure.php.net/manual/en/mysqli.prepare.php)或[** PDO **](https://secure.php.net/ manual/en/pdo.prepared-statements.php)準備帶有綁定參數的語句,如[**這篇文章**]所述(https://stackoverflow.com/questions/60174/how-can-i-prevent-sql步噴射功能於PHP)。 –

+0

什麼'mysqli_error($ link)'在查詢中顯示?如果您需要真實性,請使用UPDATE –

+0

上的'mysqli_affected_rows()'修正打印錯誤。謝謝。但沒有區別。 – swapfile

回答

1

您正在使用$result變量遍歷第一個查詢中的行列表。

但是你給循環中的$結果一個新的值,清除那裏的東西。

只要使用兩個不同的變量,你會沒事的。嘗試是這樣的:

$sql= 'SELECT ID, fb_postid, scheduled FROM `posts` WHERE clicks = "" AND fb_postid !="" AND scheduled < NOW() order by ID ASC LIMIT 10;'; 

$result = mysqli_query($link, $sql); 
print_r($result); 

while ($row = mysqli_fetch_assoc($result)) { 
      $clicks=fbcall($fbtoken, $row['fb_postid']); 
      $update="UPDATE `posts` SET `clicks`='".$clicks."' WHERE id='".$row['ID']."'"; 
      $result2 = mysqli_query($link, $update);  
      print("POSTID: " . $row['fb_postid'] . " - Clicks: " . $clicks ."<br>");  
}; 
+0

就是這樣!大。非常感謝。 – swapfile

0

修正它,並準備更新語句建:

$sql= 'SELECT ID, fb_postid, scheduled FROM `posts` WHERE clicks = "" AND fb_postid !="" AND scheduled < NOW() order by ID ASC LIMIT 10;'; 
$result = mysqli_query($link, $sql); 
$qry = "UPDATE `posts` SET `clicks`=? WHERE id=?"; 
$stmt = mysqli_prepare ($link, $qry); 
mysqli_stmt_bind_param ($stmt, 'ss',$clicks, $id); 

while ($row = mysqli_fetch_assoc($result)) { 
      $clicks=fbcall($fbtoken, $row['fb_postid']); 
      $id=$row['ID']; 
      mysqli_stmt_execute($stmt); 
      print("POSTID: " . $row['fb_postid'] . " - Clicks: " . $clicks ."<br>");  
};