Home > Backend Development > PHP Tutorial > PHP开发中四种查询返回结果分析_php技巧

PHP开发中四种查询返回结果分析_php技巧

WBOY
Release: 2016-05-17 09:21:52
Original
1147 people have browsed it
1.
复制代码 代码如下:

$connection=mysql_connect("localhost","root","password"); //连接并选择数据库服务器
mysql_select_db("test",$connection);
$query="insert into users(user_name)"; //在test数据库里插入一条数据
$query.="values('tuxiaohui')";
$result=mysql_query($query);
if(!$query)
echo "insert data failed!
";
else{
$query="select * from users"; //查询数据
$result=mysql_query($query,$connection);
for($rows_count=0;$rows_count{
echo "用户ID:".mysql_result($result,$rows_count,"user_id")."
";
echo "用户名:".mysql_result($result,$rows_count,"user_name")."
";
}
}
?>

2.
复制代码 代码如下:

$connection=mysql_connect("localhost","root","password"); //连接并选择数据库服务器
mysql_select_db("test",$connection);
$query="select * from users";
$result=mysql_query($query,$connection);
while($row=mysql_fetch_row($result))
{
echo "用户ID:".$row[0]."
";
echo "用户名:".$row[1]."
";
}
?>

3.
复制代码 代码如下:

$connection=mysql_connect("localhost","root","password"); //连接并选择数据库服务器
mysql_select_db("test",$connection);
$query="select * from users";
$result=mysql_query($query,$connection);
while($row=mysql_fetch_array($result))
{
echo "用户ID:".$row[0]."
"; //也可以写做$row["user_id"]
echo "用户名:".$row[1]."
"; //也可以写做$row["user_name"]
}
?>

4.
复制代码 代码如下:

$connection=mysql_connect("localhost","root","root"); //连接并选择数据库服务器
mysql_select_db("test",$connection);
$query="select * from users";
$result=mysql_query($query,$connection);
while($row=mysql_fetch_object($result))
{
echo "用户ID:".$row->user_id."
"; //通过对象运算符->获得改行数据在其属性上的值。
echo "用户名:".$row->user_name."
";
}
?>

5.综合比较:
mysql_result():优点在于使用方便;其缺点在于功能少,一次调用只能获取结果数据集中的一行元素,对较大型的数据库效率较低;
mysql_fetch_row():优点在于执行效率在4种方法中最高;不足在于只能用数字作为属性索引来获得属性值,在使用时非常容易出现混淆;
mysql_fetch_array():执行效率同样高,同mysql_fetch_row()相差无几,并界可以用属性名方式直接获得属性值,因此在实际应用中最常用;
mysql_fetch_object():采用了面向对象思想,在设计思路上更为先进,如果习惯于用面向对象的思路来写程序,则会很自地选择它。其次,该方法的优点还体现在,对于结构较为负责的数据结果,在逻辑上更为清晰。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template