简体   繁体   English

SQL预准备语句-如何选择多行

[英]SQL prepared statements - how to SELECT multiple rows

I have this code so far 到目前为止我有这段代码

// Starts the transaction
self::$database->startTransaction();
    try {

        $sql  = "SELECT playerId FROM players WHERE name=?";
        $stmt = self::getConnection()->prepare($sql);
        $stmt->bind_param('s', $playerName);
        foreach ($playerNames as $key => $playerName) {
            $stmt->execute();
            $stmt->bind_result($playerId);
            $stmt->fetch();
            echo $playerId . "<br>";
        }

        // commits the transaction
        self::$database->commit();
    } catch (Exception $e) {
        self::$database->rollback();
        throw new Exception(__METHOD__." | ".$e->getMessage());
    }

The array $playerNames contains the names of the players, eg $playerNames数组包含玩家的名称,例如

array('Player1', 'Player2', 'player3')

The code from above should select the playerId of those players from the database. 上面的代码应从数据库中选择那些玩家的玩家编号。 I have some issues: 我有一些问题:

  1. It just returns the last playerId (in this case the Id of 'player3'). 它仅返回最后一个 playerId(在本例中为“ player3”的ID)。 I don't know why. 我不知道为什么

  2. I use a foreach -loop to execute() . 我使用一个foreach loop来execute() is this bad for the performance, if there were hundreds of names in the array? 如果数组中有数百个名称,这对性能是否不利?

  3. In generell: Is this the correct approach for SELECT ing or INSERT ing stuff from or into a database? 概括来说:这是从数据库中SELECTINSERT内容的正确方法吗?

I read this question: How can I prevent SQL injection in PHP? 我读了一个问题: 如何防止PHP中的SQL注入?

But it didn't really work because of this: 但这并没有真正起作用,因为:

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with $row
}

I get an error with the getResult() -method. 我的getResult()方法出错。 It says, the method doesn't exist. 它说,该方法不存在。 I think my webspace doesn't support it and I can't install it manually. 我认为我的网站空间不支持它,因此无法手动安装。 So I need to stick with fetch() . 所以我需要坚持使用fetch()

Or might it have other reasons? 还是可能有其他原因?

    $sql  = "SELECT playerId FROM players WHERE name=?";
    $stmt = self::getConnection()->prepare($sql);
    $stmt->bind_param('s', $playerName);
    $stmt->bind_result($playerId);
    foreach ($playerNames as $key => $playerName) {
        $stmt->execute();
        $stmt->fetch();
        echo $playerId . "<br>";
    }
  1. You are fetching results of only last execute 您正在获取仅最后执行的结果
  2. Running long loops is apparently bad for performance. 运行长循环显然不利于性能。 Try to avoid them. 尽量避免它们。
  3. Yes, in general. 是的,一般而言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM