下面是我的自定义函数,它会处理我调用的查询:
<?php
function cusQuery($sql){
$servername = "localhost";
$username = "root";
$password = "366y~V3g4n";
$dbname = "learnTurkishDesktop";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sql);
$output = array();
if($result->num_rows>0){
while ($row = $result->fetch_assoc()){
//as you see I tried to output all rows using print_r and it worked but I want it to just return an array containing all applicable rows and the call should handle the rest(formatting and which columns to include).
print_r($output[] = $row);
}
}else{
return array("0 results");
}
mysqli_close($conn);
}
?>
现在我在index.php上调用了我的cusQuery函数
<?php
include('myFunctions.php');
$myQuery = cusQuery("SELECT Title, Content FROM user_created_notebooks");
echo "<h4>". $myQuery['Title']." ".$myQuery['Content']."</h4>";
?>
我尝试在函数调用中使用for循环,但它不起作用。以下是我正在尝试做的参考:
http://www.dreamincode.net/forums/topic/126144-shortest-way-to-write-a-mysql-fetch-query/
我也试过在函数本身中不使用while循环,就像链接中给出的示例一样,但它只输出第一个适用的行。
我也很想听到新的想法。
提前致谢。
答案 0 :(得分:0)
给定的引用完美,因为只有一行从数据库返回。 “SELECT name FROM table WHERE ID ='$ var'”;
对于您的情况,“$ output [] = $ row”语句创建一个多维数组 包含在数值数组中的关联数组,因此该方法不起作用。下面是你应该如何循环结果
if(!empty($output)){
foreach($output as $row){
echo "h4 {$row['Title']} {$row['content']}";
}
}