01/10/2018, 13:38

Cần chỉ về cách hàm lấy dữ liệu ra ngoài web

chào mọi người e đang học php hướng đối tượng nhưng e làm được phần insert và update dữ liệu vào.còn view dữ liệu ra e làm mãi 1 tuần vẫn chưa ra.mong mọi người giúp đỡ.đây là 3 file hướng đối tượng của e
-file connect database

<?php
	class Database {
		private $conn;
		private $host;
		private $user;
		private $password;
		private $baseName;
		private $port;
		private $Debug;
		private $dbname;
		private $Error;
		private $BadQuery;
		private $NumRows;
		
		function __construct($params=array()){
			$this->conn = false;
			$this->host = 'localhost';
			$this->user = 'root';
			$this->password = '123456';
			$this->port = '3306';
			$this->Debug = true;
			$this->dbname='user';
			$this->connect();
		}
		
		function _destruct(){
			$this->disconnect();	
		}	
		
		function connect(){
			if(!$this->conn){
				$this->conn = mysqli_connect($this->host,$this->user,$this->password, $this->dbname);

				if(!$this->conn){
					$this->status_fatal=true;
					echo'connection db failed';
					die();
				}else{
					$this->status_fatal=false;
				}	
			} 	
			return $this->conn;
		}
		function disconnect(){

		}
		function getAll($query){
			$cnx = $this->conn;
			if(!$cnx || $this->status_fatal){
				echo ' getall -> connection bdd failed';
				die();
			}

				$cur = mysqli_query($this->conn, $query);
				$return = array();
			while($data = mysqli_fetch_assoc($cur)) { 
				array_push($return, $data);
			} 
 
			return $return;
		}
		function execute($query,$use_slave=false){
			$cnx=$this->conn;
			if(!$cnx||$this->status_fatal){
				return null;
			}
			$cur = mysqli_query($cnx, $query);
			if($cur==false){
				$ErrorMessage=@mysqli_last_error($cnx);
				$this->handleError($query,$ErrorMessage);
			}else{
				$this->Error=false;
				$this->BadQuery=$query;
				$this->NumRows=mysqli_affected_rows($cnx);
				return;
			}
			@mysqli_free_result($cur);	
		}
		function handleError($query,$str_erreur){
			$this->Error=true;
			$this->BadQuery=$query;
			if($this->Debug){
				echo"query:".$query."</br>>";
				echo"error:".$str_erreur."</br>>";
			}
		}
	}
?>

2.file modun trong php

<?php
	include'db.php';
	class Address{
		protected $db;
		private $id;
		private $address;
		private $city;
		private $zipcode;
		private $user_id;
		
		public function __construct($id=',$address=',$city=',$zipcode=',$user_id='){
			$this->db= new Database;
			$this->id=$id;
			$this->address=$address;
			$this->city=$city;
			$this->zipcode=$zipcode;
			$this->user_id=$user_id;		
		}
		public function setId($id){
			$this->id= $id;	
		}
		public function getId(){
			return $this->id;
		}
		public function setAddress($address) {
     		$this->address = $address;
		}
		public function getAddress() {
  			 return $this->address;
		}
		public function setCity($city) {
     		$this->city = $city;
		}
		public function getCity() {
  			 return $this->city;
		}
		public function setZipcode($zipcode) {
     		$this->zipcode = $zipcode;
		}
		public function getZipcode() {
  			 return $this->zipcode;
		}
		public function setUserid($user_id) {
     		$this->user_id = $user_id;
		}
		public function getUserid() {
  			 return $this->user_id;
		}
		function getAddressById(){
			$id=$this->getId();
			$sql="SELECT * FROM address where id =$id";
			return $sql;	
		}
		function getList(){
			global $conn;
			$sql="SELECT * FROM address order by id DESC";
			$result=$this->db->execute($sql);
			return $result;
		}

		function insert(){
			$address = $this->getAddress();
			$city = $this->getCity();
			$zipcode=$this->getZipcode();
			$userid=$this->getUserid();
			global $conn;
			$sql="INSERT INTO address (address, city, zipcode, user_id) VALUES ('$address', '$city', '$zipcode', '$userid')";
			$this->db->execute($sql);
		}
		function upDate(){
		$id=$this->getId();
		$address=$this->getAddress();
		$city=$this->getCity();
		$zipcode=$this->getZipcode();
		$userid=$this->getUserid();
		global $conn;
		$sql="UPDATE address SET address='".$address."', city='".$city."', zipcode='".$zipcode."', user_id='$userid' WHERE id=$id";
        $this->db->execute($sql);
		}
		function delete(){
			global $conn;
			$sql="DELETE FROM address where id= $id";
			$this->db->execute($sql);
		}	
	}
?>

3.file view trong php

<?php 
include 'Address.php';
session_start();
if(!isset($_SESSION['ses_name'])){
		header("location:login.php");
}
echo '<a href="logout.php">Đăng xuất</a>';
?>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">	
    <link rel="stylesheet" type="text/css" href="stype.css">
</head>
<p>Xin chào <?php echo $_SESSION['ses_name']; ?></p>
<div id="left" align="center">
		<legend>Thông tin address</legend>
	<div class="divfirst">
	<div class="divlast">
				<div class="Cell">stt</div>
				<div class="Cell">address</div>
				<div class="Cell">city</div>
				<div class="Cell">zipcode</div>
				<div class="Cell">user_id</div>
                <div class="Cell">Sửa</div>
                <div class="Cell">Xóa</div>
                <?php 
				$address=new Address();
				$address->getList();
					foreach ($address as $row){
						echo"<div class='Row'>
		<div class='Cell'>$row[id]</div>
		<div class='Cell'>$row[address]</div>
		<div class='Cell'>$row[city]</div>
		<div class='Cell'>$row[zipcode]</div>
		<div class='Cell'>$row[user_id]</div>
		<div class='Cell'><a href = 'edit_add.php?id= $row[id]'>edit</a></div>
		<div class='Cell'><a href = 'del_add.php?id= $row[id]';>delete</a></div>
		</div>";
					}
				?>
	</div>
</div>
</div>
</html>

e làm mãi mà nó không lấy ra được hàm danh sách.mong mọi người giúp e cái hàm getlist trên.e phải viết thế nào?

Vô Thin viết 15:42 ngày 01/10/2018

e làm mãi mà nó không lấy ra được hàm danh sách.mong mọi người giúp e cái hàm getlist trên.e phải viết thế nào?

Nó không lấy được hàm hay hàm không chạy được/ chạy sai? Thử chỗ return $result trong getList() của bạn thành vardump($result) hoặc print_r($result) xem thử lúc chạy nó ra gì không?

Trong Tue viết 15:49 ngày 01/10/2018

print_r($result)

nó chạy ra nhưng dữ liệu không hiển thị.vì khi e return thì nó không có giá trị trả về.
giống như hàm bên file connect database
function getAll($query){
$cnx = $this->conn;
if(!$cnx || $this->status_fatal){
echo ’ getall -> connection bdd failed’;
die();
}

			$cur = mysqli_query($this->conn, $query);
			$return = array();
		while($data = mysqli_fetch_assoc($cur)) { 
			array_push($return, $data);
		} 

		return $return;
	}

thì nó có $return=array();
nên khi return giá trị trả về có đó.
e làm theo cách của anh(chị) chỉ rồi nhưng nó báo lỗi Undefined variable.

Vô Thin viết 15:47 ngày 01/10/2018

Giờ dò từng bước thử xem chứ cũng khó biết thế nào:

function getList(){
		global $conn;
            print_r($conn); // xem thử có nhận được kết nối chỗ này?
		$sql="SELECT * FROM address order by id DESC";
		$result=$this->db->execute($sql);
            print_r($result); // xem thử câu query có thực thi được không hay báo lỗi
		//return $result;
           // kiểm tra lại khai báo các tên biến có bị gõ nhầm/ sai chỗ nào, scope xem nó có ổn chưa?
         // câu SQL có đề cập đến table address (viết có chính xác không) - lấy chạy thử ở phpMyAdmin hoặc command line của MySQL xem có ra gì không? Table đó có dòng dữ liệu mẫu nào chưa hay trống trơn?
	}

Dò kỹ lại các thức trên, thậm chí là lấy hàm ra ngoài Class để chạy thuần không liên quan gì Class đã kết nối được chưa? Khi đưa vào Class thì quan hệ giữa các biến, phạm vi của biến thế nào… Sử dụng các print_r và vardump từng đoạn 1 để xuất các biến ra xem thử giá trị nó có tạo ra được không. Bật error_reporting (trong file php.ini) lên để xem báo lỗi đế đoán biết do đâu.

Trong Tue viết 15:49 ngày 01/10/2018

không được ạ! mình đã xem test lại .
câu kết nối $conn được hết.câu truy vấn sql mình đã test trong phpmysql chạy ra bảng dữ liệu.đã có 10 dòng dữ liệu trong rồi.
vấn đề mình thấy ở đây là câu return trả về không có giá trị nên nó không hiển thị ra được.
1 câu thi return null, 1 câu thì return; thì có trả về được gì đâu? còn bạn để ý câu getAll trong file đầu tiên mình gửi có hàm giá trị trả về đó.nhưng minhg không biết cách viết gán giá trj trả về thế nào?

Vô Thin viết 15:53 ngày 01/10/2018

1 câu thi return null, 1 câu thì return; thì có trả về được gì đâu? còn bạn để ý câu getAll trong file đầu tiên mình gửi có hàm giá trị trả về đó.nhưng minhg không biết cách viết gán giá trj trả về thế nào?

Lý do mình muốn biết là trước lúc trả về, thì $result có chứa gì không? Cho nên mới đề nghị bạn là vardump($result) hoặc print_r($result) để xem là nó có lấy về được 10 dòng gì đó như bạn nói hay không? Nếu nó có, thì có nghĩa là sau khi return thì $result không được gán vào getList() <= phải xem lại khai báo getList() như thế nào, có gọi đúng nó không? Ta cũng có thể thay vì return $result thì ta gán một biến global cho $result để kiểm tra xem liệu nó có lấy được giá trị $result gán vào không? Nếu global mà không được nữa, chứng tỏ câu SQL bị trục trặc, $result không có kết quả gì hoặc $result=$this->db->execute($sql); <= có vấn đề, ta tách cái này ra khỏi Class, viết bình thường xem nó có chạy ra gì không?

Mà đã bật chế độ báo lỗi trong php.ini lên chưa, cho báo lỗi ở mức cao nhất, kể cả notes và warning luôn để xem các thông báo, gỡ rối dễ hơn.

Quang Vu Quang viết 15:51 ngày 01/10/2018

$result=$this->db->execute($sql);

[2.file modun trong php] => function getList()
Nếu nhớ không nhầm func execute này dùng thực thi, nó không trả vể data.
Muốn query bác phải dùng mysqli_query mới đúng.

Bài liên quan
0