简体   繁体   English

如何使用PHP和MySQL从数据库中获取数组中的数据

[英]How to fetch data in array from Database using PHP and MySQL

i need one help.I need to fetch data from database and store them in an array using PHP and MySQL. 我需要一个帮助。我需要从数据库中获取数据,并使用PHP和MySQL将它们存储在数组中。 My table structure is given below. 我的表结构如下。

db_special: db_special:

id     member_id      subcat_id        image         comment

1       135              3             abc.png         hiii

2       135              3             wsd.png         hello

3       135              4             nbh.png         huuuu

4       120              4             nkj.png        hghghg

Here the above is my table structure.I need to fetch data using the member_id and subcat_id which is given by user and it should be grouped by member_id .Here i need the fetched data like below format. 上面是我的表结构。我需要使用用户给定的member_idsubcat_id来获取数据,并且应该按照member_id进行分组。这里我需要像以下格式那样获取数据。 suppose user have member_id=135 and subcat_id=3 then result should like below. 假设用户有member_id=135 and subcat_id=3则结果应如下所示。

data={"member_id":135,"subcat_id":3,"special_image"[{"image":"abc.png","comment":"hiii"},{"image":"wsd.png","comment":"hello"}]}

Here i need the query.Please help me. 在这里我需要查询。请帮助我。

Just like what I've said in the comments. 就像我在评论中所说的一样。 Query, fetch, create array structure, then encode: 查询,获取,创建数组结构,然后编码:

// connect
$db = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');
$member_id = 135; // values
$subcat_id = 3;
// statement
$stmt = $db->prepare('SELECT * FROM db_special WHERE member_id = :member_id AND subcat_id = :subcat_id');
$stmt->execute(array(
    ':member_id' => $member_id,
    ':subcat_id' => $subcat_id
));
// initialize container format
$data = array(
    'member_id' => $member_id,
    'subcat_id' => $subcat_id,
    'special_image' => array(), // initialize
);
// fetch values and push into container with format
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $data['special_image'][] = array('image' => $row['image'], 'comment' => $row['comment']);
}
// encode
echo json_encode($data);

Try this hope it will help you. 尝试此希望对您有帮助。

<?php
//Your Query
$sql = "YOUR QUERY"
$result = mysql_query($sql);

//Your Array
$newArray = array();

//Your Array Data
while($row = mysql_fetch_array($result)){ 
  $newArray[] = "\"".$row['COLUMN NAME']."\"";
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM