gpt4 book ai didi

php - 如何回显所有行和所有列?

转载 作者:行者123 更新时间:2023-11-29 12:13:30 24 4
gpt4 key购买 nike

我可以回显所有行吗?这是我的脚本:

$options=mysql_query("SELECT col1, col2, col3, col4 FROM table1");
while($allrowsandcolumns=mysql_fetch_array($options)) {
$options1=mysql_query("SELECT * FROM table2 where id=$allrowsandcolumns");
}
while($rows=mysql_fetch_array($options1)) {
echo $rows['name'];
}

我的错误提示:上面代码第 3 行中的数组到字符串转换

我猜测它是因为这不是显示所有列和行的方式......

最佳答案

我同意 Jay Blanchard 的观点,即您应该使用 mysql_* 函数以外的其他函数。

首先出现错误消息是因为您使用数组代替字符串:

"SELECT * FROM table2 where id=$allrowsandcolumns" 

$allrowsandcolumns 是数据库中的结果数组,其中包含第一个查询的 col1、col2、col3、col4。从视觉上看,它看起来像这样:

array ( 
"col1" => value1
"col2" => value2
"col3" => value3
"col4" => value4
)

我认为我们可以同意尝试将数组放入字符串中是行不通的。相反,您可能想要这样的东西:

"SELECT * FROM table2 where id=" . $allrowsandcolumns["col1"]

或者以与table2匹配的id列为准。

就回显所有行而言...在我看来,您是编程新手。但嵌套很容易解释:

现在你有这个:

$options=mysql_query("SELECT col1, col2, col3, col4 FROM table1");
while($allrowsandcolumns=mysql_fetch_array($options)) {
$options1=mysql_query("SELECT * FROM table2 where id=$allrowsandcolumns");
}
while($rows=mysql_fetch_array($options1)) {
echo $rows['name'];
}

这并没有按照您的想法进行。它将循环遍历 table1 中的每一行,然后在获取并回显名称时使用 $options 中的最后一行。您需要做的就是像这样嵌套循环:

$options=mysql_query("SELECT col1, col2, col3, col4 FROM table1");
while($allrowsandcolumns=mysql_fetch_array($options)) {
$options1=mysql_query("SELECT * FROM table2 where id= " . $allrowsandcolumns["col1"]);
while($rows=mysql_fetch_array($options1)) {
echo $rows['name'];
}
}

也就是说。这是一个坏主意。循环 SQL 查询对性能来说非常糟糕。在寻求知识的过程中,查找连接查询,以便您可以立即检索所有这些结果。像这样的事情:

 SELECT col1,col2,col3,col4 
FROM table1 JOIN table2 on table2.id = table1.col1

然后您可以对这些值进行一次循环。

关于php - 如何回显所有行和所有列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30266056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com