从数据库中检索数据
请帮我从数据库中检索数据并显示它。
我正在学习,这阻碍了我前进:(
我有:
$result = mysql_query($sql);
$num_reg = mysql_num_rows($result);
echo $num_reg; // this shows 3
while($row = mysql_fetch_assoc($result))
{
foreach($row as $value)
{
//Now I need to operate with the rows values.
echo $row['PHONE'];
但这不是打印电话号码,而是每个打印 5 次
我做错了什么?
非常感谢
Please give me a hand retrieving data from the database and showing it.
I'm learning and this is holding me from advancing :(
I have:
$result = mysql_query($sql);
$num_reg = mysql_num_rows($result);
echo $num_reg; // this shows 3
while($row = mysql_fetch_assoc($result))
{
foreach($row as $value)
{
//Now I need to operate with the rows values.
echo $row['PHONE'];
But this instead of printing the phone numbers, prints them 5 times each
What am I doing wrong?
Thanks a lot
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
删除
foreach
循环Remove
foreach
loop在这种情况下你不需要 foreach
可能你的
$row
有 2 个元素,并且在foreach
中你的echo $row['PHONE']
每个元素被调用一次you don't need foreach in that case
Probably your
$row
has 2 elements, and insideforeach
yourecho $row['PHONE']
is called once for every element在 while 循环中执行 print_r($row) ,在 foreach 循环中执行 print_r($value) 。
然后问你为什么要在 $row 元素上循环 echo $row 。
do a print_r($row) in your while loop and a print_r($value) in your foreach loop.
Then ask you why do you echo $row in a loop on $row elements.
您不需要在 while() 循环内使用第二个 foreach() 循环来处理这些值。您在这里所做的是循环遍历行,然后循环遍历值,但如果您已经可以通过 $row 变量访问这些值,则不需要再次循环。您收到电话号码 5 次的事实表明您的表格中有 5 列。
一个例子 - 删除 foreach() 循环:
我猜你有一个名为“name”的变量,但如果不是,请将其交换为你已有的变量。最后一个 echo 只是打印一个新行以使其更易于阅读。
You don't need a second foreach() loop inside the while() loop to work on the values. What you're doing here is looping through the rows then looping through the values but if you already have access to the values via the $row variable you don't need to loop again. The fact you get the phone number 5 times suggests you have 5 columns in your table.
An example - remove the foreach() loop:
I'm guessing you have a variable called "name" but if not just swap it for one you do have. The last echo just prints a new line to make it easier to read.