嘿,我有以下脚本无效,而且对我来说很晚,所以我可以使用一些帮助。这会从http帖子接收一个id数组,并且应该获取用户名。当发送一个我知道在我的数据库中的Id我得到null。我的剧本怎么了?
<?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;
?>
答案 0 :(得分:1)
您的代码中的这一部分:
foreach ($friendArray[] as $k => $friend)
导致语法错误。 $friendArray
此处不应有方括号[]
:
foreach ($friendArray as $k => $friend)