如何使用PHP从数据库mysql制作这样的json

5kgi1eie  于 2023-01-20  发布在  Mysql
关注(0)|答案(1)|浏览(138)
{
  "idbarang": "ID-75192864",
  "namabarang": "Fruit Tea",
  "jenisbarang": "Minuman",
  "hargabarang": "6000"
}

我试试这个

<?php 
include 'koneksi.php';

$idbarang = $_GET['id'];

if($idbarang == !null){
    $query = mysqli_query($conn, "SELECT * FROM data_barang WHERE id_barang = '$idbarang'");

    $result = array();
    $i= 0;
    while($row = mysqli_fetch_array($query)){
        $result[$i]['idbarang'] = $row['id_barang'];
        $result[$i]['namabarang'] = $row['nama_barang'];
        $result[$i]['jenisbarang'] = $row['jenis_barang'];
        $result[$i]['hargabarang'] = $row['harga_barang'];
        $i++;
    };

    echo json_encode($result);

} else {
    $query = mysqli_query($conn, "SELECT * FROM data_barang");

    $result = array();
    $i= 0;
    while($row = mysqli_fetch_assoc($query)){
        $result[$i]['idbarang'] = $row['id_barang'];
        $result[$i]['namabarang'] = $row['nama_barang'];
        $result[$i]['jenisbarang'] = $row['jenis_barang'];
        $result[$i]['hargabarang'] = $row['harga_barang'];
        $i++;
    };

    echo json_encode($result);
}
?>

这就是结果

[
  {
    "idbarang": "ID-75192864",
    "namabarang": "Fruit Tea",
    "jenisbarang": "Minuman",
    "hargabarang": "6000"
  },
  {
    "idbarang": "ID-96037284",
    "namabarang": "Sampoerna",
    "jenisbarang": "Rokok",
    "hargabarang": "12000"
  }
]
vxqlmq5t

vxqlmq5t1#

我想你是在问为什么你总是经历ELSE而从不经历IF。那是因为这个IF测试

if($idbarang == !null){

不如试试

<?php 
include 'koneksi.php';

if(!empty($_GET['id'])){

    $idbarang = $_GET['id'];

您还可以大大简化代码,并保护它免受SQL注入的影响。

// Do the renaming of column names as part of the query
$sql = 'SELECT  id_barang as idbarang, nama_barang as namabarang,
                jenis_barang as jenisberang, jenis_barang as hargabarang
        FROM data_barang';

if(!empty($_GET['id'])){
    // add the WHERE clause on to the base query
    $sql .= ' WHERE id_barang = ?';
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $_GET['id']);
    $stmt->execute();
    $res = $stmt->get_result();
    
} else {
    $res = $conn->query($sql);
}
// as the renaming is done we can just fetch all the results and convert to a JSON document
$result = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($result);

相关问题