Em đang học tí về php và chưa hiểu biết mấy về nó mà em đang gõ demo mà nó báo lỗi như vầy ai giúp em hiểu vs
Đẩy data ra chuỗi json trong php
1 Like
Bạn dán cái code lên màn hình luôn, nhìn cái hình tốn công gõ lại lắm, tui tư vấn cho nhé
Vấn đề là ở chỗ này
while(...
$res[]=$row;//you wrong here!!!
}
Phải làm thế này
$res=array();
while(....){
array_push($res,$row);
}
//In ra cho nó đẹp luôn
echo "<pre>".json_encode($res, JSON_PRETTY_PRINT)."</pre>";
Theo bác thì dòng code này nó sai ở đâu @@
<?php
//Importing Database Script
require_once('dbConnect.php');
//Creating sql query
$sql = "SELECT * FROM lop11305";
//getting result
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"id"=>$row['id'],
"name"=>$row['name'],
"masv"=>$row['masv'],
"link"=>$row['link'],
"DTB"=>$row['DTB']
));
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"id"=>$row['id'],
"name"=>$row['name'],
"masv"=>$row['masv'],
"link"=>$row['link'],
"DTB"=>$row['DTB']
));
}
Đoạn này không sai, nhưng bạn chạy thử thì biết ngay chứ sao hỏi tôi, vì kiểm tra kỹ kẻo ghi nhầm các tên field
Đầu tiên test bạn làm thế này cho gọn
while($row=mysqli_fetch_array($r){
array_push($result,$row);
}
Nếu muốn tách field thì làm thế này hay hơn
while($row=mysqli_fetch_array($r){
$tmp=array();
foreach($row as $k=>$v){
if(in_array( $k, array( 'id','ten','tuoi','v.v' ) ) ){
$tmp[$k]=$v;
}
}
array_push($result,$row);
}
Bạn phải check lại, tui gõ chay nhé…
Cái file dbconnect.php của bạn không đúng.
Dùng cái này nhé.
<?php
$con=mysqli_connect("localhost","root","","tool");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$data=array();
$result=mysqli_query($con,"SELECT * FROM hoa_don");
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<pre>".json_encode($row, JSON_PRETTY_PRINT)."</pre>";
}
mysqli_free_result($result);
mysqli_close($con);
?>