$conn=mysql_connect("localhost","root","");
$select=mysql_select_db("books",$conn);
$query="insert into computers(name,price,publish_data) ";
$query.="values('JSP',28.00,'2008-11-1')";
$query="select * from computers";
$result=mysql_query($query);
//以下是使用mysql_result()函數來獲取到查詢結果
$num=mysql_num_rows($result);
for($rows_count=0;$rows_count<$num;$rows_count++){
echo "書名:".mysql_result($result,$rows_count,"name");
echo "價格:".mysql_result($result,$rows_count,"price");
echo "出版日期:".mysql_result($result,$rows_count,"publish_data")."<br>";
}
//以下是使用mysql_fetch_row()函數來獲取到查詢結果
while($row=mysql_fetch_row($result))
{
echo "書號:".$row[0]."<br>";
echo "書名:".$row[1]."<br>";
echo "價格:".$row[2]."<br>";
echo "出版日期:".$row[3]."<br>";
echo "<br>";
}
//以下是使用mysql_fetch_array()函數來獲取到查詢結果
while($row=mysql_fetch_array($result))
{
echo "書號:".$row[0]."<br>";
echo "書名:".$row[1]."<br>";
echo "價格:".$row["price"]."<br>";
echo "出版日期:".$row["publish_data"]."<br>";
echo "<br>";
}
//mysql_fetch_assoc()同mysql_fetch_array($result,MYSQL_ASSOC)一樣
while($row = mysql_fetch_assoc($res)){
echo $row['price'].'::'.$row['publish_data'].”;
} //$row[0]不能取值
while($row=mysql_fetch_object($result))
{
echo "書號:".$row->id."<br>";
echo "書名:".$row->name."<br>";
echo "價格:".$row->price."<br>";
echo "出版日期:".$row->publish_data."<br>";
echo "<br>";
}
?>
本節主要介紹了獲取查詢結果集的4個函數,此處對它們進行綜合比較。
● mysql_result():優點在於使用方便;而缺點在於功能少,一次調用只能獲取結果數據集中的一行記錄,對較大型的數據庫效率較低。
● mysql_fetch_row():優點在於執行效率在4種方法中最高;不足在於只能用數字作爲屬性索引來獲得屬性值,在使用時非常容易出現混淆。
● mysql_fetch_array():執行效率同樣很高,同mysql_fetch_row()相差無幾,並且可以用屬性名方式直接獲取得屬性值,因此,在實際應用中最常用。
● mysql_fetch_object():採用了面向對象的思想,在設計思路上更爲先進,如果讀者習慣於面向對象的思路來寫程序,則會很自然的選擇它。其次,該方法的優點還體現在,對於結構較爲複雜的數據結果,在邏輯上顯得更爲清晰。
int mysql_data_seek(int result_identifier,int row_number)
調用該函數可以在結果集中向後滑動row_number行,在下一次調用mysql_fetch_*函數時,讀取的將是向後滑動row_number行後的記錄。