PHP中mysql資料庫基礎操作
當前通過PHP+Mysql組合來開發網站是主流趨勢,通過PHP語言來操作mysql資料庫是一件很簡單的事情,下面我們來瞭解下怎樣通過php操作資料庫。
一 、建立資料表
create table user1(
id int primary key auto_increment,
name varchar(32) not null,
password varchar(64) not null,
email varchar(128) not null,
age unsigned tinyint not null
)
二 、給資料庫添加資料
insert into user1(name,password,email,age) value ('zs',md5('12345'),'zs@163.com',30);
三 、php操作mysql資料庫文法
1、串連mysql資料庫
$conn=mysql_connect("127.0.0.1","root","901822");
if(!$conn){
die("串連失敗".mysql_error());
}else{
echo "成功";
}
2、選擇資料庫
mysql_select_db("test");
3、設定編碼
mysql_query("set names utf8");
4、執行sql語句
$sql="select * from user1";
$sql="insert into user1(name,password,email,age) values('小明',md5('123'),'xiaoming@163.com',34)";
$res=mysql_equery($sql,$conn);
5、接收返回結果
while($row=mysql_fetch_row($res)){
echo "
$row[0]--$row[1]--$row[2]";
echo "
";
var_dump($row);
}
還有一種取法
$row=mysql_fetch_array($res);
foreach($row as $key=>$val){
echo "--$val";
}
echo "
";
}
6、釋放資源
mysql_free_result($res);
mysql_close($conn);
釋放資源$result,串連資料庫資源$conn,儘早關閉