'Return multiple values from a function using mysqli_fetch_assoc [closed]
How do I return multiple values from the array returned from mysqli_fetch_assoc() in the code below?
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?
}
Solution 1:[1]
The db_select function returns a full array it looks like, so likely you are wanting to access those two variables like so:
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'];
}
}
Solution 2:[2]
According to the documentation:
A function can not return multiple values, but similar results can be obtained by returning an array.
See also the example #2 in the documentation.
In your case, you could just return $row;
. However, from your code you are trying to gather the result of multiple rows. This example gathers all individual rows in the array $rows
:
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
return $rows;
Solution 3:[3]
Try this.
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'];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | andy |
Solution 3 | Asik |