Lập trình CSDL MySQL

Kết nối CSDL là đề tài muôn thuở của dân lập trình, với thiết kế web có nội dung thay đổi hàng ngày, bạn sử dụng MySQL để nhập và xuất dữ liệu ra trình duyệt. Sau đây là tóm tắt các thủ tục cần thiết để lập trình cơ sở dữ liệu MySQL với PHP

 1. Kết nối cơ sở dữ liệu

Để kết nối cơ sở dữ liệu MySQL, ta dùng lệnh mysqli_connect

$servername=’tên máy chủ’;

$username=’tài khoản có quyền truy cập’;

$password=’password của tài khoản’;

$database=’tên của CSDL’;

$db=mysqli_connect($servername,$username.$password,$database);

 2. Tạo bảng

Để tạo được một bảng (table) dữ liệu ta cần chuẩn bị một câu lệnh sql đưa vào biến $sql, ví dụ như sau

$sql=”CREATE TABLE users (userid INT unsigned NOT NULL auto_increment, user_name varchar (255) NOT NULL default ‘’, user_password  varchar(30) default ‘’);

Nếu dùng phương thức thủ tục ta thực hiện như sau

$result=mysqli_query($db, $sql);

Còn nếu dùng phương thức hướng đối tượng ta dùng câu lệnh

$result=$db->query ($sql);

 3. Nhập dữ liệu

Nếu trong database có một table, ví dụ table là USERS, để nhập dữ liệu ta tạo form để nhập vào các giá trị như use_name, user_password. Để tránh dài dòng coi như sau khi submit form ta lấy ra được hai biến là

$user_name=$_POST[‘user_name’];

$user_password=$_POST[‘user_password’];

Ta sẽ có một câu lệnh SQL như sau

$sql_in=’INSERT INTO users(user_name,user_password) VALUES($user_name,$user_password)’

Cũng tương tự ta gọi lệnh  

$result=$db->query($sql_in);

 4. Xuất dữ liệu ra màn hình

Để xuất dữ liệu ra màn hình ta soạn câu truy vấn

$sql_o=”select * from users”;

Lấy dữ liệu

$result= $db->query($sql_o);

Dữ liệu thu được là một mảng các dòng dữ liệu, lần lượt lấy  dữ liệu từng dòng và in ra màn hình như sau:

If(mysqli_num_row($result)>0){

    While($row=mysqli_fetch_array($result)){

    Echo $row[‘userid’].’ – ‘.$row[‘user_name’].’ – ‘.$row[‘user_password’];

    }

}

5. Xuất dữ liệu ra file excel

Để đọc dữ liệu từ MySQL rồi xuất ra file excel ta cần trải qua 2 công đoạn

B1. Đọc dữ liệu ra mảng

Đọc dữ liệu thì như đã trình bày ở trên, chỉ khác ở chỗ đọc xong đưa vào biến mảng chuẩn bị cho công đoạn 2

B2. Xuất dữ liệu ra file

Bao gồm các bước sau

-       Nạp thư viện IOFactory.php có trong bộ PHPExxcel

-       Khai báo kiểu file và tên file sẽ xuất

-       Load dữ liệu vào biến xuất

-       Tiến hành xuất file

 6. Import dữ liệu từ fie excel

Để đọc dữ liệu từ Excel ta dùng công cụ mã nguồn mở PHPExcel, tải từ trang github.com ta được một filw nén PHPExcel-1.8.zip, xả nén là chép lấy thư mục chứa mã nguồn là Classes vào site mình đang thiết kế

Sau đây là đoạn code minh họa để lấy dữ liệu từ excel

Để add thư viện cần lệnh

require('./Classes/PHPExcel/IOFactory.php');

Dữ liệu dĩ nhiên được khai báo và nhận từ form và tóm tắt việc lấy file như dòng sau

$importFileName=$_FILES['file']['tmp_name'];

Nhận dạng kiểu file

$importFileType=PHPExcel_IOFactory::identify($importFileName);

Tạo đối tượng reader

$objReader=PHPExcel_IOFactory::createReader($importFileType);

Đọc dữ liệu vào đối tượng excel

$objExcel=$objReader->load($importFileName);

Lấy dữ liệu của sheet

$sheet=$objExcel->getSheet('0');

Đọc số dòng dữ liệu hiện có

$HighestRow=$sheet->getHighestRow();

Lấy dữ liệu từng dong đưa vào biến để tạo query nhập

    for ($row=2; $row <=$HighestRow ; $row++) {

              $user_name=$sheet->getCellByColumnAndRow(0,$row)->getValue();

              $user_passhash=md5($user_name);

              $firstName=$sheet->getCellByColumnAndRow(1,$row)->getValue();

              //$lastName=$sheet->getCellByColumnAndRow(3,$row);

              $sql="insert into ".$prefix."users(user_name, user_passhash,
                        user_firstname) values('$user_name','$user_passhash','$firstName') ";

              $db->query($sql);

              error_reporting();

    }//end for

Kết quả là sẽ import các dòng dữ liệu vao table users có các file user_name, user_passhash, first_name, last_name…