如何将下面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.
如何在上面的代码中使用它?
答案 0 :(得分: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循环和while:
访问它们中的每一个 foreach($token as $key=>$val){
echo $val.'<br>';
}