How to Merge PDO Mysql Array Data using Php - php

I need to merge categories and subcategories into one array. Here is code.
$sql = 'select * from category where id = ?';
$q = $db->prepare($sql);
$q->bindParam(1, $id);
$q->execute();
while($rows = $q->fetch()){
$cat[] = $rows['id'];
$s = 'select * from category where category_id = ?';
$q = $db->prepare($s);
$q->bindParam(1, $rows['id']);
$q->execute();
while($row = $q->fetch()){
$list[] = $row['id'];
}
$data = array_push($cat, $list);
echo $data;
}
I am getting 2 value when printing instead ids numbers

are you want to merge $cat and $list?
you can try:
array_merge($cat, $list);

I solved this problem with the help of this post combine-results-from-two-pdo-queries
$id = '1';
$results = array();
$sql = 'select * from category where id = ?';
$q = $db->prepare($sql);
$q->bindParam(1, $id);
$q->execute();
while($rows = $q->fetch(PDO::FETCH_ASSOC)){
$results[] = $rows['id'];
}
$s = 'select * from category where category_id = ?';
$q = $db->prepare($s);
$q->bindParam(1, $id);
$q->execute();
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$results[] = $row['id'];
}
var_dump($results);

I think what you want is this:
$sql = 'select * from category where id = ?';
$q = $db->prepare($sql);
$q->bindParam(1, $id);
$q->execute();
$data = array();
while($rows = $q->fetch()){
$cat[] = $rows['id'];
$s = 'select * from category where category_id = ?';
$q = $db->prepare($s);
$q->bindParam(1, $rows['id']);
$q->execute();
while($row = $q->fetch()){
$list[] = $row['id'];
}
$data = array_merge($data, $cat, $list);
//$data = array_unique($data);
print_r($data);
}
Notice the $data = array(); before the while loop. With array_merge you merge categories and subcategories with the $data array into the data array.
If you happen to get duplicted value you do not need or want, simply uncomment $data = array_unique($data); and it will erase duplicated entries for you.
Please clarify your question, if I do not address your problem and I will update my answer.
Have fun, may the source be with you.

Related

PHP PDO fetch data from Array

This Code Works Perfectly For Mysqli
$sql = "SELECT * FROM 'mem_tree' ";
$res = mysqli_query($conn, $sql) or die("database error:".mysqli_error($conn));
while($row = mysqli_fetch_assoc($res)){
$data[] = $row;
}
$itemsByReference = array();
but When i'm trying to do with PDO it Doesn't Work
$sql = "SELECT * FROM 'mem_tree' ";
$stmt = $dbh->prepare($sql);
$stmt->execute();
while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)){
$data[] = $row;
}
$itemsByReference = array();
Here i found Solution of it
$sql = "SELECT * FROM mem_tree";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$final_arr = array();
$data = array();
$final_arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
$data = $final_arr;
$itemsByReference = array();

How would i retrieve the rows from Select Statement

I need to store the rows in an array but can't seem to get it to work, the code is below:
I am sure $result = $stmt->get_result(); does not work.
When i test in the browser output is empty.
<?php
include "connect.php";
$uid = $_REQUEST["U_ID"];
$stmt = $mysqli->prepare("SELECT * FROM U_User WHERE U_ID = ?");
$stmt->bind_param("d", $uid);
$stmt->execute();
$stmt->fetch();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc())
{
$users[] = $row;
}
$stmt->close();
$arr = array('user' => $users);
echo json_encode($arr);
mysqli_close($conn);
?>
Just like php_nub_qq said. I switched to PDO works great.
<?php
include "connect.php";
$uid = $_REQUEST["U_ID"];
$q = $conn->prepare("SELECT * FROM U_User WHERE U_ID = :uid");
$q->execute(array(':uid' => $uid));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
$users[] = $r;
}
$q = $conn->prepare("SELECT * FROM P_Post u WHERE P_U_ID = :uid");
$q->execute(array(':uid' => $uid));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
$posts[] = $r;
}
$q = $conn->prepare("SELECT * FROM T_Thread u WHERE T_U_ID = :uid");
$q->execute(array(':uid' => $uid));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
$threads[] = $r;
}
$arr = array('user' => $users, 'post' => $posts, 'thread' => $threads);
echo json_encode($arr);
$conn = null;
?>

PHP prepared statement not returning array

My array is empty when I'm binding an id variable. The table contains 5 columns that I'd like in an array. This is what I tried:
$records = array();
$id = 22;
if($results = $db->prepare("SELECT * FROM categories WHERE id = ?")) {
$results->bind_param('i', $id);
$results->execute();
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row;
}
$results->free();
}
}
print_r($records);
you are binding param 'i' but using a '?' placeholder. Use one of these:
if($results = $db->query("SELECT * FROM categories WHERE id = ?")) {
$results->bind_param(1, $id);
or
if($results = $db->query("SELECT * FROM categories WHERE id = :i")) {
$results->bind_param(':i', $id);
See http://www.php.net/manual/en/pdostatement.bindparam.php for more examples.

display array of items from DB php/MySQL

I am unsure how to display the items field. I want to display two tables of data; one that has all the items from a user and one with all the items to teh user. All I've been able to output is the item_id's(I pasted the html below). How to get all the item info from these ids, which is in the item table, and populate the HTML?
trans table
item table
$from = 1;
$sql = $db->prepare("SELECT * FROM test WHERE from_id = :id");
$sql->bindValue(':id', $from);
$sql->execute();
while($row = $sql->fetch())
{
$t =$row['items'];
$u =$row['to_id'];
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$t</td>
<td>$u</td></tr>";
}
HTML DISPLAY
Try this!
<?php
$from = 1;
$sql = $db->prepare("SELECT * FROM test WHERE from_id = :id");
$sql->bindValue(':id', $from);
$sql->execute();
while($row = $sql->fetch())
{
$t =$row['items'];
$u =$row['to_id'];
$itemIDs = #explode(",", $t);
$items = array();
foreach($itemIDs as $ID){
$sqlItem = $db->prepare("SELECT itemname FROM itemtable WHERE itemid = :itemid");
$sqlItem->bindValue(':itemid', $ID);
$sqlItem->execute();
$itemname ='';
while($rowItems = $sqlItem->fetch())
{
$itemname .=$rowItems['itemname'];
}
$items[$t] = $itemname;
}
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$items[$t]</td> <td>$u</td></tr>";
}
below is my code for testing,
<?php
$from = 1;
$sql = mysqli_query($db,"SELECT * FROM test WHERE from_id = '$from'");
while($row = mysqli_fetch_array($sql))
{
$t =$row['items'];
$u =$row['to_id'];
$itemIDs = #explode(",", $t);
$itemname ='';
foreach($itemIDs as $ID){
$sqlItem = mysqli_query($db, "SELECT itemname FROM itemtable WHERE item_id = '$ID'");
while($rowItems = mysqli_fetch_array($sqlItem))
{
$itemname .= $rowItems['itemname'].', ';
}
$items[$u] = $itemname;
}
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$items[$u]</td> <td>$u</td></tr>";
}
echo "<table>".$trans."</table>";
?>
Note : change my queries with ur need
in ur while loop
while($row = $sql->fetch())
{
$items_array = array();
$items_array = explode(",",$row["items"]);
foreach($items_array as $key => $value)
{
//modify ur query according to ur need
$query3 = "SELECT item_name
FROM item_table
WHERE item_id =".$value." ";
$result3 = mysql_query($query3);
$row3 = mysql_fetch_assoc($result3);
$item_name .= $row3['subcategory_name'].", ";
}
}
now ur array will contains item_id,
use foreach loop in ur while loop and get info of Item from item table with item_id from expolode function
Within while you will have to fire new query that will get the information of items.
For eg :
"SELECT * FROM item_info_table WHERE id IN (id1,id2, id3)"
It will return you the item information corresponding to the id's.
The data is not normalized. Get it to normalize and you'll have a much better and cleaner solution.

JSON parse Mysql query result in php pdo

I am trying to do following
$statement = $conn->prepare('SELECT * FROM myTable');
$statement->execute();
if(!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
{
return false;
}
$conn = null;
} catch(PDOException $e) {
throw $e;
return false;
}
return return json_encode(array('Result'=>$row);
Works and fetches all entries in a table make then JSON Array and send them,
However I want to make a query where selected ids must be send in a JSON Array
E.g 10, 20, 30
I assume that this will be done in a For loop perhaps
$statement = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
$row = $statement->fetch(PDO::FETCH_OBJ)))
Now suppose i have id's = 10,20,30 i want to append all of them in a JSON Array How can i do that?
just like return json_encode(array('Result'=>$row);
Edited Code
function GetMyMembers()
{
$myId = trim($_REQUEST['myId']);
try {
$conn = $this->GetDBConnection();
$statement = $conn->prepare('SELECT valId FROM memList WHERE myId=:myId' );
$statement->bindParam(':myId', $myId, PDO::PARAM_INT);
$statement->execute();
if(!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
{
return false;
}
// $row contains ALL THE ID'S
$placeholders = str_repeat('?,', count($row));
$placeholders = substr($placeholders, 0, -1);
$sql = "SELECT id, * FROM players WHERE id IN ($placeholders)";
$statement = $conn->prepare($sql);
$statement->execute($row);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
$conn = null;
} catch(PDOException $e) {
throw $e;
return false;
}
return $rows;
}
$statement = $conn->prepare('SELECT * FROM myTable');
$statement->execute();
$data = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC)))
{
$data[$row['id']] = $row;
}
return json_encode(array('Result'=>$data));
Btw, using raw API is not convenient. With Database abstraction library your code can be as short as 2 following lines:
$data = $db->getInd("id",'SELECT * FROM myTable');
return json_encode(array('Result'=>$data));
Edit:
if you have an array of ids, you need more complex code
$ids = array(1,2,3);
$data = array();
$statement = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
foreach ($ids as $id) {
$statement->bindValue(':id', $id, PDO::PARAM_STR);
$statement->execute();
$data[] = $statement->fetch(PDO::FETCH_OBJ);
}
return json_encode(array('Result'=>$data));
But while using Database abstraction library, there will be the same 2 lines:
$data = $db->getAll('SELECT * FROM myTable where id IN (?a)', $ids);
return json_encode(array('Result'=>$data));
Edit2:
if you need ids only
$statement = $conn->prepare('SELECT id FROM myTable');
$statement->execute();
$data = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC)))
{
$data[] = $row['id'];
}
return json_encode(array('Result'=>$data));
while using Database abstraction library, it's still 2 lines:
$ids = $db->getCol('SELECT id FROM myTable');
return json_encode(array('Result'=>$ids));
$ids = array(1,2,3);
$placeholders = str_repeat('?,', count($ids));
$placeholders = substr($placeholders, 0, -1);
$sql = "SELECT id, * FROM table WHERE id IN ($placeholders)";
$sth = $dbh->prepare($sql);
$sth->execute($ids);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
echo json_encode(array('Result' => $rows));
Based on additional comments:
Best option:
$sql = '
SELECT *
FROM table1 AS t1
INNER JOIN table2 t2
ON t2.foreign_key = t1.id
';
or
$sql = 'SELECT id FROM table1';
$sth = $dbh->prepare($sth);
$sth->execute();
$ids = $sth->fetchColumn();
//next look above

Categories