我有这个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行。但它会将结果打印到屏幕上。如何使它成为变量,以便它可以在函数中返回?
感谢。
更新:根据Phil的回答,现在这是我的完整代码:
<?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()
答案 0 :(得分: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);
答案 1 :(得分:2)
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;
}