MySQLi返回一个数组,其中bind_result和fetch不起作用


MySQLi return an array with bind_result and fetch not working

我想知道如何重写/修复以下代码。

基本上,我有一个名为DB的数据库,其中有一个表poems。我想获得poems表中具有特定ID的所有数据(即谁写了这首诗,它有什么标签,它的内容,它是何时创建的,等等),并将其安全地存储在一个数组中,以便稍后打印到网页上。

我的托管服务不支持mysqli_getresult()所需的mysqlnd驱动程序,所以我目前收到错误"Call to undefined method mysqli_stmt::get_result()"

$mysqli是到数据库的预写连接,使用new mysqli()

function getpoemdata($mysqli) {
                echo "Function started.";
                if(isset($_GET['poem_id'])) { // Check if poem_id is set in the URL
                    $poemid=$_GET['poem_id']; // Get poem_id set in URL
                    if (!is_int($poemid)) { $poemid = 7; } // Check if poem_id is set an integer
                    if ($poemid <= 0) { $poemid = 7; } //Check if poem_id is positive- If negative, it is changed to positive
                    $stmt = $mysqli->prepare("SELECT * FROM `poems` WHERE `poem_id` = ?");
                    $stmt->bind_param('i', $poemid);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    $returned_data = $returned_data->fetch_array();
                    while($stmt->fetch()){
                        echo $returned_data . '<br />';
                    }
                    $stmt->free_result();
                }
                else { //If user simply types "poemview.php" and not "poemview.php?poem_id="
                echo "error";
            }
    }

提前感谢您的任何帮助-我对PHP很陌生,并试图在学习过程中学习它-每次我尝试做一些新的事情,需要学习十几个函数时,都会有点不知所措。

get_result()是在PHP 5.3.0中引入的,如上所述,它需要mysqlnd。但是,我认为您不需要它。您可以将fetch()与bind_result结合使用来检索数据。可能还有其他方法。

文档示例:

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";
if ($stmt = $mysqli->prepare($query)) {
    /* execute statement */
    $stmt->execute();
    /* bind result variables */
    $stmt->bind_result($name, $code);
    /* fetch values */
    while ($stmt->fetch()) {
        printf ("%s (%s)'n", $name, $code);
    }
    /* close statement */
    $stmt->close();
}
/* close connection */
$mysqli->close();
?>

文档中的一个示例显示了如何绑定到数组。