How to build an associative array with 2 sqls? - php

I want to build an associative array, which will run two mysql tables.
Name of tables: cs_lots , cs_lots_history .
My PHP CODE -
$rows = array();
$res2 = mysql_query("SELECT * FROM cs_lots WHERE active_lot='1'") or die(mysql_error());
$result1 = mysql_query("SELECT DISTINCT id_lot FROM cs_lots_history WHERE user_steamid='".$_SESSION['steamid']."'") or die(mysql_error());
while($row = mysql_fetch_array($res2)) {
$rows []= array(
'id' => $row['id'],
'inv_id' => $row['inv_id'],
'inv_assets' => $row['inv_assets'],
'name' => $row['inv_name'],
'inv_image' => $row['inv_image'],
'inv_rarity' => $row['inv_rarity'],
'inv_color' => $row['inv_color'],
'inv_type' => $row['inv_type'],
'inv_price' => $row['inv_price'],
'price_ticket' => $row['price_ticket'],
'maxUsers' => $row['places'],
'nowUsers' => $row['now_places'],
'my' => false
);
}
Array with this code:
LOTS = [{"id":"166","inv_id":"989","inv_assets":"3432669422","name":"Redline ","inv_image":"image","inv_rarity":"Field-Tested","inv_color":"d32ce6","inv_type":"1","inv_price":"2105.97","price_ticket":"14","maxUsers":"240","nowUsers":"1","my":false},
{"id":"167","inv_id":"929","inv_assets":"3551634073","name":"Hyper Beast ","inv_image":"image","inv_rarity":"Battle-Scarred","inv_color":"eb4b4b","inv_type":"1","inv_price":"924.43","price_ticket":"8","maxUsers":"180","nowUsers":"0","my":false},
{"id":"168","inv_id":"1104","inv_assets":"3313740799","name":"Asiimov ","inv_image":"image","inv_rarity":"Battle-Scarred","inv_color":"eb4b4b","inv_type":"1","inv_price":"1495.00","price_ticket":"13","maxUsers":"180","nowUsers":"19","my":false},
{"id":"169","inv_id":"847","inv_assets":"3603670527","name":"Jaguar ","inv_image":"image","inv_rarity":"Battle-Scarred","inv_color":"eb4b4b","inv_type":"1","inv_price":"2711.65","price_ticket":"13","maxUsers":"320","nowUsers":"8","my":false},
{"id":"170","inv_id":"1100","inv_assets":"3313741398","name":"Asiimov ","inv_image":"image","inv_rarity":"Field-Tested","inv_color":"eb4b4b","inv_type":"1","inv_price":"2756.70","price_ticket":"16","maxUsers":"260","nowUsers":"10","my":false},
{"id":"171","inv_id":"899","inv_assets":"3551642235","name":"Atomic Alloy ","inv_image":"image","inv_rarity":"Factory New","inv_color":"d32ce6","inv_type":"1","inv_price":"862.50","price_ticket":"8","maxUsers":"180","nowUsers":"1","my":false}];
Now my array running with one mysql table and i have only my:false But i need change key my and value false to true where SQL $result1 have same result $result1['id_lot'] with $row['id'] .
As Example: If $result1['id_lot'] = $row['id'] i need this code:
{"id":"166","inv_id":"989","inv_assets":"3432669422","name":"Redline ","inv_image":"image","inv_rarity":"Field-Tested","inv_color":"d32ce6","inv_type":"1","inv_price":"2105.97","price_ticket":"14","maxUsers":"240","nowUsers":"1","my":true}`
Thanks.

LEFT JOIN + aliases:
$rows = array();
$res2 = mysql_query("SELECT cs_lots_history.id, cs_lots_history.user_steamid, cs_lots_history.id_lot, cs_lots.id as csid, inv_id, inv_assets, inv_image, inv_color, inv_name, inv_rarity, inv_type, inv_price, price_ticket, places, now_places FROM cs_lots LEFT JOIN cs_lots_history ON cs_lots.id = cs_lots_history.id_lot WHERE active_lot='1' OR user_steamid='".$_SESSION['steamid']."' GROUP BY cs_lots.id") or die(mysql_error());
$a=0;
while($row = mysql_fetch_array($res2)) {
$rows []= array(
'id' => $row['csid'],
'inv_id' => $row['inv_id'],
'inv_assets' => $row['inv_assets'],
'name' => $row['inv_name'],
'inv_image' => $row['inv_image'],
'inv_rarity' => $row['inv_rarity'],
'inv_color' => $row['inv_color'],
'inv_type' => $row['inv_type'],
'inv_price' => $row['inv_price'],
'price_ticket' => $row['price_ticket'],
'maxUsers' => $row['places'],
'nowUsers' => $row['now_places'],
'my' => !empty($row['id_lot']) ? true : false
);
}
Thanks #Sean.

Related

PHP, Get all items of particular type in one array

Ok so I have two tables Category and Dishes. Each Category has an id. And each dish belongs to a particular category. Now what I want is for all dishes belonging to a particular category to be grouped together. So All the Soups will be in the Soups Array [{Cabbage,Price,Description,...}, {Tomato,Price,Description,...}]. All the chicken in the chickens array and so forth. What I'm Currently doing is this:
$query = "Select id from Category";
$Id = $mysqli->query($query);
while($row = $Id->fetch_assoc()) {
$idlist[] = $row["id"];
}
foreach ($idlist as $id){
$query = "SELECT * from Dishes where Dishes.cat_id = '$id'";
$Listings = $mysqli->query($query);
while($row = $Listings->fetch_assoc()) {
$AllDishes[] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'cat_id' => $row['cat_id'],
'Price' => $row['Price'],
'ImagePath' => $row ['ImagePath']
);
}
}
But this results in all the dishes being grouped together. How do I separate the dishes based on their category? Also is this the right way to structure JSON Data?
1.Use JOIN to do that in single query (best solution):-
$query = "Select Dishes.*,Category.id as cat_id from Category LEFT JOIN Dishes on Dishes.cat_id = Category.id";
$Listings = $mysqli->query($query);
$AllDishes = array();
while($row = $Listings->fetch_assoc()) {
$AllDishes[$row['cat_id']][] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'cat_id' => $row['cat_id'],
'Price' => $row['Price'],
'ImagePath' => $row ['ImagePath']
);
}
print_r($AllDishes);
If you want to do in your coding way then:-
2.Distinguish them based on id of the category:-
$query = "Select id from Category";//change column name
$Id = $mysqli->query($query);
while($row = $Id->fetch_assoc()) {
$idlist[] = $row['id'];
}
foreach ($idlist as $id){
$query = "SELECT * from Dishes where Dishes.cat_id = '$id'";
$Listings = $mysqli->query($query);
while($row = $Listings->fetch_assoc()) {
$AllDishes[$id][] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'cat_id' => $row['cat_id'],
'Price' => $row['Price'],
'ImagePath' => $row ['ImagePath']
);
}
}
3.Distinguish them based on name of the category:-
$query = "Select id,category_name from Category";//change column name
$Id = $mysqli->query($query);
while($row = $Id->fetch_assoc()) {
$idlist[] = $row;
}
foreach ($idlist as $id){
$id = $id['id'];
$category_name = $id['category_name']; //change column-name
$query = "SELECT * from Dishes where Dishes.cat_id = '$id'";
$Listings = $mysqli->query($query);
while($row = $Listings->fetch_assoc()) {
$AllDishes[$category_name][] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'cat_id' => $row['cat_id'],
'Price' => $row['Price'],
'ImagePath' => $row ['ImagePath']
);
}
}
Note:- Please change the column-name in 3rd solution(as i don't know what column-name you have to store category names.)
I am not sure but i thinks here will be your while loop for expected results
$AllDishes = array();
while($row = $Listings->fetch_assoc()) {
$AllDishes[$row['Name']][] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'cat_id' => $row['cat_id'],
'Price' => $row['Price'],
'ImagePath' => $row ['ImagePath']
);
}
You can use SQL joins instead of two separate SQL queries
I hope the following may help you.
$query = "SELECT * FROM Dishes INNER JOIN Category
ON Dishes.id = Category.id ORDER BY Dishes.id";
$res = $mysqli->query($query);
while($row = $res->fetch_assoc())
{
$AllDishes[$$row['category_name']][] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' =>
$row['Description'],
'cat_id' =>
$row['cat_id'],
'Price' => $row['Price'],
'ImagePath' =>
$row['ImagePath']
);//Array Close
}

Creating JSON array of arrays with keys from MySQL into sing JSON object

I am trying to create an array of arrays in a loop to a JSON object, but It returns two objects instead. If I remove the array around the array with a key, it works but I need the key.
This is the format I am looking for:
$shop = array( "1408842145690" => array( id => "1408842145690",
code => "1",
title => "zdfdsf",
date => "2014-08-01",
description => "fghgf"
),
"1408840099517" => array( id => "1408840099517",
code => "1",
title => "test",
date => "2014-08-01",
description => "this is a test"
)
);echo json_encode($shop);
This is the code I am using
$query = " SELECT * FROM todolist ";
if ($result = mysqli_query($mysqli,$query)) {
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$tasks = array(
$row['task_id'] => array( 'id' => $row['task_id'],
'code' => $row['task_statusbox'],
'title' => $row['task_title'],
'date' => $row['task_date'],
'description' => $row['task_description']
)
);
$alltasks[] = $tasks;
}
echo json_encode($alltasks);
/* free result set */
$result->close();
}
This is the result I get:
{"1408842145690":{"id":"1408842145690","code":"1","title":"zdfdsf","date":"2014-08-01 00:00:00","description":"fghgf"}},{"1408840099517":{"id":"1408840099517","code":"1","title":"test","date":"2014-08-01 00:00:00","description":"this is a test"}}
This is the result I am looking for
{"1408842145690":{"id":"1408842145690","code":"1","title":"zdfdsf","date":"2014-08-01","description":"fghgf"},"1408840099517":{"id":"1408840099517","code":"1","title":"test","date":"2014-08-01","description":"this is a test"}}
Replace the contents of your while loop with the following:
$tasks = array('id' => $row['task_id'],
'code' => $row['task_statusbox'],
'title' => $row['task_title'],
'date' => $row['task_date'],
'description' => $row['task_description']
);
$alltasks[$row['task_id']] = $tasks;
EDIT: I tested the above, and it does work. Here is the full code with the replacement intact... try a copy/paste.
$query = " SELECT * FROM todolist ";
if ($result = mysqli_query($mysqli,$query)) {
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$tasks = array('id' => $row['task_id'],
'code' => $row['task_statusbox'],
'title' => $row['task_title'],
'date' => $row['task_date'],
'description' => $row['task_description']
);
$alltasks[$row['task_id']] = $tasks;
}
echo json_encode($alltasks);
/* free result set */
$result->close();
}

PHP mysql select to array and check if value exist

I have this MySQL table:
Where I want to get count of each platform (windows, linux, mac, unknown).
Notice that in table is no mac or unknown data, there for num will be 0
Conditions:
order must be like in wanted output
check if plaform is in table, if not add zero to output
Question: How to sort in query to have order like in wanted output, and add zero if no platform in table?
Wanted output:
array (
'0' => array('name' => 'windows', 'num' => 3),
'1' => array('name' => 'linux', 'num' => 3),
'2' => array('name' => 'mac', 'num' => 0),
'3' => array('name' => 'unknown', 'num' => 0)
);
My try:
PHP:
function get_platforms() {
$query = "
SELECT platform, COUNT(platform) AS num
FROM stats
GROUP BY platform
ORDER BY platform ASC
";
$select = mysqli_query($this->c, $query);
while ($row = mysqli_fetch_array($select)) {
$data[] = array(
'name' => $row['platform'],
'num' => $row['num']
);
}
return $data;
}
Current outpup:
array (
'0' => array ('name' => 'linux', 'num' => 3)
'1' => array ('name' => 'windows', 'num' => 3)
);
Because you don't have any mac or unknown data in your database, you will not get any result to this platform, not even 0. What you can do is to have a preconfigured array with the platforms you are expecting to get:
$data = array(
'windows' => 0,
'linux' => 0,
'mac' => 0,
'unknown' => 0
)
Now in your get_platforms function do this:
function get_platforms() {
$query = "
SELECT platform, COUNT(platform) AS num
FROM stats
GROUP BY platform
ORDER BY platform ASC
";
$select = mysqli_query($this->c, $query);
while ($row = mysqli_fetch_array($select)) {
$data[$row['platform']] = $row['num'];
}
return $data;
}
you will end up with this:
$data = array(
'windows' => 3,
'linux' => 3,
'mac' => 0,
'unknown' => 0
)
And then you can reformat the data in the way that you want. For example you can do this:
$result = array();
foreach($data as $platform => $count){
$result[] = array('name' => $platform, 'count' => $count);
}
And you will end up with the result in the same format you're asking.
First of all you should define an order of desired output, lets say you have array
$osList = array('linux', 'windows', 'mac', 'something');
Now fetch your mysql results to temporary assoc array:
$data = array();
$query = "SELECT platform, COUNT(platform) AS num"
. " FROM stats"
. " GROUP BY platform";
$result = mysqli_query($this->c, $query);
while ($row = mysqli_fetch_array($result)) {
$data[$row['platform']] = (int) $row['num'];
}
And here you can form output array:
$output = array();
foreach ($osList as $os) {
$output[] = array(
'name' => $os,
'count' => isset($data[$os]) ? $data[$os] : 0
);
}
You must have another table which has all the platforms listed there. For example we call it platforms which has a column platform_name with all the unique names of platforms (including mac), then the query would be:
SELECT platforms.`platform_name`, COUNT(stats.`platform`) FROM `platforms`
LEFT JOIN `stats` ON platforms.`platform_name` = stats.`platform`
GROUP BY platforms.`platform_name`

active record issue to return array (codeigniter)

I have a table called uploaded_files in my database where I have the following fields:
id, file_name, upload_id, filetype_id
this last field (filetype_id) is a Foreign Key to a table called filetype where I have these fields:
id, filetype_desc
I'm trying to create a method in my model to return all the fields in table uploaded_files, in an array following this structure:
array(
'file_type_1' => array(
'id' => 1,
'file_name' => "lalala.txt",
'upload_id' => $uploadId,
'filetype_id' => 1
),
'file_type_2' => array(
'id' => 1,
'file_name' => "lelele.txt",
'upload_id' => $uploadId,
'filetype_id' => 2
),
'file_type_3' => array(
'id' => 1,
'file_name' => "blabla.txt",
'upload_id' => $uploadId,
'filetype_id' => 3
),
);
}
Until now, I came to this:
public function get_UploadedFilesFromUploadId($uploadId){
//$query = "select * from uploaded_files where upload_id =".$uploadId;
$query = $this->db->get_where('uploaded_files', array(
'upload_id' => $uploadId
)
);
return $this->db->query($query);
}
$query = $this->db->get_where('uploaded_files', array(
'upload_id' => $uploadId
)
);
$res = $this->db->query($query);
$result = array();
foreach ($res->result_array() as $row)
{
$key = 'file_type_'.$row['filetype_id'];
$result[$key] = $row;
}
$query = $this->db->get_where('uploaded_files',array('upload_id' => $uploadId));
foreach($query->result() as $row)
{
echo $row->filetype_id;
}
I think it's help you.

Looping through results of a sql query

I have a query that returns multiple rows. I can't seem to find a way to store the rows in the $params array. Is there a way to loop throw and store each row in the $params variable
$aResult = $db->exec_sql($sql);
$params = array(
// where $aResult[o]'' would be row 1 [1] row 2 etc. //
'store_id' => $aResult[]['iStoreID'],
'user_id' => $aResult[]['iUserID'],
'store_name' => $aResult[]['cStoreName'],
'store_url' => $aResult[]['cStoreURL'],
'rid' => $aResult[]['cRID'],
'affiliate_id' => $aResult[]['iAffiliateID'],
'team_id' => $aResult[]['iTeamID'],
'bizOP' => $aResult[]['cDefaultBizOpp'],
'showBizOPp' => $aResult[]['iShowBizOppDropdown'],
'boPosting' => $aResult[]['iEnableBOPosting'],
'brandinglevel' => $aResult[]['iBrandingLevel']
);
thank you for your help
As simple as that:
$params = array();
foreach($aResult as $row) {
$params[] = array(
'store_id' => $row['iStoreID'],
'user_id' => $row['iUserID'],
'store_name' => $row['cStoreName'],
'store_url' => $row['cStoreURL'],
'rid' => $row['cRID'],
'affiliate_id' => $row['iAffiliateID'],
'team_id' => $row['iTeamID'],
'bizOP' => $row['cDefaultBizOpp'],
'showBizOPp' => $row['iShowBizOppDropdown'],
'boPosting' => $row['iEnableBOPosting'],
'brandinglevel' => $row['iBrandingLevel']
);
}
Without knowing the exact structure of the result array i guess you need something like this:
<?php
$params = array();
$mapping = array(
'store_id' => 'iStoredID',
'user_id' => 'iUserID',
// and so on...
);
foreach ($aResult as $row) {
$tempRow = array();
foreach ($row as $key => $value) {
$paramKey = isset($mapping[$key]) ? $mapping[$key] : $key;
$tempRow[$paramKey] = $value;
}
$params[] = $tempRow;
}
I use it like this
$aResult = mysql_query($sql);
while($data = mysql_fetch_array($result)) {
'store_id' = $aResult['iStoreID'];
}
At least that is the idea

Categories