1

我有这个 PHP 函数:

function userParent($Username)
{
global $con;
$Result = mysqli_query($con, "SELECT Username FROM Family WHERE Parent = '$Username' LIMIT 10");
$row = mysqli_fetch_assoc($Result);
return $row; 
}

该函数应该给我10行数组,但为什么我只有一个数组值?我试图测试函数括号外的代码并尝试像这样添加 WHILE 循环:

while ($row = mysqli_fetch_assoc($Result)){
    print_r($row);
}

它有效。我得到了数组格式的 10 行。但它会将结果打印到屏幕上。如何使其成为变量,以便可以在函数中返回?

谢谢。

更新:根据菲尔的回答,现在这是我的完整代码:

<?php
function userParent(mysqli $con, $username) {
    $stmt = $con->prepare('SELECT Username FROM Family WHERE Parent = ? LIMIT 10');
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $res = $stmt->get_result();
    return $res->fetch_all(MYSQLI_ASSOC);
}

$DbServer = 'localhost';
$DbUser = 'username';
$DbPassword = 'password';
$DbName = 'dbname';
$mysqli = new mysqli($DbServer, $DbUser, $DbPassword, $DbName);

$arrayParent = userParent($mysqli, 'root');
print_r($arrayParent);

?>

但我收到此错误消息:

致命错误:在第 6 行的 /home/myhome/public_html/test.php 中调用未定义的方法 mysqli_stmt::get_result()

4

2 回答 2

3

使用return

function userParent(mysqli &$dbms, $username){
    // You need to "escape" strings, which you would use in direct queries.
    // OR BETTER: use mysqli prepared statements with parameter binding.
    $username = mysqli_real_escape_string($dbms, $username);

    $result = mysqli_query($dbms, "SELECT Username FROM Family WHERE Parent = '$username' LIMIT 10");

    // Create temporary array for resultset:
    $buffer = array();

    // Fetch data to temporary buffer:
    while ($row = mysqli_fetch_assoc($result)){
        $buffer[] = $row;
    }

    // Free result set:
    $result->free();

    // Return buffer to global scope:
    return $buffer;
}

$users = userParent($con, 'John');

var_dump($users);
于 2013-04-19T04:41:55.417 回答
2

试试mysqli_result::fetch_all

function userParent(mysqli $con, $username) {
    $stmt = $con->prepare('SELECT Username FROM Family WHERE Parent = ? LIMIT 10');
    if ($stmt === false) {
        throw new Exception($con->error, $con->errno);
    }
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $res = $stmt->get_result();
    return $res->fetch_all(MYSQLI_ASSOC);
}

然后像这样调用它

$parents = userParent($mysqli, 'some username');

如果您不知道准备好的语句和参数绑定,请阅读这些

更新

显然(未记录),该mysqli_stmt::get_result()方法仅在使用mysqlnd驱动程序时可用。如果您无法使用此驱动程序,请尝试此替代方法

function userParent(mysqli $con, $username) {
    $stmt = $con->prepare('SELECT Username FROM Family WHERE Parent = ? LIMIT 10');
    if ($stmt === false) {
        throw new Exception($con->error, $con->errno);
    }

    $stmt->bind_param('s', $username);
    $stmt->execute();

    $parent = null;
    $parents = array();
    $stmt->bind_result($parent);
    while($stmt->fetch()) {
        $parents[] = $parent;
    }
    return $parents;
}
于 2013-04-19T04:43:50.300 回答