php學習正式起航(6)

來源:互聯網
上載者:User
現在講講php的錯誤處理

<?php$file=fopen("1.txt","r");?>

如果檔案不存在 系統會直接報錯誤
用die就可以自己寫錯誤資訊 die是死亡的意思,表示錯誤

為了避免使用者獲得類似上面的錯誤訊息,我們在訪問檔案之前檢測該檔案是否存在

<?phpif(!file_exists("1.txt")){die("File not found");}else{$file=fopen("1.txt","r");}?>

如果檔案不存在,會列印File not found,而不是系統冒出的錯誤


其實php的錯誤處理遠不止這些,後面還有異常等
放在以後在說吧

現在開始重頭戲,終於要用php對mysql資料庫進行操作了

首先是串連資料庫

<?php$link = mysql_connect('localhost','root','');if (!$link) {die('Could not connect to MySQL: ' . mysql_error());}echo 'Connection OK'; mysql_close($link);?>

$link 這個又是一個資源變數,表示資料庫連接狀態,你可以試著列印看看會出現什麼
mysql_connect函數就是串連mysql資料庫啦
有3個函數 分別是伺服器位址 資料庫使用者名稱 資料庫使用者密碼
mysql_error函數可以知道串連錯誤原因
mysql_close是關閉資料庫連接

現在先建立一個資料庫
create database test;
然後建立一個表

超級簡單吧

進入phpmyadmin看看

首先我們插入幾條資料看看

現在會串連mysql資料庫了,接著我們要在mysql其中一個資料庫裡插入資料了

<?php$link = mysql_connect('localhost','root','');if (!$link) {die('Could not connect to MySQL: ' . mysql_error());}mysql_select_db('test',$link);mysql_query("insert into user (name,age) values ('harry',15)",$link);mysql_close($link);?>

mysql_select_db就是選擇資料庫的函數
mysql_query就是執行sql語句的函數,任何sql都可執行,包括建立資料庫和表
兩個函數的第2個參數可以省略
mysql_select_db('test');
mysql_query("insert into user (name,age) values ('harry',15)");
如果第2個參數沒有指定串連標識符,則使用上一個開啟的串連。如果沒有開啟的串連,將無參數調用 mysql_connect() 來嘗試開啟一個並使用之

現在看看是否能插入成功

ok 已經插入了

現在我們用表單形式插入資料

<html><body> <form action="" method="post">Name: <input type="text" name="name" />Age: <input type="text" name="age" /><input type="submit" /></form> </body></html>
<?php$name=$_POST['name'];$age=$_POST['age'];if(isset($name)&&isset($age)){$link = mysql_connect('localhost','root','');if (!$link) {die('Could not connect to MySQL: ' . mysql_error());}mysql_select_db('test');$sql="insert into user (name,age) values ('$name',$age)";if(mysql_query($sql))echo "Insert Success!";elseecho "Insert Fail!".mysql_error();mysql_close($link);}?>

mysql_query() 在執行sql語句成功時返回 TRUE,出錯時返回 FALSE

現在來顯示資料吧

<html><body> <form action="" method="post">Name: <input type="text" name="name" />Age: <input type="text" name="age" /><input type="submit" /></form><?php//資料庫連接$link = mysql_connect('localhost','root','');if (!$link) {die('Could not connect to MySQL: ' . mysql_error());}mysql_select_db('test'); //插入$name=$_POST['name'];$age=$_POST['age'];if(isset($name)&&isset($age)){ $sql="insert into user (name,age) values ('$name',$age)";if(mysql_query($sql))echo "Insert Success!";elseecho "Insert Fail!".mysql_error(); }//查詢$sql="select * from user";$result=mysql_query($sql);while($row = mysql_fetch_array($result)){echo "<table>";echo "<tr>";echo "<td>" . $row['id'] . "</td>";echo "<td>" . $row['name'] . "</td>";echo "<td>" . $row['age'] . "</td>";echo "</tr>";echo "</table>";} mysql_free_result($result);mysql_close($link); ?></body></html>


$result=mysql_query($sql); $result也是一個資源變數,當mysql_query執行查詢sql語句的時候,其返回結果就不再是true和false ,而是個結果集,你可以想象就是mysql_query查詢的結果返回一張表給了$result,$result就是一張表(結果集)

mysql_fetch_array函數則是專門處理結果集的,從結果集中取得一行作為關聯陣列,或數字數組,或二者兼有,mysql_query($sql); 其本身就是結果集了
為什麼要迴圈呢,因為mysql_fetch_array一次只能在結果集(表)取一行資料
然後把這一行資料以一維關聯陣列的形式給$row,$row就是一維關聯陣列
mysql_fetch_array有個指標指著每一行,每當執行完這個函數的時候,指標就自動指向下一行,如果當函數再次被執行,就能擷取到這行的資料,直到最後一行,指標就會指向空的,所以迴圈也會因為空白而結束
不要以為$row是二維數組,它一直是一維,而且每迴圈一次就被重新賦值一次
有人可能懷疑,數組也能做為迴圈條件?可以的
$a=array(1,2)
while($a)
這樣是能夠迴圈的,只不過是死迴圈
因為while括弧裡只要不為0的東東都能迴圈


$row['name'] 就個就是從數組裡取值了,關聯陣列還記得吧
其實用數組下標也可以的,之前沒說,其實關聯陣列也具有普通數組的特性,且更強大
所以這是可以的

echo "<td>" . $row[0] . "</td>";echo "<td>" . $row[1] . "</td>";echo "<td>" . $row[2] . "</td>";

mysql_free_result是釋放資源
不是必須使用,僅需要在考慮到返回很大的結果集時會佔用多少記憶體時調用。在指令碼結束後所有關聯的記憶體都會被自動釋放的


另外mysql_fetch_row也可以查詢結果,不過跟mysql_fetch_array比,弱爆了,這裡只是介紹下曾經有這麼個東西。。。

//查詢

$sql="select * from user";$result=mysql_query($sql);while($row = mysql_fetch_row($result)){echo "<table>";echo "<tr>";echo "<td>" . $row[0] . "</td>";echo "<td>" . $row[1] . "</td>";echo "<td>" . $row[2] . "</td>";echo "</tr>";echo "</table>";}

mysql_fetch_row() 從和指定的結果標識關聯的結果集中取得一行資料並作為數組返回。每個結果的列儲存在一個數組的單元中
則row不再是關聯陣列而是普通數組,所以只能用數組下標


下面說說幾個常用的資料顯示函數
int mysql_num_rows ( resource $result )
mysql_num_rows() 返回結果集中行的數目。此命令僅對 SELECT 語句有效
int mysql_num_fields ( resource $result )
mysql_num_fields() 返回結果集中欄位的數目
int mysql_insert_id ([ resource $link_identifier ] )
mysql_insert_id() 返回給定的 link_identifier 中上一步 INSERT 查詢中產生的 AUTO_INCREMENT 的 識別碼

重新寫下

<?phpheader("Content-Type:text/html;charset=gbk");error_reporting(0);?> <html><body> <form action="" method="post">Name: <input type="text" name="name" />Age: <input type="text" name="age" /><input type="submit" /></form> <?php//資料庫連接$link = mysql_connect('localhost','root','');if (!$link) {die('Could not connect to MySQL: ' . mysql_error());}mysql_select_db('test'); //插入$name=$_POST['name'];$age=$_POST['age'];if(isset($name)&&isset($age)){ $sql="insert into user (name,age) values ('$name',$age)";if(mysql_query($sql))echo "Insert Success!";elseecho "Insert Fail!".mysql_error(); } //查詢$sql="select * from user";$result=mysql_query($sql);while($row = mysql_fetch_row($result)){echo "<table>";echo "<tr>";echo "<td>" . $row[0] . "</td>";echo "<td>" . $row[1] . "</td>";echo "<td>" . $row[2] . "</td>";echo "</tr>";echo "</table>";}echo "總共".mysql_num_rows($result)."記錄<br/>";echo "每行".mysql_num_fields($result)."欄位";mysql_free_result($result);mysql_close($link);?></body></html>

header("Content-Type:text/html;charset=gbk"); 這個是表明檔案編碼格式,顯示中文需要這樣
error_reporting(0); 屏蔽一切系統提示的注意,警告,和錯誤

現在完成 修改和刪除部分

<?phpheader("Content-Type:text/html;charset=gbk");error_reporting(0);?> <html><body> <form action="" method="post">Name: <input type="text" name="name" />Age: <input type="text" name="age" /><input type="submit" /></form> <?php//資料庫連接$link = mysql_connect('localhost','root','');if (!$link) {die('Could not connect to MySQL: ' . mysql_error());}mysql_select_db('test');//插入$name=$_POST['name'];$age=$_POST['age'];if(isset($name)&&isset($age)){ $sql="insert into user (name,age) values ('$name',$age)";if(mysql_query($sql))echo "Insert Success!";elseecho "Insert Fail!".mysql_error(); } //查詢$sql="select * from user";$result=mysql_query($sql);while($row = mysql_fetch_array($result)){?><form action="" method="post">ID: <?=$row['id']?>Name: <input type="text" name="_name" value="<?=$row['name']?>"/>Age: <input type="text" name="_age" value="<?=$row['age']?>" /><input type="hidden" name="id" value="<?=$row['id']?>" /><input type="submit" value="修改"/><a href="index.php?uid=<?=$row['id']?>">刪除</a></form> <?php} echo "總共".mysql_num_rows($result)."記錄<br/>";echo "每行".mysql_num_fields($result)."欄位";//修改$name=$_POST['_name'];$age=$_POST['_age'];$id=$_POST['id'];if(isset($name)&&isset($age)&&isset($id)){ $sql="update user set name='$name',age='$age' where id=$id";if(mysql_query($sql))header("location:index.php");elseecho "Update Fail!".mysql_error(); }//刪除$uid=$_GET['uid'];if(isset($uid)){ $sql="delete from user where id=$uid";if(mysql_query($sql))header("location:index.php");elseecho "Delete Fail!".mysql_error(); }mysql_close($link); ?></body></html>


至此,php對mysql資料庫的增刪改查操作就全在這一個頁面了,灰常的簡單

加了個簡單的分頁,超簡單的。。。。暫時就不講解怎麼個來的了,加了簡單的注釋,大家應該能看懂代碼

<?phpheader("Content-Type:text/html;charset=gbk");error_reporting(0);?> <html><body> <form action="" method="post">Name: <input type="text" name="name" />Age: <input type="text" name="age" /><input type="submit" /></form> <?php//資料庫連接$link = mysql_connect('localhost','root','');if (!$link) {die('Could not connect to MySQL: ' . mysql_error());}mysql_select_db('test'); //插入$name=$_POST['name'];$age=$_POST['age'];if(isset($name)&&isset($age)){ $sql="insert into user (name,age) values ('$name',$age)";if(mysql_query($sql))echo "Insert Success!";elseecho "Insert Fail!".mysql_error(); } //分頁查詢if(isset($_GET['pager']))$pager=($_GET['pager']-1)*5;else$pager=0; $sql="select * from user";$result=mysql_query($sql);$num=mysql_num_rows($result); //總共記錄數$page=ceil($num/5); //總共多少頁 這裡每頁5條記錄 ceil函數四捨五入的。。for($i=1;$i<=$page;$i++)echo "<a href='index.php?pager=".$i."'>".$i."</a>"; $sql="select * from user limit $pager,5";$result=mysql_query($sql);while($row = mysql_fetch_array($result)){?><form action="" method="post">ID: <?=$row['id']?>Name: <input type="text" name="_name" value="<?=$row['name']?>"/>Age: <input type="text" name="_age" value="<?=$row['age']?>" /><input type="hidden" name="id" value="<?=$row['id']?>" /><input type="submit" value="修改"/><a href="index.php?uid=<?=$row['id']?>">刪除</a></form> <?php} echo "總共".$num."記錄<br/>";echo "每行".mysql_num_fields($result)."欄位"; //修改$name=$_POST['_name'];$age=$_POST['_age'];$id=$_POST['id'];if(isset($name)&&isset($age)&&isset($id)){ $sql="update user set name='$name',age='$age' where id=$id";if(mysql_query($sql))header("location:index.php");elseecho "Update Fail!".mysql_error(); }//刪除$uid=$_GET['uid'];if(isset($uid)){ $sql="delete from user where id=$uid";if(mysql_query($sql))header("location:index.php");elseecho "Delete Fail!".mysql_error(); }mysql_close($link); ?></body></html>

暫時先到這裡了
php後面內容還有很多,還有對象等知識,光資料操作就還有物件導向的

以上就是php學習正式起航(6)的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.