PHP - return SQL GROUP BY as array? - php

I'm trying to return a MySQL query using GROUP BY as a array.
My table looks like this:
user_id | type
--------------------
1 | test
1 | test
2 | test
1 | hello
1 | helloworld
And my code and query:
$number_of_workouts = array();
$query = mysqli_query(connect(),"SELECT type, COUNT(*) FROM `log` WHERE `user_id` = $user_id GROUP BY type");
$number_of_workouts = mysqli_fetch_assoc($query);
return $number_of_workouts;
This code above isn't returning a array with all types listed, it will only return the number of one type(assuming that $user_id = 1.
How can I return the result of the query as an array?

mysqli_fetch_assoc($query);
fetches 1 row only from the resultset
If you want ALL rows from the resultset, you have to loop for each row and add it to a stack like:
$number_of_workouts = array();
$query = mysqli_query(connect(),
"SELECT type, COUNT(*) AS count
FROM `log`
WHERE `user_id` = $user_id
GROUP BY type"
);
$array = array();
while ($number_of_workouts = mysqli_fetch_assoc($query)) {
$array[$number_of_workouts['type']] = $number_of_workouts['count'];
}
// Now you have all results like you want in the variable array:
print_r($array);
// print count of type test:
echo $array['test'];
Or you try out mysqli_fetch_all() (http://www.php.net/manual/en/mysqli-result.fetch-all.php)
(sorry for many updates)

You are fetching only first record here. Keep the fetching statement in while loop
while($number_of_workouts = mysqli_fetch_assoc($query))
{
echo "<pre>";
print_r($number_of_workouts);
}

Related

Select data from the database before or after a defined value

I am having problems achieving the query to select data from a table in the db after a defined value has been met.
My code to do this is:
$fi = 'first_segment'
$im = popo.jpg
$sqls = "SELECT * FROM $fi,news_pictures
WHERE $fi.pi_id = news_pictures.pi_id
AND news_pictures.i_name = '$im'
GROUP BY news_pictures.id DESC";
I wasn't able to achieve the result with that query.
Basically, I want the query to confirm if news_pictures.i_name = '$im' and if true, return starts from the value of $im followed by other data in the table depending on news_pictures.id DESC.
The sample data and output:
Table news_pictures:
id i_name
-- ------
1 coco.jpg
2 lolo.jpg
3 popo.jpg
4 dodo.jpg
Since $im = popo.jpg, I want my query to display all values starting from popo.jpg with id DESC, i.e. popo.jpg, lolo.jpg, coco.jpg.
I got to solve the question with the help of a friend.
$fsqls = "SELECT * FROM $fi,news_pictures WHERE $fi.pi_id = news_pictures.pi_id AND news_pictures.i_name = '$im' GROUP BY news_pictures.id";
$rres = mysqli_query($connection, $fsqls) or print(mysqli_error($connection));
while($row = mysqli_fetch_assoc($rres))
{
$rnm = $row["id"];
}
$sqls = "SELECT * FROM news_pictures WHERE news_pictures.id <= $rnm ORDER BY news_pictures.id DESC";

Make hierarchy from table with PHP

I have a table in database and in this table i have added 3 columns that is i, name,parent_id.please see below.
ID | name | parent_id
1 name1 0
2 name2 1
3 name3 1
Now i want to fetch this id from database. I have created a method in PHP and fetch data one by one from database. Please see below
function getData($id)
{
$array = array();
$db = JFactory::getDBO();
$sql = "SELECT * from table_name when id = ".$id;
$db>setQuery($sql);
$fetchAllDatas = $db->getObjectList();
foreach ($fetchAllDatas as $fetchAllData)
{
if($fetchAllData->parent_id > 0)
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
$this->getData($fetchAllData->parent_id);
}
else
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
}
}
return $array;
}
Now if i call this method with id 3 like
$this->getData(3); // has a parent
It will return like that
Array(
[0]=>name1
)
But i want like below
Array(
[1]=>name3,
[0]=>name1
)
I know i have redefine array if we have parent but how i manage it.
i have used array_push php function but its not work with my condition.
foreach ($fetchAllDatas as $fetchAllData)
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
if($fetchAllData->parent_id > 0)
array_push($array,$this->getData($fetchAllData->parent_id));
}
return $array;
1)Because you do $array[$fetchAllData->parent_id] = $fetchAllData->name; in the if and in the else, you do this in both cases so put out of if..else.
2) Try to push the result of your second call in the original array to get what you want.
you have unique ID in your table, so if you call your query it will always return only one result. Maybe you wanted to write query this way:
$sql = "SELECT * from table_name when parent_id = ".$id;
if you want to get the result with given ID and his parent, you should add this after calling $this->fetchSharedFolder(...);
$array = array_merge($array, $this->getData($fetchAllData->parent_id));

SQL Query check column values if it's in an Array

My existing SQL Query:
$getEdu = "SELECT * FROM Request_Subject WHERE REQUEST_ID = $id
AND SUBJECT_ID IN (2,3,4)";
So in my Database, each REQUEST_ID can be associated with multiple SUBJECT_IDs
And SUBJECT_ID has values ranging from 1 to 10.
So my existing values in the table are:
REQUEST_ID: 1 -> SUBJECT_IDs: 2,3
REQUEST_ID: 2 -> SUBJECT_IDs: 2,4
REQUEST_ID: 3 -> SUBJECT_IDs: 2,8
So currently when the query runs, REQUEST_ID = 3 will still be included in the results because it has the SUBJECT_ID = 2.
Is there a possible way for me to create a SQL Query where even if one value matches, the Query would ignore the REQUEST_ID because it has different values from the array.
Thank you in advance.
UPDATE
Current Results:
$requestSubjects = array();
// So if I call REQUEST_ID = 3
$getEdu = "SELECT * FROM Request_Subject WHERE REQUEST_ID = 3
AND SUBJECT_ID IN (2,3,4)";
$getEdu_answer = mysqli_query($connection, $getEdu);
if(!$getEdu_answer || mysqli_num_rows($getEdu_answer)==0) {
echo "Error";
die();
}
else {
while($subjectRow = mysqli_fetch_assoc($getEdu_answer)) {
$subject = $subjectRow["Subject_ID"];
array_push($requestSubjects, $subject);
}
$reqSub = '{"reqSubject":' .json_encode($requestSubjects). '}';
echo $reqSub; // Returning a JSON to ajax
}
Echoed Results:
{"reqSubject":[2]}
The result is correct as the REQUEST_ID=3 is associated with a SUBJECT_ID = 2.
However what I want is that since REQUEST_ID=3 is also associated with SUBJECT_ID = 8, it should not echo a result at all.
If I understand you correctly, you have ALL SUBJECT_IDS of a REQUEST_ID to match (2,3,4) and only then to print the result?
if so, you can construct the query for each SUBJECT_ID
EDIT:
You must get ALL SUBJECT_IDs of REQUEST_ID using another sqlquery
Contact SUBJECT_IDs to your $getEdu query, and only then execute $getEdu query
Example:
$getEdu = "SELECT * FROM Request_Subject WHERE REQUEST_ID = $id";
//$sub_list is the all subect_id of $id
foreach ($sub_list as $sub_id){
$getEdu.=" AND $sub_id IN (2,3,4)";
}
$getEdu_answer = mysqli_query($connection, $getEdu);
If you execute it on your example, REQUEST_ID =3,
Than $qetEdu query should be:
SELECT * FROM Request_Subject WHERE REQUEST_ID = 3 AND 2 IN (2,3,4) AND 8 IN (2,3,4)
meaning that REQUEST_ID = 3 won't return because 8 is not in (2,3,4)
Hope it help a bit.
maybe
$getEdu = "SELECT * FROM Request_Subject WHERE REQUEST_ID=3
AND SUBJECT_ID IN (2,3,4, if(REQUEST_ID=3,8,null))";
if I understand you correctly...

SQL returns 2 of the 3 rows

I'm trying to select something from a table and insert that information into another table
For example I've 3 rows in table A which I want to insert into table B, he only inserts 2 of the 3.
I got this: I've tried it with fetch_array() but I get only the error non-object
EDIT: THE PART OF THE SCRIPT
$log = $db->query("SELECT itemname FROM log_mitem WHERE mobname = '".$mobname."' AND game = '".$game."'") or die($db->error);
if($log1 = $log->fetch_object());
{
while($loco = $log->fetch_object())
{
You shouldn't have that first if, just do:
$log = $db->query("SELECT itemname FROM log_mitem WHERE mobname = '".$mobname."' AND game = '".$game."'") or die($db->error);
while($loco = $log->fetch_object()) {
// do something
}
Also note that you don't need a while loop for this trivial task, you can use INSERT INTO ... SELECT syntax
INSERT INTO table1 ( column1 )
SELECT col1
FROM table2
WHERE cond1

Displaying 5 rows of data from query

I have a simple table (mgap_orders) with customer orders in it. Multiple have the the same id (mgap_ska_id) and I simply want to pull 5 records from the table and display all five.
I can easily get one record with the following query and PDO, but how can I display 5 rows instead of only one row?
$result_cat_item = "SELECT * FROM mgap_orders WHERE mgap_ska_id = '$id' GROUP BY mgap_ska_id";
while($row_cat_sub = $stmt_cat_item->fetch(PDO::FETCH_ASSOC))
{
$item=$row_cat_sub['mgap_item_description'];
$item_num=$row_cat_sub['mgap_item_number'];
$item_type=$row_cat_sub['mgap_item_type'];
$item_cat=$row_cat_sub['mgap_item_catalog_number'];
$item_ven=$row_cat_sub['mgap_item_vendor'];
$item_pur=$row_cat_sub['mgap_item_percent_purchased'];
$item_sales=$row_cat_sub['mgap_item_sales'];
}
Use limit 5 then put the results in an array, like this:
$result_cat_item = "SELECT * FROM mgap_orders WHERE mgap_ska_id = '$id' GROUP BY mgap_ska_id LIMIT 5";
$items = array();
while($row_cat_sub = $stmt_cat_item->fetch(PDO::FETCH_ASSOC))
{
$items['item'] = $row_cat_sub['mgap_item_description'];
$items['item_num'] = $row_cat_sub['mgap_item_number'];
$items['item_type'] = $row_cat_sub['mgap_item_type'];
$items['item_cat'] = $row_cat_sub['mgap_item_catalog_number'];
$items['item_ven'] = $row_cat_sub['mgap_item_vendor'];
$items['item_pur'] = $row_cat_sub['mgap_item_percent_purchased'];
$items['item_sales'] = $row_cat_sub['mgap_item_sales'];
}
Then you can do:
foreach($items as $item) {
// echo $item['item'] or whatever
}
EDIT: Or you can skip putting them in the array and just use the while() to do what you need to do with the data.

Categories