我想创建一个函数来从具有不同表的不同表中获取数据。有可能吗?
这是我的功能代码
<?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();
}
}
}
?>
这是用于测试我的功能
<?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();
?>
但它不起作用。 有人能帮我吗?或者向我解释一下如何获得和阵列。
错误:
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
答案 0 :(得分:2)
使用此代码return $row = array();
时,您将返回一个空白数组。您需要解决此问题。
此外,您没有将返回值保存到任何变量。
在测试功能的代码中,将fetch_data($selectsql);
更改为$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 "\n";
}
?>
答案 1 :(得分:2)
首先,您为函数fetch_data
返回空数组。 。在while循环之外返回数据
<?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
}
?>
其次,您必须将表单函数的返回值分配给变量
<?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();
?>