I want to create an function to fetch data from different tables which have different table. Is it possible?
This is my function code
<?php
// Check connection
function fetch_data($selectsql){
include 'connectdb.php';
$result = $conn->query($selectsql);
if($result->num_rows <= 0 ){
echo "0 results";
}
else{
while ($row = $result->fetch_assoc()){
return $row = array();
}
}
}
?>
and this is for use testing my function
<?php
include 'fetch_data_test.php';
include 'connectdb.php';
$selectsql = "SELECT * FROM user";
$row = fetch_data($selectsql);
echo $name = $row["name"];
echo $lastname = $row["lastname"];
$conn->close();
?>
but it didn't work. Can someone help me? or explain me more about how it can get and array.
Error:
Notice: Undefined index: name in /var/www/html/home/use_fetch.php on line 7 Notice: Undefined index: lastname in /var/www/html/home/use_fetch.php on line 8
First you are return empty array for your function fetch_data
. . Return you data outside your while loop
<?php
// Check connection
function fetch_data($selectsql){
$rows=array();// create an array
include 'connectdb.php';
$result = $conn->query($selectsql);
if($result->num_rows <= 0 ){
echo "0 results";
}
else{
while ($row = $result->fetch_assoc()){
$rows= $row;// assign your data to array
}
}
return $rows;// return array
}
?>
Second you have to assign your return values form function to variable
<?php
include 'fetch_data_test.php';
include 'connectdb.php'
$selectsql = "SELECT * FROM user";
$row=fetch_data($selectsql);// assing into a variable
echo $name = $row["name"];
echo $lastname = $row["lastname"];
$conn->close();
?>
You're returning a blank array when you use this code return $row = array();
You need to fix that.
Also, you're not saving returned value to any variable.
In your code to test your function, change fetch_data($selectsql);
to $rows = fetch_data($selectsql);
<?php
// Check connection
function fetch_data($selectsql){
include 'connectdb.php';
$rows = array();
$result = $conn->query($selectsql);
if($result->num_rows <= 0 ){
echo "0 results";
} else{
while ($row = $result->fetch_assoc()){
$rows[] = $row;
}
}
$conn->close();
return $rows;
}
?>
<?php
include 'fetch_data_test.php';
$selectsql = "SELECT * FROM user";
$rows = fetch_data($selectsql);
foreach($rows as $row){
echo $name = $row["name"];
echo $lastname = $row["lastname"];
echo "
";
}
?>