BÀI 3 - LẤY DỮ LIỆU TỪ CƠ SỞ DỮ LIỆU
Video bài học
Bước 1: Tạo chương trình kết nối với database.
Bước 2: Tham chiếu đến từng dữ liệu trong database.
Bước 3: Xuất dữ liệu thành file json.
Bước 1: Tạo file connect.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "shoprobot";
$conn = mysqli_connect($host, $username, $password, $database);
mysqli_query($conn, "SET NAMES '.utf8.'");
// if ($conn){
// echo "Successfully";
// } else {
// echo "Unsuccessfully";
// }
?>
Bước 2: Tạo file lấy dữ liệu getdulieu.php
<?php
include "connect.php";
$query = "SELECT * FROM loaisanpham";
$data = mysqli_query($conn, $query);
$mangloaisp = array();
while($row = mysqli_fetch_assoc($data)) {
array_push($mangloaisp, new Loaisp(
$row['ID'],
$row['tenLoaiSanPham'],
$row['hinhAnhLoaiSanPham']));
}
echo json_encode($mangloaisp); //Xuất file json
class Loaisp{
function __construct($id, $tenloaisp, $hinhanhloaisp){
$this->ID = $id;
$this->tenLoaiSanPham = $tenloaisp;
$this->hinhAnhLoaiSanPham = $hinhanhloaisp;
}
}
?>