You are on page 1of 4

BI 10: KT HP PHP V MYSQL TRONG NG DNG WEBSITE

bi trc, chng ta cng nghin cu v cc c php sql v Mysql c bn bao gm vic to bng, to kt ni, thm, sa, xa cc dng d liu trong c s d liu. V tip theo bi ny, chng ta s cng tm hiu v cch s dng mysql kt hp vi PHP xut ra d liu nh th no. lm vic vi mysql v PHP chng ta cn nm 6 hm c bn:

1- Kt ni c s d liu: C php: mysql_connect("hostname","user","pass")

2- La chn c s d liu: C php: mysql_select_db("tn_CSDL") V d: $conn=mysql_connect("localhost","root","root") or die(" khong the ket noi"); mysql_select_db("demo");

3- Thc thi cu lnh truy vn: C php: mysql_query("Cu truy vn y");

4- m s dng d liu trong bng: C php: mysql_num_rows(); Website hc trc tuyn www.videobook.vn

5- Ly d liu t bng a vo mng: C php: mysql_fetch_array();

6- ng kt ni c s d liu:

C php: mysql_close();

V d p dng: To c s d liu da trn tng on code sau: mysql -hlocalhost -uroot -proot mysql>create database demo_mysql; mysql> use demo_mysql; mysql>create table user(id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, username VARCHAR(50) NOT NULL, password CHAR(50) NOT NULL, PRIMARY KEY(id)); To trang test.php. u tin chng ta s kt ni c s d liu.

<?php $conn=mysql_connect("localhost", "root", "root") or die("can't connect database"); mysql_select_db("demo_mysql",$conn); ?>

Tip n vit cu truy vn ly ra tt c user t database.

<? Website hc trc tuyn www.videobook.vn

$sql="select * from user"; $query=mysql_query($sql); ?>

Kim tra xem trong bng d liu tn ti user no cha ?. Nu cha th xut ra thng bo li, ngc li th a chng vo mng v lp cho n ht bng d liu.

<? if(mysql_num_rows($query) == 0) { echo "Chua co du lieu"; } else { while($row=mysql_fetch_array($query)) { echo $row[username] ." - ".$row[password]."<br />"; } } ?> V cui cng chng ta ng kt ni v kt thc thao tc x l.

<? mysql_close($conn); ?> V cui cng l file hon chnh ca ng dng trn:

<? Website hc trc tuyn www.videobook.vn

$conn=mysql_connect("localhost", "root", "root") or die("can't connect database"); mysql_select_db("demo_mysql",$conn); $sql="select * from user"; $query=mysql_query($sql); if(mysql_num_rows($query) == 0) { echo "Chua co du lieu"; } else { while($row=mysql_fetch_array($query)) { echo $row[username] ." - ".$row[password]."<br />"; } } mysql_close($conn); ?> Tng kt:

bi ny chng ta lm vic vi sql v cc k thut kt ni vi database ca PHP. Cc hm PHP h tr mysql hin nay c rt nhiu. Tuy nhin v tnh nng cng nh phng thc s dng th chng cng ging nhau. Do vy cc bn khng nn lo lng khi lm vic vi nhng hm m chng ta ang nghin cu.

Website hc trc tuyn www.videobook.vn