正在将值设置为变量


Setting value to variable

如何将下面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

为了获得特定的令牌,您需要一个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循环和while访问其中的每一个:

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