2016-04-03 225 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>'; 
}