如何从mysqli_fetch_assoc获取特定值并从下面的代码中的函数返回它们?
具体来说,我在单击提交按钮时尝试同时从db_select()返回$ CID和$ Fname。
function db_query($sql){
$con = db_connect();
$result = mysqli_query($con,$sql);
return $result;
}
function db_select($sql){
$rows = array();
$result = db_query($sql);
if(!$result){
return false;
}
while($row = mysqli_fetch_assoc($result)){
$CID = $row['C_ID'];
$Fname = $row['C_Fname'];
$rows = $CID;
}
return $rows;
}
if (isset($_POST['submit'])){
echo $rows=db_select("SELECT C_ID,C_Fname FROM Customer WHERE C_Email='$Email'")
//how to also return $Fname?
}
答案 0 :(得分:1)
db_select函数返回一个完整的数组,所以很可能你想要访问这两个变量,如下所示:
function db_select($sql){
$rows = array();
$result = db_query($sql);
if(!$result){
return false;
}
// This function could potentially return multiple rows...
while($array = mysqli_fetch_assoc($result)){
// This will return multiple rows
$row[] = $array;
}
// This will return only one row
// (but there may be more that you are missing)
// $row = mysqli_fetch_assoc($result)
// Notice change here
return $row;
}
if (isset($_POST['submit'])){
$rows = db_select("SELECT C_ID,C_Fname FROM Customer WHERE C_Email='$Email'")
// If you have the one row option you echo like so
// echo $rows['C_ID'];
// echo $rows['C_Fname'];
// For multiple row option, do a foreach or if you know the key you can access it directly
foreach($rows as $arrays) {
echo $arrays['C_ID'];
echo $arrays['C_Fname'];
}
}
答案 1 :(得分:0)
函数不能返回多个值,但返回数组可以获得类似的结果。
另请参阅文档中的示例#2。
在您的情况下,您可以return $row;
。但是,从您的代码中,您尝试收集多行的结果。此示例收集数组$rows
中的所有单独行:
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
return $rows;
答案 2 :(得分:0)
试试这个。
function db_select($sql){
$rows = array();
$result = db_query($sql);
if(!$result){
return false;
}else{
$row = mysqli_fetch_assoc($result);
return $row;
}
}
if (isset($_POST['submit'])){
$rows = db_select("SELECT C_ID,C_Fname FROM Customer WHERE C_Email='$Email'")
echo $rows['C_ID'];
echo $rows['C_Fname'];
}