ARRAY PHP How to put variables in array - php

Hi guys i would like to ask help on my problem..
I have 4 variables made from my query:
$sql1 = mysql_num_rows(mysql_query("SELECT * FROM tbl_reservation WHERE YEAR(date_added) = YEAR(NOW()) AND order_action = 'Online Transaction' "));
$sql2 = mysql_num_rows(mysql_query("SELECT * FROM tbl_reservation WHERE YEAR(date_added) = YEAR(NOW()) AND order_action = 'Walkin Transaction' "));
$sql3 = mysql_num_rows(mysql_query("SELECT * FROM tbl_reservation WHERE YEAR(date_added) = YEAR(NOW())-1 AND order_action = 'Online Transaction' "));
$sql4 = mysql_num_rows(mysql_query("SELECT * FROM tbl_reservation WHERE YEAR(date_added) = YEAR(NOW())-1 AND order_action = 'Walkin Transaction' "));
I would like to put them in an array..to be exactly on my expectations.
Here is my sample code:
$stack = array($sql1, $sql2);
array_push($stack, $sql3, $sql4);
$query = print_r($stack);
$result = $query;
print json_encode($result);
It display like this on my browser:
Array ( [0] => 0 [1] => 8 [2] => 0 [3] => 1 ) true
But i want to display it like this:
[{"0","1"},
{"2","3"}]
I am planning to make a line graph on this.. I have a Chart.min.js and jquery.min.js
If any way.. The whole point.. i want to make a line graph that would compare my data from current year to last year.
Help me pls. :(

Give a try
<?php
$a = array(0,8,0,1) ;
echo "<pre>";print_r(json_encode(array_chunk($a, 2)));
?>
with that. You can get this result
[[0,8],[0,1]]
Btw, Why you need to do that with your array ? .
Edited
After i check your question again, So you want get the order
<?php
$stack = array(0,8,0,1) ;
$array2= array();
foreach ($stack as $key => $val) {
$array2[] = $key;
}
echo "<pre>";print_r(json_encode(array_chunk($array2, 2)));
?>

Related

Combine multiple array but when one array is empty not show anything in php

I need help about combine multiple array from database and fetch with
fetchAll(PDO::FETCH_ASSOC)
first I look for data member with percentage of 90% and every data in search in database in subtract one column in query "SELECT", for example like this :
$query1 = "SELECT * FROM tb_member WHERE category = '1' AND gender = 'M' AND age = '30'";
$stmt1 = $this->db->prepare($query1);
$stmt1->execute();
$data1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);
$query2 = "SELECT * FROM tb_member WHERE category = '1' AND age = '30'";
$stmt2 = $this->db->prepare($query2);
$stmt2->execute();
$data2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
$query3 = "SELECT * FROM tb_member WHERE category = '1' AND gender = 'M'";
$stmt3 = $this->db->prepare($query3);
$stmt3->execute();
$data3 = $stmt3->fetchAll(PDO::FETCH_ASSOC);
And I combine the array with a sample code like this
$data = $data1 + $data2 + $data3;
I have tried and succeeded, but when one of the array is empty or unread it will error or not display any data even notification error
And i try make "if and else" like this
if(empty($data1)){
$data = $data2 + $data3;
}
elseif(empty($data2)){
$data = $data1 + $data3;
}
elseif(empty($data3)){
$data = $data1 + $data2;
}
else{
$data = $data1 + $data2 + $data3;
}
And page not show anything or blank, is there any other solution to solve this problem ?
UPDATE
After all i use array_merge() to combine multiple array from #Saral and when some variable is empty i use code sample like this
if(empty($array)){
$array = array();
}
And then it's work, thank you.
You combine array like this
$data = array_merge($data1, $data2, $data3);
For example,
$array1 = [];
$array2 = ['a', 'b'];
$array3 = ['l', 'k', 'm'];
$array4 = [];
$array = array_merge($array1, $array2, $array3, $array4);
print_r($array);
Output:
Array ( [0] => a [1] => b [2] => l [3] => k [4] => m )
It's weird that $array = $array1+$array2+$array3+$array4; gave me Array ( [0] => a [1] => b [2] => m )
The best way to combine array like this:
$data=compact($data1,$data2,$data3);
or
$data=array_combine($data1,$data2,$data3);

Add to array in comma separated values from database

my database table is named order. it has a row like order. I store values like this 1,2,3,4,5. Now i would like to add to array and from it out info..
I tried to do that but it is not working...
here is my code:
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
$array = array($sql_order);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
if want check print_r($array) Output
Array ( [0] => 1,23,4,5 )
this one is not working.. i think its supposed to be like this: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
FASTEST APPROACH
You need to use explode() function. Here is an example of it :
<?php
$array = array('0' =>'1,2,3,4,5');
$array = explode(',', $array[0]);
var_dump($array);
?>
Here is your updated code, to get array in that format.
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
$array = array($sql_order);
$array = explode(',', $array[0]);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
Note this is solution which you are looking for. But it isn't recommended due to reason told to you as comment.
PROPER WAY TO HANDLE THIS
You should ideally normalize your Database so this kind of problem don't come even in future to you.
Here is a proposed table structure change, which you can consider, depending on your need & time.
Remove order column from your table. Add a new table named order_suborders as follows:
| COLUMN | TYPE |
|:-----------|------------:|
|parent_order| int |
| order_id | int |
You can change name of columns and table according to your wish.
Move old data accordingly.
Use query SELECT order_suborders.order_id FROM order, order_suborders WHERE order.id = ".$_GET['id']." AND order.id = order_suborders.parent_order
you can use explod to split with ","
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
//$array = array($sql_order);
$array=explod(",",$sql_order);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}

How to get multiple results from SQL query

I have this function:
function findAllmessageSender(){
$all_from = mysql_query("SELECT DISTINCT `from_id` FROM chat");
$names = array();
while ($row = mysql_fetch_array($all_from)) {
$names[] = $row[0];
}
return($names);
}
that returns all the ID of my users in a private messaging system. Then I want to get the all the messages where the user_id is equal to the user logged in and from_id is equal to all from_id I got from the previous function:
function fetchAllMessages($user_id){
$from_id = array();
$from_id = findAllmessageSender();
$data = '\'' . implode('\', \'', $from_id) . '\'';
//if I echo out $ data I get these numbers '113', '141', '109', '111' and that's what I want
$q=array();
$q = mysql_query("SELECT * FROM chat WHERE `to_id` = '$user_id' AND `from_id` IN($data)") or die(mysql_error());
$try = mysql_fetch_assoc($q);
print_r($try);
}
print_r return only 1 result:
Array (
[id] => 3505
[from_id] => 111
[to_id] => 109
[message] => how are you?
[sent] => 1343109753
[recd] => 1
[system_message] => no
)
But there should be 4 messages.
You have to call mysql_fetch_assoc() for each row that is returned. If you just call mysql_fetch_assoc() once then its only going to return the first row.
Try something like this:
$result = mysql_query("SELECT * FROM chat WHERE `to_id` = '$user_id' AND `from_id` IN($data)") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
'mysql_fetch_assoc' returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
You need to iterate array like:
while ($row = mysql_fetch_assoc($q)) {
echo $row["message"];
}

mysql statement not working

I have this code
if(!isset($_GET['album_id'])) { die("Album Not Found!"); } else { $album_id = mysql_real_escape_string($_GET['album_id']); }
$sql = "SELECT * FROM `audio_albums` WHERE `album_id` = ".$album_id."";
$qry = mysql_query($sql);
$num = mysql_num_rows($qry);
if($num == 1) {
// Fetch Array
$arr = mysql_fetch_array($qry);
// Assign Values
$album_name = $arr['album_name'];
$album_name_seo = $arr['album_name_seo'];
$album_id = $arr['album_id'];
// Fetch Songs
$sql2 = "SELECT audio_id,album_id,title FROM `audios` WHERE `album_id` = ".$album_id." AND `public_private` = 'public' AND `approved` = 'yes' LIMIT 0, 30 ";
$qry2 = mysql_query($sql2);
$arr2 = mysql_fetch_array($qry2);
print_r($arr2);
} else {
echo "Album Not Found!";
}
and when i execute the code, it results in this
Array
(
[0] => qCpPdBZIpkXfVIg4iUle.mp3
[audio_id] => qCpPdBZIpkXfVIg4iUle.mp3
[1] => 1
[album_id] => 1
[2] => Ambitionz Az a Ridah
[title] => Ambitionz Az a Ridah
)
Actually it fetches data of only one row but there are several rows in result. Whats wrong in the code? why isn't it working?
Well, mysql_fetch_array fetches one row. You just need to do a loop to fetch all of them, as the manual shows: http://php.net/mysql_fetch_array
while ($arr2 = mysql_fetch_array($qry2)) {
print_r($arr2);
}
You really should learn some SQL ( yes , actually learn it ), and stop using the horribly outdated mysql_* functions.
$stmt = $dbh->prepare('
SELECT
audios.audio_id AS audio_id
audio_albums.album_id AS album_id
audios.title AS title
audio_albums.album_name AS album
audio_albums.album_name_seo AS seo_album
FROM audios
LEFT JOIN audio_albums USING (album_id)
WHERE
audio_albums.album_id = :id
audios.public_private = "public" AND
audios.approved = "yes"
LIMIT 0, 30
');
$stmt->bindParam( ':id', $_GET['album_id'], PDO::PARAM_INT );
if ( $stmt->execute() )
{
var_dump( $stmt->fetchAll(PDO::FETCH_ASSOC) );
}else{
echo 'empty .. try another';
}

Adding to a loop in PHP without overwriting

I am trying to store the dates and month name from my database in this format. I am aiming to store the month and then count the entries in that month and then store the count. This is my loop, but I have trouble formatting the array properly.
while ( $row = mysql_fetch_assoc($res) ) {
if ($row['Date'] != $prev_date) {
$values=array(
$row['Date'] => $count,
);
$prev_date = $row['Date'];
}
$count++;
}
print_f($values);
You can see that I will always overwrite my previous array and I am not really adding entries into the array. I couldn't figure out how to do it. I'm basically trying to see the number of entries per month.
OLD Update: Currently learning the MYSQL thing that one commenter mentioned. I'll update when I get it.
You can make this using group by in sql, some like this: select date, count(*) from table group by date
Edit:
If you need only count by month use some like this: select MONTH(dateField) as NewDate, count(*) FROM table GROUP BY NewDate
I almost got it!
$values=array();
while ( $row = mysql_fetch_assoc($res) ) {
if ($row['Date'] != $prev_date) {
$values[$row['Date']] = $count;
$prev_date = $row['Date'];
$count = 0;
}
$count++;
}
Update: Need a little help with this part.
My output:
Array ( [9] => [10] => 999 [11] => 986 )
999 was supposed to be stored in 9 and 986 was supposed to be stored in 10.
Update: Here's my new code, I would appreciate it if someone can show me a more efficient way.
$sql = "SELECT MONTH(AddDate) AS Date, column_name FROM table ORDER BY AddDate ASC";
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
$values=array();
while ( $row = mysql_fetch_assoc($res) ) {
if ( $row['Date'] != $prev_date) {
$month = $row['Date'];
$sql = "SELECT count(MONTH(AddDate)) AS EntryAmount FROM `table` WHERE MONTH(AddDate)=$month ";
$countResults = mysql_query($sql) or die(mysql_error());
if( $entryAmount = mysql_fetch_array($countResults) ) {
$values[$row['Date']] = $entryAmount['EntryAmount'];
}
$prev_date = $row['Date'];
}
}
Output:
Array ( [9] => 999 [10] => 986 [11] => 264 )
Not sure I understand what you're trying to do. How about this?
$values[$row['Date']]++;
How about looping on the result of a query something like this:
SELECT COUNT(MONTH(AddDate)) AS EntryAmount, MONTH(AddDate) as MonthValue FROM table GROUP BY MONTH(AddDate)

Categories