PHP連接MySQL數據庫
阿新 • • 發佈:2017-07-08
關閉 ould passwd name cti mysqli blog 自動 標識符
在新版本PHP中,過去的mysql_系列函數已被棄用,這裏使用的是mysqli。
建立連接:
$con=mysqli_connect(servername,username,password);
對於連接失敗的處理:
if (!$con) { die("Could not connect"); }
設置活動的 MySQL 數據庫:
mysqli_select_db($con,databasename);
以上工作做完以後,就可以對數據庫進行操作了。以下介紹一些常用函數:
mysqli_query(connection,query,resultmode); //執行針對數據庫的查詢,即執行一條sql語句。
mysqli_num_rows(result); //返回結果集中行的數量。result為由 mysqli_query()、mysqli_store_result() 或 mysqli_use_result() 返回的結果集標識符。
mysqli_fetch_array(result,resulttype); //從結果集中取得一行作為關聯數組,或數字數組,或二者兼有。
例:
$user=$_POST[‘user‘]; $passwd=$_POST[‘passwd‘]; $con= mysqli_connect("localhost","root","123456"); if (!$con) {die("Could not connect"); } mysqli_select_db($con,"test"); $sql="select * from Account where user=‘{$user}‘"; $insert_sql="insert into Account (user,passwd) values (‘{$user}‘,‘{$passwd}‘)"; $result=mysqli_query($con,$sql); if (mysqli_num_rows($result)!=0) { echo "抱歉,用戶名已存在!"; } else { mysqli_query($con,$insert_sql); echo "註冊成功!"; } mysqli_close($con); //可選操作,因為已打開的非持久連接會在腳本執行完畢後自動關閉。
PHP連接MySQL數據庫