Cac buoc ket noi PHP voi mysql

Go down

Cac buoc ket noi PHP voi mysql

Bài gửi by Admin on Fri Aug 07, 2015 10:00 am

Code:

/* ket noi voi server
buoc 1:
mysql_connect(ten_server,user,password)
hoac bien=mysql_connect(ten_server,user,password)
dung if
or die("ket noi server that bai")
or die("ket noi server that bai".mysql_error());

ket noi voi csdl
buoc 2:
mysql_select_db(ten_csdl);
hoac
mysql_select_db(ten_csdl,bien);

Chuoi truy van
buoc 3:
select, delete, insert, update
Thuc thi cau truy van
buoc 4:
mysql_query(buoc 3);

dong ket noi csdl
buoc 5:
mysql_close(bien);
Rieng o buoc 3 la cau lenh select thi buoc 4 thay doi nhu sau:
buoc 4:
$bientam=mysql_query(buoc3);
buoc 4.1: lay du lieu trong csdl ra ngoai gan vao mang
$r=mysql_fetch_array(buoc 4) // lay 1 dong
hoac
while($r=mysql_fetch_array(buoc 4)) lay het cac dong
buoc 4.2: xuat ra man hinh
echo $r[0]....$r[n]

*/
Demo:
HTML
Code:

<form action="" method="post" name="f2">
Ten:<input type="text" name="txtten" /><br />
Dia chi:<input type="text" name="txtdc" /><br />
Ngay:<input type="text" name="txtngay" /><br />
<input type="submit" value="Them" name="sbthem" />
<input type="submit" value="Hien Thi" name="sbhienthi" />
</form>
Xu ly php
Code:

// cau lenh insert
//b1
$kn=mysqli_connect("localhost","root","") or die ("khong ket noi voi server");
//b2
mysqli_select_db($kn,"CN10");
if(isset($_REQUEST['sbthem'])){
$ten=$_REQUEST['txtten'];
$dc=$_REQUEST['txtdc'];
$ngay=$_REQUEST['txtngay'];
//b3
$sql="insert into tblbang1(Ten,Diachi,NgaySinh) values('$ten','$dc','$ngay')";
//b4
mysqli_query($kn,$sql);
}
Xoa
Code:

if(isset($_REQUEST['id'])){
$id=$_REQUEST['id'];
//b3
$sql="delete from tblbang1 where Id='$id'";
//b4
mysqli_query($kn,$sql);
}
Hien thi
Code:

if(isset($_REQUEST['sbhienthi'])){
//b3
$sql="select * from tblbang1";
//b4
$rs=mysqli_query($kn,$sql);
http://b4.1
echo "<table border=1>";
echo "<tr><td>Id</td><td>Ten</td><td>Dia chi</td><td>Ngay sinh</td><td></td><td></td></tr>";
while($r=mysqli_fetch_array($rs)){
   echo "<tr><td>$r[0]</td><td>$r[1]</td><td>$r[2]</td><td>$r[3]</td><td>Sua</td><td><a href='?id=$r[0]'>Xoa</a></td></tr>";
   }
echo "</table>";
}
Dong ket noi
Code:

mysql_close($kn);
avatar
Admin
Admin

Tổng số bài gửi : 22
Join date : 18/03/2014
Age : 31

Xem lý lịch thành viên http://phuocmien.forumvi.com

Về Đầu Trang Go down

Về Đầu Trang


 
Permissions in this forum:
Bạn không có quyền trả lời bài viết