警告:PDOStatement :: execute()要求参数1为数组,字符串

时间:2011-11-25 20:52:57

标签: php

我想从数据库中提取32个值,但不是在32个不同的事务中提取。我收到了这个警告,我没有理解它有什么问题。

$team = "SELECT teamname FROM teamnames WHERE";
for ($j = 1; $j <= 32; ++$j) {
    teamid == "$j";
    if ($j != 1) {
        $team .= ",";
    }
    if ($j == 32) {
        $team .= "\")";
    }
}

$teamselect = $db->prepare($team);
$teamselect->execute($team);
for ($y = 1; $y <= 32; ++$y) {    
    $_SESSION["team$y"] = $teamselect->fetchColumn();
}

2 个答案:

答案 0 :(得分:2)

PDOStatement::execute将数组作为其第一个参数,其中索引与占位符的索引或键匹配。

$team="SELECT teamname FROM teamnames WHERE teamname.id = ?";
$stmt = $pdo->prepare($team);
$stmt->execute(array($yourteamid));

现在给出你的代码,我会做以下事情:

$ids = range(1,32);

$team = sprintf(
  'SELECT teamnames.teamname FROM teamnames WHERE teamnames.teamid IN (%s)', 
  implode(',', array_fill(1, count($ids), '?'))
);

$teamselect=$db->prepare($team);
$teamselect->execute($ids);

// then do whatever with your results.

答案 1 :(得分:2)

当您在execute()上使用PDO命令时。如果您有参数,则应该在execute()中使用数组。请参阅以下示例。

$userQuery = $dbh->prepare("SELECT * FROM user where id = ?");
$userQuery->execute(array($_SESSION['user']));
$userData = $userQuery->fetch(PDO::FETCH_ASSOC);