0

嘿,我有以下脚本不起作用,而且对我来说迟到了,所以我可以使用一些帮助。这会从 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;

?>
4

1 回答 1

1

您的代码中的这一部分:

foreach ($friendArray[] as $k => $friend)

导致语法错误。$friendArray这里不应该有方括号[]

foreach ($friendArray as $k => $friend)
于 2012-10-12T07:05:46.690 回答