这是我的api中使用的声明。它是下面整个函数中的第二个$result
变量。如何改变它以使用PDO?
$result = query("SELECT p.IdPhoto, p.device_token, /*title,*/ p.IdUser FROM photos p JOIN login l ON (l.IdUser = p.IdUser) WHERE p.IdPhoto='%d'", $IdPhoto) ;
整个功能
function stream($IdPhoto=0) {
if ($IdPhoto==0) {
//Load Photos
$result = query("SELECT IdPhoto, device_token, /*title,*/ IdUser FROM photos /*p*/ ORDER BY IdPhoto DESC LIMIT 300 ");
} else {
//Want this to be PDO :)
$result = query("SELECT p.IdPhoto, p.device_token, /*title,*/ p.IdUser FROM photos p JOIN login l ON (l.IdUser = p.IdUser) WHERE p.IdPhoto='%d'", $IdPhoto) ;
}
此代码是否可以代替第二个结果变量?我的目标是将其更改为PDO,以便更成功地扩展。到目前为止,还没有产出。
$dbh = new PDO('mysql:host=localhost;dbname=pushchat', 'pushchat', 'A very secure password!!!');
$result = $dbh->query("SELECT p.IdPhoto, p.device_token, /*title,*/ p.IdUser FROM photos p JOIN login l ON (l.IdUser = p.IdUser) WHERE p.IdPhoto='%d'", $IdPhoto) ;
这些是我的数据库连接值
'host' => 'localhost',
'dbname' => 'pushchat',
'username' => 'pushchat',
'password' => 'A very secure password!!!',
更新 php日志文件
[08-Apr-2016 03:39:25 Europe/Berlin] PHP Notice: Undefined index: IdPhoto in /Applications/MAMP/htdocs/Hi2/index.php on line 44
更新
在测试文件中使用PDO语法,浏览器返回一行。如何通过j son让应用程序立即调用它?
<?php
$conn = new PDO('mysql:host=localhost;dbname=pushchat', 'pushchat', 'd]682\#%yI1nb3');
function new_function()
{
echo "hi<br>";
$an_int = 12;
// If this is an integer
if (is_int($an_int))
{
global $conn;
$stmt = $conn->prepare("SELECT IdPhoto, device_token, IdUser FROM photos ORDER BY IdPhoto DESC LIMIT 300 ");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);
$swag_Bag = 'p.device_token';
print_r($swag_Bag);
}
}
new_function();
?>
更新
这就是应用程序调用原始stream
函数的方式。
-(void)refreshStream
{
//The "stream" command from the web API
[[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"stream", @"command", nil] onCompletion:^(NSDictionary *json)
{
//got stream
[self showStream:[json objectForKey:@"result"]];
...
}];
}
答案 0 :(得分:3)
试试这个:
$conn = new PDO('mysql:host=localhost;dbname=dbname', 'root', 'password');
function stream($IdPhoto=0) {
global $conn;
if ($IdPhoto==0) {
// load the last 300 photos
$stmt = $conn->prepare("SELECT IdPhoto, device_token, IdUser FROM photos ORDER BY IdPhoto DESC LIMIT 300 ");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
} else {
//This is the statement i need to call explicitly via PDO
//do the same as above, but just for the photo with the given id
$stmt = $conn->prepare("SELECT p.IdPhoto, p.device_token, p.IdUser FROM photos p JOIN login l ON (l.IdUser = p.IdUser) WHERE p.IdPhoto= :idphoto ");
$stmt->execute([':idphoto' => $IdPhoto]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
}
if (!$stmt->errorInfo()[0]) {
// if no error occured, print out the JSON data of the
// fetched photo data
print json_encode($result);
} else {
//there was an error, print out to the iPhone app
errorJson('Photo stream is broken');
}
}