2016-04-03 143 views
0

如何將下面的php語句中的device_token字段設置爲名爲$token的變量?將變量值設置爲

result = query("SELECT device_token, IdPhoto, IdUser FROM photos ORDER BY IdPhoto DESC LIMIT 1") ; 

基於關閉W3Schools的SQL文件:The WHERE clause is used to extract only those records that fulfill a specified criterion.如何能在上面的代碼中使用?

http://www.w3schools.com/sql/sql_where.asp

+1

你的選擇查詢將返回50條記錄,要設置其價值'$ token' –

+0

我想存儲在$令牌device_token值。 – user3233623

回答

1

爲了得到一個特定的標記,你需要一個WHERE條款和特定userid

$id = 1; //You may get this from a form/session you created for login user  
$dbh = new PDO('mysql:host=localhost;dbname=dbname', 'root', 'password');  
$result = $dbh->query("SELECT device_token, IdPhoto, IdUser 
         FROM photos WHERE IdUser='$id' 
         ORDER BY IdPhoto DESC LIMIT 1"); 
$devicetoken = $result->fetch(PDO::FETCH_ASSOC); 

echo $devicetoken['device_token']; 

但是,如果你並不需要一個特定的標記,並希望返回所有的令牌,你不需要WHERE條款和LIMIT。但是,LIMIT爲您提供了更改語句將返回的行數的選項。

$result = $dbh->query("SELECT device_token, IdPhoto, IdUser 
         FROM photos 
         ORDER BY IdPhoto DESC"); 
$token = $result->fetch(PDO::FETCH_ASSOC);//store the device token here in $token 

現在devicetoken包含所有device_token的數組。您可以使用foreach循環和並訪問他們每個人同時:

foreach($token as $key=>$val){ 
     echo $val.'<br>'; 
}