Determine how many entries exist for a certain date - php

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);

Related

How to remove duplicates from json in PHP

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'

Counting the number of times each variable appears in table

Basically, I am seeking to know if there is a better way to accomplish this specific task.
Basically, what happens is I query the db for a list of "project needs" -- These are each uniquer and only appear once.
Then, I search another table to find out how many members have the required "skills - which are directly correlated to the project needs".
I accomplished exactly what I was trying to do by running a second query and then inserting them into an array like this:
function countEachSkill(){
$return = array();
$query = "SELECT DISTINCT SKILL_ID, SKILL_NAME FROM PROJECT_NEEDS";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result)){
$query = "SELECT COUNT(*) as COUNT FROM MEMBER_SKILLS WHERE SKILL_ID = '".$row['NEED_ID']."'";
$cResult = mysql_query($query);
$cRow = mysql_fetch_assoc($cResult);
$return[$row['SKILL_ID']]['Count'] = $cRow['COUNT'];
$return[$row['SKILL_ID']]['Name'] = $row['SKILL_NAME'];
}
arsort($return);
return $return;
}
But I feel like there has to be a better way (perhaps using some kind of join?) that would return this in a result set to avoid using the array.
Thanks in advance.
PS. I know mysql_ is depreciated. It is not my choice on which to use.
SELECT P.SKILL_ID, P.SKILL_NAME, COUNT(M.SKILL_ID) as COUNT FROM PROJECT_NEEDS P INNER JOIN MEMBER_SKILLS M
ON P.SKILL_ID=M.SKILL_ID
GROUP BY P.SKILL_ID, P.SKILL_NAME
I've adjusted Nriddens answer to accomodate for the select distinct, Im under the belief that his adjustment would be ok given SKILL_ID is a primary key
function countEachSkill(){
$return = array();
$query = "
SELECT
COUNT(*) AS COUNT,
PROJECT_NEEDS.SKILL_NAME,
PROJECT_NEEDS.SKILL_ID
FROM
(SELECT DISTINCT
SKILL_ID, SKILL_NAME
FROM
PROJECT_NEEDS) AS PROJECT_NEEDS
INNER JOIN
MEMBER_SKILLS
ON
MEMBER_SKILLS.SKILL_ID = PROJECT_NEEDS.SKILL_ID
GROUP BY PROJECT_NEEDS.SKILL_ID";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result)){
$return[$row['SKILL_ID']]['Count'] = $row['COUNT'];
$return[$row['SKILL_ID']]['Name'] = $row['SKILL_NAME'];
}
arsort($return);
return $return;
I am subquerying on the select distinct because I dont believe you have a dedicated skills table with an auto inc primary key, if that was there I wouldn't be using a subquery.
Can you test this query
select project_needs.*,count(members_skills.*) as count from project_needs
inner join members_skills
on members_skills.skill_id=project_needs.skill_id Group by project_needs.skill_name, project_needs.skill_id

Total up how many men and how many women in a column. Possibly in order to repopulate the planet

Trying to search through a column in a db, and pull out the total number of males, and total number of females.
This data is stored in the db as f and m in the whatsex column.
$query = "SELECT whatsex, COUNT(*) FROM soberdata GROUP BY whatsex";
$result = mysqli_query($connection,$query) or die(mysql_error());
$sexdb = mysqli_fetch_array($result);
$totalmale = $sexdb['m'];
$totalfemale = $sexdb['f'];
echo $totalfemale." & ".$totalmale;
This code outputs nothing. What am I doing wrong?
$sexdb have only "whatsex" and "COUNT(*)" columns. You should use one of them
try
print_r($sexdb);
and look if some of results meet your needs
Your query is going to return a whatsex value, and a COUNT(*) value, not m or f. Doing a var_dump($sexdb) would show you what's in the array.
You are treating a multi-dimensional array as flat. You could do this to flatten it
$query = "SELECT whatsex, COUNT(*) as total FROM soberdata GROUP BY whatsex";
while ($row = mysqli_fetch_array($result)) {
$$row['whatsex'] = $row['total']; // this makes a variable ($m or $f) using the value of the row
}
$totalmale = !empty($m) ? $m : 0;
$totalfemale = !empty($f) ? $f : 0;
You should empty check the results of the db in case there is no male or female entries to avoid errors.

mysql multiple table query inside php loop

Faily new to php and mysql, this will probably seem very messy.
This is what I came up with:
$query = "show tables like 'whatever%'";
$result = mysql_query($query);
$num_results = mysql_num_rows($result);
for ($i = 0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
$sql=mysql_query("SELECT * FROM ". $row[0] ." WHERE a=(SELECT MAX(a)) AND b=(SELECT MAX(b)) AND c LIKE 'd%' ORDER BY date DESC LIMIT 1");
while($info=mysql_fetch_array($sql)){
echo "...";
}
}
I get the desired value from each table, so x results depending on the amount of tables. What I would like is to have the results of the queried tables but only show the top 10-5 ordered by date/time.
Is this possible with the current script? Is there an easier way (while, number of tables changing constantly)? Is this query method database intensif?
Cheers!
I call constantly changing number of tables having similar structure a design error. also query switch to
$sql=mysql_query("SELECT * FROM $tbl WHERE c LIKE 'd%' ORDER BY a DESC, b DESC, date DESC LIMIT 1");
is a little relief to database.

While loop problems

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?

Categories