我想要一个可以使用mysqli_fetch_assoc()获取的函数,它是这样的:
<?php
$con = mysqli_connect("localhost", "root", "", "primary");
function fetchAssoc($query){
global $con;
$queryexec = mysqli_query($con, $query);
$return = array();
while($stuff = mysqli_fetch_assoc($queryexec)){
$return[] = $stuff;
}
return $return;
}
$yup = fetchAssoc("SELECT * FROM posts");
while($thing = $yup){
echo $thing, "<br />";
}
?>
但由于某种原因,我得到了这个结果: 注意:第20行的C:\ xampp \ htdocs \ Experiments \ index.php中的数组到字符串转换 阵列
第20行是echo $thing, "<br />";
答案 0 :(得分:1)
$yup = fetchAssoc("SELECT * FROM posts");
while($thing = $yup){
echo $thing, "<br />";
}
$yup
是关联数组,在你的while循环中,你分配给$thing
- 现在也是一个数组
您应该执行类似
的操作foreach($yup as $y){
// here $y is an array in the form of
// array( ['column_name'] => 'value', '[other_col]' => 'value')
// so you could do
echo $y['column'], $y['other_col'],'<br />';
}
答案 1 :(得分:0)
fetch_assoc
会返回一系列项目,一次打印出来(看看有什么)你可以这样做:
print_r($thing);
或者如果你想单独打印它们:
foreach($thing as $t){
echo $t . '<br />';
}
此外,while循环将永远运行,因为它基本上是这样的:
while(true){
// do something
}
答案 2 :(得分:0)
<?php
$con = mysqli_connect("localhost", "root", "", "primary");
function fetchAssoc($query){
global $con;
$queryexec = mysqli_query($con, $query);
$return = array();
while($stuff = mysqli_fetch_assoc($queryexec)){
$return[] = $stuff;
}
return $return;
}
$yup = fetchAssoc("SELECT * FROM posts");
foreach($yup AS $thing){
// $thing is an associative array so use keys to access data from it like
echo $thing['ID'], "<br />";
}
?>
答案 3 :(得分:0)
你可以尝试这个程序。
<?php
$con = mysqli_connect("localhost", "root", "", "primary");
function fetchAssoc($query){
global $con;
$queryexec = mysqli_query($con, $query);
$return = array();
while($stuff = mysqli_fetch_assoc($queryexec)){
$return[] .= $stuff['name']; //Enter your column name in place of name from your posts table.
}
return $return;
}
$yup = fetchAssoc("SELECT * FROM posts");
foreach($yup as $thing){
echo $thing . "<br />";
}
?>
由于
答案 4 :(得分:0)
$con = mysqli_connect("localhost", "root", "", "primary");
function fetchAssoc($query){
global $con;
$queryexec = mysqli_query($con, $query);
$return = array();
while($stuff = mysqli_fetch_assoc($queryexec)){
$return[] = $stuff;
}
return $return;
}
$yup = fetchAssoc("SELECT * FROM posts");
foreach($yup as $thing){
foreach($thing as $element){
echo $element."<br/>";
}
}
答案 5 :(得分:-1)
您的代码非常完美。但只是一个错误。这里$ thing是一个数组,所以你无法回应它。 试试这个:
while($thing = $yup){
print_r ($thing);
echo "<br />";
}