I'm trying to select count of repeated dates and output its numbers
$user_curr_id = $_SESSION['user_id'];
$sql = "SELECT COUNT(datum) FROM table_name WHERE user_ids = $user_curr_id";
I have no idea how to do it.
2014-07-23,2014-07-23,2014-07-23 => 3
2014-07-24,2014-07-24 =>2
2014-07-25 => 1
and get $result = 3,2,1
I assume you're looking after the GROUP BY clause:
$sql = "SELECT datum, COUNT(datum) as cnt
FROM table_name
WHERE user_ids = $user_curr_id
GROUP BY datum
ORDER BY COUNT(datum) DESC;";
if your column datum is of the data type DATE.
Note
As already mentioned you're vulnerable to sql injection. You should use a parameterized prepared statement and bind your input value to this parameter like that:
$sql = "SELECT datum, COUNT(datum) cnt
FROM table_name
WHERE user_ids = ?
GROUP BY datum
ORDER BY COUNT(datum) DESC;";
$result = array();
if ($stmt = $mysqli->prepare($sql)) {
if ($stmt->bind_param('s', $user_curr_id)) {
if($res = $stmt->execute()) {
while ($row = $res->fetch_assoc()) {
$result[] = $row['cnt']; // add the content of field cnt
}
}
}
}
echo implode(',', $result);
Related
How to add select COUNT and DISTINCT in the below $query? Please let me know if you need any other details to solve this issue. Thank you for your time.
if(isset($_POST["intake_year"]))
{
$query = "
SELECT * FROM marketing_data
WHERE intake_year = '".$_POST["intake_year"]."'
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output[] = array(
'semester' => $row["semester"],
'student_matric' => floatval($row["count"])
);
}
echo json_encode($output);
}
//SELECT count(student_matric) AS count, semester, intake_year FROM marketing_data GROUP BY intake_year - This query is to only COUNT student_matric
//SELECT DISTINCT semester FROM marketing_data ORDER BY semester DESC - This query is to only DISTINCT semester
I guess you are looking for something like that
$query = "
SELECT distinct semester , count(student_matric) as count FROM marketing_data
WHERE intake_year = '".$_POST["intake_year"]."'
Group by student_matric " ;
I want to make for each data exist on databases then do loop up to get unique data.
Here my code:
$id = rand(10000000,99999999);
$check_id = $db->prepare("SELECT * FROM sh_url WHERE sh_id='$id'");
$check_id->execute();
$count_id = $check_id->rowCount();
for ($count_id != 0) {
$lid = $id+1;
}
$shorturl = htmlentities(base_convert($lid,20,36));
$query = $db->prepare("INSERT INTO `sh_url`(`sh_id`) VALUES (:id)");
$query->bindParam(":id", $lid);
$query->execute();
Why don't you use distinct keyword to do this.
SELECT DISTINCT column1, column2, ...
FROM table_name;
My Query:
select distinct ml.send_to from message_log as ml where NOT exists
(select mobile_no from user_details WHERE user_details.mobile_no = ml.send_to);
$select1 = $db->select()->from('user_details',array('mobile_no'))
->where('user_details.mobile_no = ml.send_to');
$select2 = $db->select()->distinct()
->from(array('ml'=>'message_log'), array('ml.send_to')))
->where('NOT EXISTS ?', $select1);
This will do the trick in the easiest way.
you can use customer query in zend as
$sql = 'select distinct ml.send_to from message_log as ml where NOT exists
(select mobile_no from user_details WHERE user_details.mobile_no = ml.send_to);';
$stmt = new Zend_Db_Statement_Mysqli($db, $sql);
$stmt->execute();
while ($row = $stmt->fetch()) {
echo $row['send_to'];
}
this will really help you
http://framework.zend.com/manual/1.12/en/zend.db.statement.html
The code I have below joins 5 tables and then is suppose to sort by date_timed_added. The query worked perfectly if i only join 4 tables. For some reason after the 4th table, its giving me issues. The issue is that it sorts and displays the 5th table first and then the rest follow. How can i fix it so that it sorts date_time_added properly by querying all the other tables?
//$sid is a variable that is drawn from DB
$sql = "select `client_visit`.`visit_id`, `client_visit`.
`why_visit`, `client_visit`.`date_time_added`, `client_visit`.
`just_date`, `client_visit`.`type` from `client_visit` where
`client_visit`.`system_id` = '$sid' and `client_visit`.
`added_by` = '$sid'
UNION
select `client_notes`.`note_id`, `client_notes`.`note_name`,
`client_notes`.`date_time_added`, `client_notes`.`just_date`
, `client_notes`.`type` from `client_notes` where `client_notes`.
`added_by` = '$sid'
UNION
select `client_conditions`.`med_id`, `client_conditions`.`med_name`,
`client_conditions`.`date_time_added`, `client_conditions`.`just_date`,
`client_conditions`.`type` from `client_conditions` where
`client_conditions`.`system_id` = '$sid' and `client_conditions`.
`added_by` = '$sid'
UNION
select `client_stats`.`stat_test_id`, `client_stats`.`stat_why`,
`client_stats`.`date_time_added`, `client_stats`.`just_date`,
`client_stats`.`type`
from `client_stats` where `client_stats`.`system_id` = '$sid'
and `client_stats`.`added_by` = '$sid'
UNION
select `client_documents`.`doc_id`, `client_documents`.`doc_name`,
`client_documents`.`date_time_added`, `client_documents`.`just_date`,
`client_documents`.`type` from `client_documents` where `client_documents`.
`system_id` = '$sid' and `client_documents`.`added_by` = '$sid'
ORDER BY `date_time_added` DESC LIMIT $startrow, 20";
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$result = mysql_query($sql);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
//Just using these two variables i can display the same row info
//for all the other tables
$stuffid = htmlspecialchars($row['visit_id']);
$title = htmlspecialchars($row['why_visit');
}
}
}
As per the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/union.html
If you want to order the ENTIRE result set, the ORDER BY clause must be placed on the LAST query in the UNION, with each query being bracketed.
(SELECT ...)
UNION
(SELECT ...)
ORDER BY ...
sth like this should do.
SELECT Tbl1.field1
FROM ( SELECT field1 FROM table1
UNION
SELECT field1 FROM table2
) Tbl1
ORDER BY Tbl1.field1
In the dbase I 've few tables named as aaa_9xxx, aaa_9yyy, aaa_9zzz. I want to find all data with a specified DATE and show it with the TIME ASC.
First, I must find a tables in the dbase:
$STH_1a = $DBH->query("SELECT table_name
FROM information_schema.tables
WHERE table_name
LIKE 'aaa\_9%'
");
foreach($STH_1a as $row)
{
$table_name_s1[] = $row['table_name'];
}
Second, I must find a data wit a concrete date and show it with TIME ASC:
foreach($table_name_s1 as $table_name_1)
{
$STH_1a2 = $DBH->query("SELECT *
FROM `$table_name_1`
WHERE
date = '2011-11-11'
ORDER BY time ASC
");
while ($row = $STH_1a2->fetch(PDO::FETCH_ASSOC)) {
echo " ".$table_name_1."-".$row['time']."-".$row['ei_name']." <br>";
}
}
.. but it shows the data sorted by tables name, then by TIME ASC. I must to have all this data (from all tables) sorted by TIME ASC.
Thank You dev-null-dweller, Andrew Stubbs and Jaison Erick for your help.
I test the Erick solution :
foreach($STH_1a as $row) {
$stmts[] = sprintf('SELECT *
FROM %s
WHERE date="%s"', $row['table_name'], '2011-11-11');
}
$stmt = implode("\nUNION\n", $stmts);
$stmt .= "\nORDER BY time ASC";
$STH_1a2 = $DBH->query($stmt);
while ($row_1a2 = $STH_1a2->fetch(PDO::FETCH_ASSOC)) {
echo " ".$row['table_name']."-".$row_1a2['time']."-".$row_1a2['ei_name']." <br>";
}
it's working but I've problem with 'table_name' - it's always the LAST table name.
//----------------------------------------------------------------------
...and the ending solution with all fixes, thanks all for your help, :))
foreach($STH_1a as $row) {
$stmts[] = sprintf("SELECT *, '%s' AS table_name
FROM %s
WHERE date='%s'", $row['table_name'], $row['table_name'], '2011-11- 11');
}
$stmt = implode("\nUNION\n", $stmts);
$stmt .= "\nORDER BY time ASC";
$STH_1a2 = $DBH->query($stmt);
while ($row_1a2 = $STH_1a2->fetch(PDO::FETCH_ASSOC)) {
echo " ".$row_1a2['table_name']."-".$row_1a2['time']."-".$row_1a2['ei_name']." <br>";
}
Instead of printing the line as you fetch it from db, gather all data in one array taht you will be able to sort with usort and your own callback function.
Other option is to get it sorted directly from mysql, using UNION selects like this:
$SQL = "
(SELECT '$table_name_1' AS tbl_name, time, ei_name FROM `$table_name_1` WHERE date = '2011-11-11')
UNION
(SELECT '$table_name_2' AS tbl_name, time, ei_name FROM `$table_name_2` WHERE date = '2011-11-11')
UNION
(SELECT '$table_name_3' AS tbl_name, time, ei_name FROM `$table_name_3` WHERE date = '2011-11-11')
ORDER BY time ASC
";
You need to use the UNION sql directive:
<?php
$STH_1a = $DBH->query("SELECT table_name
FROM information_schema.tables
WHERE table_name
LIKE 'aaa\_9%'");
$stmts = array();
foreach($STH_1a as $row)
{
$stmts[] = sprintf('SELECT *, %s AS `table_name` FROM %s WHERE date="%s"', $row['table_name'], $row['table_name'], '2011-01-01');
}
$stmt = implode("\nUNION\n", $stmts);
$stmt .= "\nORDER BY time ASC";
$STH_1a2 = $DBH->query($stmt);
FIX: Included the table name as returned value.
The correct way to fix it will be to UNION your selection data as stated in other answers.
A quick fix would be to change your second code block to something like:
$Sorted = array();
foreach($table_name_s1 as $table_name_1)
{
$STH_1a2 = $DBH->query("SELECT *
FROM `$table_name_1`
WHERE date = '2011-11-11'
ORDER BY time ASC
");
while ($row = $STH_1a2->fetch(PDO::FETCH_ASSOC)) {
$Sorted[$row['time']] = " ".$table_name_1."-".$row['time']."-".$row['ei_name']." <br>";
}
}
ksort($Sorted);
foreach($Sorted as $Entry) {
echo $Entry;
}
Note: This will 'fail' for cases where there are multiple entries for one date.