嘿,我有下面的腳本不工作,它對我來說晚了,所以我可以使用一些幫助。這從http帖子接收一個id數組,並且應該抓取用戶名。當我發送一個單一的ID,我知道是在我的數據庫中,我得到空回來。我的腳本有什麼問題?PHP腳本只返回上一個值
<?php
$friendArray[] = $_POST["friendId"];
$hostname = 'http://localhost/';
$dbname = 'MYDB';
$db_username = 'user';
$db_password = 'pass';
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',);
$inQuery = implode(',', array_fill(0, count($friendArray), '?'));
try {
$dsn = "mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=".$dbname;
$dbh = new PDO($dsn, $db_username, $db_password, $options);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare('SELECT USER_SCREEN_NAME USER WHERE USER_ID IN (' . $inQuery . ')');
foreach ($friendArray[] as $k => $friend)
{
$sth->bindValue(($k+1), $friend);
}
$sth->execute();
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
}
catch(PDOException $e) {
echo $e->getMessage();
}
$dbh = null;
?>
解決方法:我發現的主要問題是在sql語句中沒有「FROM」。之後,我經歷了更多的迭代和問題,最終得到以下工作。另一個問題是,循環和綁定不起作用,所以一旦我得到了適當的格式數組傳遞它執行了伎倆。
<?php
$friendArray = array();
foreach ($_POST["friendId"] as $myFriend)
{
$friendArray[] = $myFriend;
}
$hostname = 'http://localhost/';
$dbname = 'MYDB';
$db_username = 'user';
$db_password = 'pass';
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',);
$inQuery = implode('', array_fill(0, count($friendArray)-1, " OR USER_ID = ?"));
try {
$dsn = "mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=".$dbname;
$dbh = new PDO($dsn, $db_username, $db_password, $options);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare("SELECT USER_SCREEN_NAME FROM USER WHERE USER_ID = ?" . $inQuery . "");
$sth->execute($friendArray);
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
}
catch(PDOException $e) {
echo $e->getMessage();
}
$dbh = null;
?>
這行,在該腳本不能按預期工作? –
可能在這裏,但是'$ friendArray [] = $ _POST [「friendId」];方括號中的原因是什麼?難道不會僅僅將'$ _POST [「friendId」]'賦值給'$ friendArray [0]'? –
@cegfault查看'$ inQuery'是如何被填充的;這根本不是SQL注入。 –