I have a MySQL, PHP code as follows.
$sql = "SELECT * FROM shipschedule WHERE ship_date BETWEEN '2016-08-01' AND '2016-8-31'";
$result = $mysqli->query($sql);
$e = array();
while($r = $result->fetch_array()) {
$rows = array();
$rows['title'] = $r['title'];
$rows['start'] = $r['ship_date'];
array_push($e, $rows);
}
echo json_encode($e);
The above php code echos
[{"title":"111","start":"2016-08-10"},
{"title":"111","start":"2016-08-10"},
{"title":"111","start":"2016-08-10"},
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-16"}]
My question is how I can echo the above as follow instead. Please see that duplicate start dates will be removed by title.
[{"title":"111","start":"2016-08-10"},
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-16"}]
title 111 has the same 3 start dates, and I need to display it like
{"title":"111","start":"2016-08-10"},
title 222 has the same 2 start dates, and I need to display it like
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-16"}]
You could prevent receiving duplicates, and reduce requesting unnecessary data by adjusting your query.
SELECT DISTINCT title, start FROM ...
It would be much easier (and probably faster too) to just get the right (unique) data from MySQL. This can be achieved with the distinct modifier:
SELECT DISTINCT title, start
FROM shipschedule
WHERE ship_date BETWEEN '2016-08-01' AND '2016-8-31'
Related
I'm trying to get specific rows in table 1 (stellingen). I want to store these rows to specify the rows im interested in for the second table (stelling). So lets say table 1 has 5 rows where stelling ID matches REGIOID = 5. These IDS from stelling ID I want to use to fetch the data from the second table. see the code to see what I tried. I'm not managing to find a way in order too make this happen.
So maybe too be clearer because people always say im not clear:
There are two tables. they both have a matching column. Im trying to tell the second table I want data but only if it matches the data of the first table. Like a branch of a tree. Then, I want to output some data that's in the second table.
I've tried something like this before:
SELECT
*
FROM
table2
LEFT JOIN
table1 ON
table1.ID = table2.table1_id
I've tried to create a while loop to get the data before(after the first if statement and the last += was for the variable $amountofstellinge):
$amountOfStellinge = 0;
while ($amountOfStellinge<5){
mysqli_data_seek($result, $amountOfStellinge);
Here is the code what it looks like now, its wrong, i've been messing with t a lot, but maybe it shows you what I'm trying to achieve better.
if($result = mysqli_query($con, "SELECT * FROM stellingen WHERE REGIOID=1;")) {
$row = mysqli_fetch_assoc($result);
$stellingid= $row["Stelling_ID"];
//checking.. and the output is obviously not what I want in my next query
printf($stellingid);
//defining the variable
$Timer=0;
$sql1="SELECT * FROM stelling WHERE stelling_iD=$stellingid ORDER BY Timer DESC;";
$records2 = mysqli_query($con, $sql1);
$recordscheck = mysqli_num_rows($records2);
//max 5 data
if ($recordscheck < 5){
while ($stelling = mysqli_fetch_assoc($records2)){
//At the end, i would like to only have the data that is most recent
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}}
$recordscheck+=1; } // this is totally wrong
EDIT:
I've tried this, #noobjs
$Timer=0;
$sql1="SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.ID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer LIMIT 5 DESC ;";
$records2 = mysqli_query($con, $sql1);
printf($records2);
while ($stelling = mysqli_fetch_assoc($records2)){
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}
with this error:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in
EDIT for more clarification
Here is some sample data
The expected results is:
every page has uses data from a different REGIOID. I expect the page to show data from the table stelling(Table 1). Accordingly to the REGIOID (Table2)
if i understand right:
SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.stellingID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer DESC LIMIT 5 ;
here's the code and i want to echo only 1 city from mysql database!
<?php
include('db.php');
$queryss = mysqli_query($conn, 'SELECT * FROM areas');
while ($rowx = mysqli_fetch_array($queryss)) {
echo "{pro:'$rowx[1]',city:'$rowx[2]', dist:'$rowx[3]', town:'$rowx[4]', area:'$rowx[5]',subarea:'$rowx[6]',ucname:'$rowx[7]'},";
}
?>
and i'm, getting this input here! 3 time karachi in my html, but i want only 1 of this city. SELECT DISTINCT is working in mysql but how can i use it in PHP?
Your query should be
SELECT * FROM areas GROUP BY id
I have tested it.
Use
SELECT DISTINCT column_name1,column_name2 FRAM areas
in your SQL where column_nameN stands for the columns you need for your output.
OR use something like this (untested):
$results = [];
while ($rowx = mysqli_fetch_array($queryss)) {
$results[] = $rowx;
}
$results= array_unique($results);
foreach($results as $rowx) {
echo "{pro:'$rowx[1]',city:'$rowx[2]', dist:'$rowx[3]', town:'$rowx[4]', area:'$rowx[5]',subarea:'$rowx[6]',ucname:'$rowx[7]'},";
}
First Solution
You can insert distinct keyword into your SQL to accomplish what you need, like so
SELECT DISTINCT your_column_name FROM table_name
Second Soltion
You can execute your SQL statement and then use array_unique, to be like so
$selectStatement = mysqli_query($con, 'SELECT * FROM areas');
$selectedArrayValues = mysqli_fetch_array($selectStatement);
$selectedUniqueArrayValues = array_unique(selectedArrayValues);
// Then return that array to your HTML code
I recommend the first solution because it's more optimized
This question already has answers here:
Subquery returning more than 1 row
(3 answers)
Closed 1 year ago.
I want to run a foreach loop from database, but I dont know how to start. I have an array which I have generated from a while loop:
/* mysql query for geting leave_type ID */
$leaveType = mysql_query("
SELECT `leave`.leave_type_id_leave_type,
`leave`.staff_leave_application_staff_id_staff,
`leave`.date,
`leave`.date_updated,
`leave`.active
FROM `leave`
WHERE `leave`.staff_leave_application_staff_id_staff = $iid
GROUP BY `leave`.leave_type_id_leave_type
");
/* Now put all leave Type ID in an array */
echo "<table>";
$types = array();
while($leaveFW = mysql_fetch_array( $leaveType )){
$types[] = $leaveFW['leave_type_id_leave_type'];
}
print_r($types);
Now I want to run a foreach loop which will query below code for each ID in array. :
$leaveQ = mysql_query("SELECT Count(*) as total, monthname(date) as
month FROM `leave`
WHERE `leave`.staff_leave_application_staff_id_staff = $iid
and `leave`.leave_type_id_leave_type = $type");
I want to show $leaveQ['month'] and $leaveQ['total'] in foreach loop.
May be my foreach like this, but how to get $type['month'] and $type['total'] :
foreach ($types as $type)
{
$leaveQ = mysql_query("SELECT Count(*) as total, monthname(date) as month
FROM `leave` WHERE `leave`.staff_leave_application_staff_id_staff = $iid
and `leave`.leave_type_id_leave_type = $type");
}
May youwant something like this
foreach($types as $result)
{
$iid = $result['staff_leave_application_staff_id_staff'];
$type = $result['leave_type_id_leave_type'];
$leaveQ = mysql_query("SELECT Count(*) as total, monthname(date) as
month FROM `leave`
WHERE `leave`.staff_leave_application_staff_id_staff = $iid
and `leave`.leave_type_id_leave_type = '".$leaveFW['leave_type_id_leave_type']."'");
while($row = mysql_fetch_assoc($leaveQ))
{
echo $row['month']."<br>";
echo $row['total']."<br>";
}
}
Don't do this!
mysql_ functions are deprecated as of PHP 5.5!
doing this (get one query, then run another query for each rows in a foreach loop) is a bad approach, commonly seen in a lot of code flying around the 'net...
Also, I think you want to get the count for each month; in that case you have to use the GROUP BY clause for that
The proper way to do this is using JOIN operations, and instead of a query for each line, only one query to get all the data.
Blindly following that advice, not changing too much, just merging the two queries, your query should look like this:
SELECT Count(*) as total, monthname(date) as month, types.leave_type_id_leave_type
FROM `leave`
JOIN (SELECT DISTINCT `leave`.leave_type_id_leave_type
FROM `leave`
WHERE `leave`.staff_leave_application_staff_id_staff = $iid) as types
ON leave.leave_type_id_leave_type = types.leave_type_id_leave_type
WHERE `leave`.staff_leave_application_staff_id_staff = $iid
GROUP BY monthname(date), types.leave_type_id_leave_type
Differences to your approach:
the inner query is almost the same as your 1st query, but
instead of GROUP BY, I used the DISTINCT - in this case, it is the same, but I think this is easier to read - and that is an important aspect!
I only selected the relevant column for it (leave_type_id_leave_type)
I altered the outer query a bit more
the JOIN does what replaces the "foreach" approach
only those rows are "taken into count" (in this case, literally :) ), that are appropriate for the inner query
this will return the count for each month and each type.
To make this even better:
Use properly parametrized prepared statements: better performance, and getting used to it makes you avoid SQL injection in situations where that applies...
you can use PDO for that, it is not deprecated...
Looking at the resulting query, it is easy to see that this can be further simplified, and does not need the inner query, also getting rid of one filter on $iid
SELECT Count(*) as total, monthname(date) as month, leave_type_id_leave_type
FROM `leave`
WHERE `leave`.staff_leave_application_staff_id_staff = $iid
GROUP BY monthname(date), leave_type_id_leave_type
Differences now:
huge performance jump...
a lot less, and a lot readable code
EDIT
Here is the SQL fiddle to see how this works
foreach($types as $type){
$leaveQ = mysql_query("SELECT Count(*) as total, monthname(date) as
month FROM `leave`
WHERE `leave`.staff_leave_application_staff_id_staff = $iid
and `leave`.leave_type_id_leave_type = $type");
while($leave = mysql_fetch_assoc($leaveQ)){
var_dump($leave['total'] , $leave['month']);
}
}
If I understand correctly you want to loop thru the types found from your block of code and then issue more database queries and extract more data.
You can basically reuse your first block of code again, wrapped with a foreach loop:
foreach($types as $type){
$query = mysql_query("YOUR_SQL_USING_$TYPE");
while($row = mysql_fetch_array( $query )){
print_r($row);
// or print($row['COLUMN_NAME']);...
}
}
All,
I have the following code:
$fetch = mysql_query("SELECT * FROM calendar_events where event_status='booked' and event_type='wedding' GROUP BY start");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['title'] = $row['title'];
$row_array['start'] = $row['start'];
$row_array['end'] = $row['end'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
I'm using the fullcalendar and trying to determine how many events have the same start date. So for example if I had the following dates:
02/06/2012
02/06/2012
03/01/2012
04/05/2012
On dates that have entries in my database I'd like to basically see how many events are on that date and basically say how many spots are left. So for any given date I can have two scheduled events so for 02/06/2012 I'd like it to return "Booked" and for 03/01/2012 I'd like "1 spot left" and etc.
How can I go about doing something like this?
Thanks!
SELECT
start, count(*) as used, 2-count(*) as free
FROM calendar_events
WHERE event_status='booked'
and event_type='wedding'
GROUP BY start
or as by your comment:
SELECT
date(start) as eventdate, count(*) as used, 2-count(*) as free
FROM calendar_events
WHERE event_status='booked'
and event_type='wedding'
GROUP BY date(start)
You're almost there, but you want to use COUNT(*) to return the number of entries in the group. (Remember to give the column an alias so that you can retrieve it.) You should also limit yourself the retrieving only the start column since retrieving columns that aren't in the GROUP BY clause is non-standard.
You're almost done, as the others beat me to the punch. You can try something like this. The important part is simply having the count as mentioned.
$fetch = mysql_query("SELECT id,title,start,end,count(*) as filled FROM calendar_events where event_status='booked' and event_type='wedding' GROUP BY start");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['title'] = $row['title'];
$row_array['start'] = $row['start'];
$row_array['end'] = $row['end'];
$row_array['filled'] = $row['filled'];
$row_array['booked'] = ($row['filled'] >= 2) ? true : false;
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
I have put together the following code, the problem is that each while loop is only returning one set of data.
$result = mysql_query("SELECT date FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' GROUP BY date");
$i = 1;
echo "<table cellspacing=\"10\" style='border: 1px dotted' width=\"300\" bgcolor=\"#eeeeee\">";
while ($row = mysql_fetch_assoc($result))
{
$date=date("F j Y", $row['date']);
echo $date;
echo "
<tr>
<td>Fixture $i - Deadline on $date</td>
</tr>
";
$result = mysql_query("SELECT * FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' AND date = '$row[date]' ORDER BY date");
while ($row = mysql_fetch_assoc($result))
{
extract ($row);
echo "
<tr>
<td>$home_user - $home_team V $away_user - $away_team</td>
</tr>
";
}
$i++;
}
echo "</table>";
I should get many dates, and then each set of fixture below.
At the moment, the first row from the first while loop is present, along with the data from the second while loop.
However, it doesn't continue?
Any ideas where I can correct this?
Thanks
Replace
$result = mysql_query("SELECT * FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' AND date = '$row[date]' ORDER BY date");
while ($row = mysql_fetch_assoc($result))
with
$result1 = mysql_query("SELECT * FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' AND date = '$row[date]' ORDER BY date");
while ($row = mysql_fetch_assoc($result1))`
What happens with your current code is that after executing internal while, next call (in external loop)to mysql_fetch_assoc($result) always returns false (because you just iterated through it in internal loop). All you need is to use a different variable in internal loop.
You're overwriting the $result variable. Change the second one to $result2 or something and see what happens. Make sure you do it when you set the variable, and use it in the query.
You are changing your $result variable in your loop so it is at the end after the inner while loop has run.
you just mixing variables. second result and row should be named differently.
though it would be better to make it with one single query
Well you've got the answer to your question.
I just want to add that usually you can write a smarter SQL query and manage without an inner query with it's loop. And your code will work a lot faster if you'll have 1 query instead of N+1.
LEFT JOIN usually can be used to replace inner looping. Example:
SELECT DISTINCT A.date, B.* FROM table_fixtures A
LEFT JOIN table_fixtures B ON A.date = B.date
WHERE B.compname = "a value"
However this time it looks illogical. I think what you actually do is achievable with a simple query like this:
SELECT * FROM table ORDER WHERE compname="something" ORDER BY date
You are reusing the same variables over for your inner loop and its breaking the outer loop.
Change your inner loop to something like:
$result2 = mysql_query("SELECT * FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' AND date = '$row[date]' ORDER BY date");
while ($row2 = mysql_fetch_assoc($result2))
{
extract ($row2);
echo "
<tr>
<td>$home_user - $home_team V $away_user - $away_team</td>
</tr>
";
}
On a different note - why do you have a GROUP BY date in the first row, when all you have in the projection list is the date?