将$ item = mysql_fetch_assoc($ stmt)更改为预准备语句样式

时间:2012-02-23 20:38:34

标签: php sql prepared-statement

此代码有效但我正在尝试解决如何更改$ rose = mysql_fetch_assoc($ stmt);部分为“预备声明风格”。有人知道吗?

$rose_id = $_GET['rose_id'];
  //prepare the statement
  $stmt = $conn2->prepare("SELECT * FROM rosename 
            LEFT JOIN rosevariety ON (rosename.variety_name = rosevariety.variety_name) 
            WHERE rose_id = ?");

            //bind the parameters
  $stmt->bind_param("i", $rose_id);

  //$sql = mysql_query($query, $conn);
  $stmt->execute();

  //was there a good response?
  if ($stmt) {

    $rose = mysql_fetch_assoc($stmt);

    //echo out rose information
    echo "<h1>".$rose['latin_name']."</h1>";
    echo "<h2>".$rose['common_name']."</h2>";

3 个答案:

答案 0 :(得分:5)

如果使用PDO:

$rose = $stmt->fetch(PDO::FETCH_ASSOC);

http://www.php.net/manual/en/pdostatement.fetch.php

如果使用mysqli:

$result = $stmt->get_result();
$rose = $result->fetch_assoc();

http://www.php.net/manual/en/mysqli-stmt.get-result.php
http://php.net/manual/en/mysqli-result.fetch-assoc.php

答案 1 :(得分:1)

如果使用PDO,$stmt->fetch(PDO :: FETCH_ASSOC)就是答案。

答案 2 :(得分:1)

http://www.php.net/manual/en/mysqli-stmt.fetch.php

while ($rose = $stmt->fetch()) {
   //$rose = current row;
}

实际上我认为你需要做正确的使用

while(($rose = $stmt->fetch()) !== false){
  //$rose = current row;
}