I'm trying to get a JSON Object from two tables in the MySQL database, but nothing returned.
product table: id, title, description, price
product_colors table: id, product_id, product_color
My PHP code:
$st = $conn->prepare ('SELECT `product`.id , `product`.title, `product`.description, `product`.price, GROUP_CONCAT(`product_colors`.product_color) AS colors FROM `product` LEFT JOIN `product_colors` ON `product`.id = `product_colors`.product_id GROUP BY `product`.id');
$st->execute();
$products = [];
$rows = $st->fetchAll(\PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$row['product_colors'] = explode(',', $row['product_color']);
$products[] = $row;
}
echo json_encode ($products);
This what I want to get:
[
{
id: 4,
title: 'Car',
description: "Pellentesque orci lectus",
price: '120$',
product_color: ['Red', 'Blue', 'Black']
},
{
id: 6,
title: 'Bus',
description: "orci lectus",
price: '10$',
product_color: ['White', 'Blue', 'Green']
}
]
So finally i got the answer, first the query is correct and perfect, the error in fetching and loop, so this is the perfect solution and much easier:
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$r['colors']=explode(',', $r['colors']); //colors like what i named the GROUP_CONCAT
$rows[] = $r;
Still considering PDO? You may want this...
<?php
$output = array();
$products = 'product'; // "product" Table
$colors = 'product_colors'; // "product_colors" Table
//if "id" is auto-incremented which may not match "product_id", You may want to create another "product_id" in $products table to use the $statement commented below
/*
$statement = $connection->prepare(
"SELECT t.product_id, t.title, t.description, t.price, c.product_color FROM `$products` t, `$colors` c WHERE t.product_id = c.product_id"
);
*/
$statement = $connection->prepare(
"SELECT t.id as product_id, t.title, t.description, t.price, c.product_color FROM `$products` t, `$colors` c WHERE t.product_id = c.product_id"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output['id'] = $row['product_id'];
$output['title'] = $row['title'];
$output['description'] = $row['description'];
$output['price'] = $row['price'];
$output['product_color'] = explode(',', $row['product_color']);
}
echo json_encode($output);
?>
Related
Like this my query is working fine:
$pdo = $db->prepare('SELECT *
FROM projects WHERE project_id = :project_id ');
$pdo->execute(array('project_id' => $project_id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo "ok";
}
But when I add a subselection then I get a blank page:
$pdo = $db->prepare('SELECT *
(SELECT * FROM animals WHERE projects.animal=animals.id) AS animal
FROM projects WHERE project_id = :project_id ');
$pdo->execute(array('project_id' => $project_id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo "ok";
}
What did I do wrong?
You can use INNER JOIN to have both tables.
$pdo = $db->prepare('SELECT *
FROM projects
INNER JOIN animals ON projects.animal=animals.id
WHERE project_id = :project_id ');
$pdo->execute(array('project_id' => $project_id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo "ok";
}
Try this query beacuse this query will return all the projects that have an animal associated in table animals.
I think is this that you want
Found this solution:
$pdo = $db->prepare('SELECT *
FROM projects
LEFT JOIN animals ON projects.animal=animals.id
WHERE project_id = :project_id ');
$pdo->execute(array('project_id' => $project_id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo "ok";
}
UPDATE :
i need get a all values of tags field !
MY Query :
$query = db_select('node', 'node');
$query->fields('tagsdata',array('name'));
$query->fields('node', array('nid'));
$query->leftJoin('field_data_field_tags', 'tags', 'tags.entity_id = node.nid');
$query->leftJoin('taxonomy_index', 'tagsindex', 'tagsindex.nid = tags.entity_id');
$query->leftJoin('taxonomy_term_data','tagsdata','tagsdata.tid = tags.field_tags_tid AND node.nid = tagsindex.nid');
$result = $query->execute();
while( $record = $result->fetchAssoc() ) {
$items[] = $record;
}
AND MY CODE :
//SORT
array_multisort(array_column($items, 'nid'), $items);
foreach ($items as $row) {
$hash[$row[nid]] = $row;
}
$resultfinal = ($hash);
// END SORT
foreach($resultfinal as $finalarrays)
{
$tags=$finalarrays['name'];
print_R ($tags);
}
WITH above code just return one and first value of tags, i need to print all of them !
You can use GROUP_CONCAT mysql function to get all value imploded by comma :
$result = db_query("SELECT tags.entity_id as nid, GROUP_CONCAT(t.name) as tdata FROM field_data_field_tags
INNER JOIN taxonomy_term_data t ON t.tid = tags.field_tags_tid
WHERE tags.entity_type = :type GROUP BY tags.entity_id",
array(':type' => 'node'))->fetchAllKeyed();
NB : sometimes you have too much string to concat so you need to increase limit before by :
db_query('SET SESSION group_concat_max_len=10000');
$result = db_query("SELECT tags.entity_id as nid, GROUP_CONCAT(t.name) as tdata FROM field_data_field_tags
INNER JOIN taxonomy_term_data t ON t.tid = tags.field_tags_tid
WHERE tags.entity_type = :type GROUP BY tags.entity_id",
array(':type' => 'node'))->fetchAllKeyed();
https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat
foreach($result as $nid => $tags) {
echo $nid . ' : '.$tags;
}
here is mytable structure?
table:category
id name
1 x
2 y
table:subproduct
id cat_id name myval
1 1 xyz test
2 1 abc test2
So basically i want to select all values from subproduct for each id of category table and show it in array in php?
here is my PHP code
$sqlnew = "SELECT c.cat_id,c.cat_title,s.sub_id,s.sub_title,s.store_cashback FROM category c JOIN subproduct s ON c.cat_id = s.pid";
$pdo = getDB();
$stmtnew = $pdo->query($sqlnew);
$resultnew = $stmtnew->fetchAll();
var_dump($resultnew);
I am using PHP PDO.
If you want to get all items with a particular category ID, you should do something like this:
$statement = $pdo->prepare("SELECT * FROM subproduct INNER JOIN category " .
"ON category.id = subproduct.cat_id WHERE category.id = :id");
$statement->bindValue(":id", $category_id, PDO::PARAM_INT);
$statement->execute();
$data = $statement->fetchAll();
You could use this to individually fetch each category ID and build an array like this:
$statement = $pdo->query("SELECT id FROM category;");
$ids = $statement->fetchAll(PDO::FETCH_COLUMN, 0);
$data = array();
foreach($ids as $id)
{
$statement = $pdo->prepare("SELECT * FROM subproduct INNER JOIN category " .
"ON category.id = subproduct.cat_id WHERE category.id = :id");
$statement->bindValue(":id", $id, PDO::PARAM_INT);
$statement->execute();
$data[$id] = $statement->fetchAll();
}
print_r($data);
I am not crazy about this because it looks inefficient and I don't like looping through queries. You could also request all the data at once and then rearrange it:
$statement = $pdo->query("SELECT * FROM subproduct");
$data = array();
while($subproduct = $statement->fetch(PDO::FETCH_ASSOC))
{
$id = $subproduct['cat_id'];
if (!isset($data[$id])
$data[$id] = array();
array_push($data[$id], $subproduct);
}
print_r($data);
I don't really like this either because using PHP to sort MYSQL data feels wrong since that is MYSQL's job. I could have requested MYSQL sort the data, but then the data would still need to be broken up into a multi-dimensional array, so I am not sure that helps.
I was working on a post system..
So, I have to show posts by friends of the user and the groups in which user has participated..
Here is my code to show posts..
<?php
$sql = "SELECT * FROM posts WHERE uploader_id=:friend_id ORDER BY id DESC";
$query = $db->prepare($sql);
$query->execute(array(
":friend_id" => $friend_id
));
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$name = $row['name'];
echo "POST BY $name";
}
$sql = "SELECT * FROM group_posts WHERE id=:member_group ORDER BY id DESC";
$query = $db->prepare($sql);
$query->execute(array(
":member_group" => $group_id
));
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$name = $row['name'];
echo "POST BY $name";
}
?>
Now, I want all these posts to be shuffled in a way that all the posts of the post table and group_posts table are shown in the descending order.
UPDATE
I edited my code to this..
I figured out that first I'll have to code this before coding my post system..
<?php
$sql = "SELECT * FROM friends WHERE user_one=:me OR user_two=:me2 UNION SELECT * FROM group_members WHERE member_id=:me3";
$query = $db->prepare($sql);
$query->execute(array(
":me" => $my_id,
":me2" => $my_id,
":me3" => $my_id
));
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$user_one = $row['user_one'];
$user_two = $row['user_two'];
$group_id = $row['group_id'];
if ($user_one == $my_id) {
$friend_id = $user_two;
} else {
$friend_id = $user_one;
}
echo $friend_id . "<BR>" . $group_id;
}
?>
Now, here's the problem..
This is successfully printing the $friend_id but, it shows an undefined index 'group_id' while printing $group_id.
I have checked all the fields are correct.
Try using just one query with UNION
SELECT *
FROM (
SELECT name, id FROM posts WHERE uploader_id=:friend_id
UNION
SELECT name, id FROM group_posts WHERE id=:member_group
) p
ORDER BY p.id DESC
Note, your inner queries must return the same number of columns in the same order (and I think with the same name/alias, too).
Lindsay is a social girl, so she meets a lot of people and she'd like to organize her notebook as such:
first the tabs, that she names somewhat like 'school', 'work', 'party', 'online' etc.
inside each tab she creates groups like: 'cool', 'handy', 'clingy', 'good kissers', 'marriage material' etc.
and inside those groups are actual guys, each one in one group only.
So, now I'm querying the database to show her the notebook at glance.
function getNotebook($user_id)
{
// $data[][][] = array(); // declare 3-dimensional array
$sql = "SELECT tab_id, tab_name, tab_color FROM tab WHERE user_id = ?";
$query = $this->db->query($sql, $user_id);
foreach ($query->result() as $row)
{
// ... (put each tab array in the first dimension of $data array)
$sql = "SELECT group_id, group_name, group_size, group_position FROM group WHERE tab_id = ?";
$query2 = $this->db->query($sql, $row->tab_id);
foreach ($query2->result() as $row2)
{
// ... (put each group array in the second dimension of $data)
$sql = "SELECT person_id, person_name, person_gender, person_eye_color FROM person WHERE group_id = ?";
$query3 = $this->db->query($sql, $row2->group_id);
foreach ($query3->result() as $row3)
{
// ... (put each person array in the third dimension of $data)
}
}
}
return $data;
}
I know it's not good to create HTML right here in the model, so I need to save it (in array?) and return it to controller, and then to model, where I would need to go through it and add HTML tags.
Comments in the function is where I need your help.
Solution #2:
Add user_id field to the person table and get all the information with this query:
$sql = "SELECT * FROM person p
INNER JOIN group g ON g.id = p.group_id
INNER JOIN tab t ON t.id = g.tab_id
WHERE p.user_id = ?
ORDER BY t.id, g.id";
$query = $this->db->query($sql, $user_id);
function getNotebook($user_id)
{
$data = array(); // not applicable
$sql = "SELECT tab_id, tab_name, tab_color FROM tab WHERE user_id = ?";
$query = $this->db->query($sql, $user_id);
foreach ($query->result() as $row)
{
$temp1 = array(
'id' => $row->tab_id,
'name' => $row->tab_name,
'color' => $row->tab_color,
'groups' => array()
); // create temporary array for storage after loop
$sql = "SELECT group_id, group_name, group_size, group_position FROM group WHERE tab_id = ?";
$query2 = $this->db->query($sql, $row->tab_id);
foreach ($query2->result() as $row2)
{
$temp2 = array(
'id' => $row2->group_id,
'name' => $row2->group_name,
'size' => $row2->group_size,
'position' => $row2->group_position,
'people' => array()
); // create another temporary array for storage after loop for second dimension
$sql = "SELECT person_id, person_name, person_gender, person_eye_color FROM person WHERE group_id = ?";
$query3 = $this->db->query($sql, $row2->group_id);
foreach ($query3->result() as $row3)
{
$temp2['people'][] = array(
'name' => $row3->person_name,
'gender' => $row3->person_gender,
'eye_color' => $row3->person_eye_color
); // store data
}
$temp1['groups'][] = $temp2; // store temp array
}
$data[] = $temp1; // store temp array
}
return $data;
}
Is that what you're looking for?