PHP查詢Mysql資料庫範例程式碼

來源:互聯網
上載者:User

1.<!--使用mysql_result()來擷取資料-->

 代碼如下 複製代碼

<?php
$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!<br>";
else{
$query="select * from users"; //查詢資料
$result=mysql_query($query,$connection);
for($rows_count=0;$rows_count<7;$rows_count++) //用mysql_result獲得資料並輸出,mysql_result() 返回 MySQL 結果集中一個單元的內容。
{
echo "使用者ID:".mysql_result($result,$rows_count,"user_id")."<br>";
echo "使用者名稱:".mysql_result($result,$rows_count,"user_name")."<br>";
}
}
?>

2.<!--使用mysql_fetch_row()來擷取資料,以數組的形式返回查詢結果-->

 

 代碼如下 複製代碼
<?php
$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]."<br>";
echo "使用者名稱:".$row[1]."<br>";
}
?>

3.<!--使用mysql_fetch_array()來擷取資料,同mysql_fetch_row()類似,也是擷取結果集中當前行資料,並在調用後自動滑向下一行-->

 

 代碼如下 複製代碼
<?php
$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]."<br>"; //也可以寫做$row["user_id"]
echo "使用者名稱:".$row[1]."<br>"; //也可以寫做$row["user_name"]
}
?>

4.<!-- 使用mysql_fetch_object()以對象的形式返回查詢結果,也是用於查詢資料結果集,返回當前行資料,並自動滑向下一行,不同的是它返回的 是一個對象,這個對象的屬性集合即為資料的屬性集合,而屬性上的值則為資料庫中當前行該屬性上的值-->

 代碼如下 複製代碼

 

<?php
$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."<br>"; //通過對象運算子->獲得改行資料在其屬性上的值。
echo "使用者名稱:".$row->user_name."<br>";
}
?>

5.綜合比較:


mysql_result():優點在於使用方便;其缺點在於功能少,一次調用只能擷取結果資料集中的一行元素,對較大型的資料庫效率較低;
mysql_fetch_row():優點在於執行效率在4種方法中最高;不足在於只能用數字作為屬性索引來獲得屬性值,在使用時非常容易出現混淆;
mysql_fetch_array():執行效率同樣高,同mysql_fetch_row()相差無幾,並界可以用屬性名稱方式直接獲得屬性值,因此在實際應用中最常用;
mysql_fetch_object():採用了物件導向思想,在設計思路上更為先進,如果習慣於用物件導向的思路來寫程式,則會很自地選擇它。其次,該方法的優點還體現在,對於結構較為負責的資料結果,在邏輯上更為清晰。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.