简体   繁体   English

关于 PHP 的初学者问题,是否有其他方法可以显示来自 mySQL 的数据而不是 for/foreach/while 循环?

[英]Beginner question on PHP, is there alternative ways to display data from mySQL than for/foreach/while loop?

I want to create a small application instead of downloading a source code and use it.我想创建一个小型应用程序,而不是下载源代码并使用它。

I will display data from the database in many different places in my page.我将在页面的许多不同位置显示来自数据库的数据。 For example, I will have to display the NAME somewhere, the ADDRESS somewhere else and at the end of the page the BIRTH.例如,我必须在某处显示 NAME,在其他地方显示 ADDRESS,并在页面末尾显示 BIRTH。

The page will display the details of one person only, based on the ID given through a form.该页面将根据通过表格提供的 ID 仅显示一个人的详细信息。 Below is the way I know on how to display the details of the person with ID 1.以下是我知道如何显示 ID 为 1 的人的详细信息的方式。

$query="select * from student WHERE id='1'";

and in every place that will be a personal detail about the person with ID 1 this?并且在每个地方都将是关于 ID 1 的人的个人详细信息?

while($nt=mysql_fetch_array($rt)){
echo "$nt[name]<br>";
}

and in another place在另一个地方

while($nt=mysql_fetch_array($rt)){
echo "$nt[address]<br>";
}

and somewhere else和其他地方

while($nt=mysql_fetch_array($rt)){
echo "$nt[birth]<br>";
}

My question is if there is another way of displaying info, instead of what I posted (including for/foreach loops and one big while loop), to display the details?我的问题是,是否有另一种显示信息的方式,而不是我发布的内容(包括 for/foreach 循环和一个大的 while 循环)来显示详细信息? Something faster maybe, with less repetitive code?也许更快,重复代码更少?

Thank you.谢谢你。

Since you're only fetching one row, you do not need a loop at all.由于您只获取一行,因此您根本不需要循环。

Only once, issue your query and assign the first row to a variable.只有一次,发出您的查询并将第一行分配给一个变量。

$query = "SELECT * FROM student WHERE id = 1 LIMT 1";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

Now at one part of your page, echo $row['name'];现在在页面的一部分, echo $row['name']; , somewhere else you can echo $row['address'] , and at the end you can echo $row['birth']; ,在其他地方你可以echo $row['address'] ,最后你可以echo $row['birth']; . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM