PHP Select Orders of Day From MySQL - php

I have a table called order and it has few columns like customer, phone and orderdate which this one has MySQL Date field type format and it is loaded like
orderdate
-|----------|--
|2014-06-12|
|2014-06-13|
|2014-06-12|
|2014-06-14|
|2014-06-14|
|2014-06-11|
|2014-06-11|
now I tried to get all orders of day by running a query like
$query = "SELECT * FROM order WHERE orderdate = DATE(NOW())";
or
$query = "SELECT * FROM order WHERE DATE(orderdate) = DATE(NOW())";
but I am not getting any thing not even error message. Can you please let me know how I can do this? Thanks
Update:
Here is the whole code:
<?PHP
include 'conconfig.php';
$con = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if (mysqli_connect_error())
{
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
$query = "SELECT * FROM order WHERE DATE(orderdate) = DATE(NOW())";
if ($result = $con->query($query))
{
if ($result->num_rows > 0)
{
$resultStr.= '<table style="width:300px">';
while($row = $result->fetch_assoc())
{
$resultStr.= '<tr><td>'.$row['customer'].'</td><td>'.$row['phone'].'</td></tr>';
}
$resultStr.= '</table>';
}
else
{
$resultStr = 'There is No Order For Today';
}
}
echo $resultStr;
$con->close();

Order is a reserved word. Try this query:
SELECT * FROM `order` WHERE orderdate = DATE(NOW())

Order is a reserved word. You can escape it with ` like so:
SELECT * FROM `order` WHERE ...
Here is a list of reserved words which should be avoided as mysql table and column names.
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

Related

PHP SQL INSERT INTO statement not working directly after table creation [duplicate]

<?php
$query1 = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X";
$query2 = "CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH)";
$query3 = "CREATE VIEW final_output AS SELECT current_rankings.player, current_rankings.rank as current_rank LEFT JOIN previous_rankings.rank as prev_rank
ON (current_rankings.player = previous_rankings.player)";
$query4 = "SELECT *, #rank_change = prev_rank - current_rank as rank_change from final_output";
$result = mysql_query($query4) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo $row['player']. $row['current_rank']. $row['prev_rank']. $row['rank_change'];
}
?>
All the queries work independently but am really struggling putting all the pieces together in one single result so I can use it with mysql_fetch_array.
I've tried to create views as well as temporary tables but each time it either says table does not exist or return an empty fetch array loop...logic is there but syntax is messed up I think as it's the 1st time I had to deal with multiple queries I need to merge all together. Looking forward to some support. Many thanks.
Thanks to php.net I've come up with a solution : you have to use (mysqli_multi_query($link, $query)) to run multiple concatenated queries.
/* create sql connection*/
$link = mysqli_connect("server", "user", "password", "database");
$query = "SQL STATEMENTS;"; /* first query : Notice the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS;"; /* Notice the dot before = and the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS;"; /* Notice the dot before = and the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS"; /* last query : Notice the dot before = at the end ! */
/* Execute queries */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_array($result))
/* print your results */
{
echo $row['column1'];
echo $row['column2'];
}
mysqli_free_result($result);
}
} while (mysqli_next_result($link));
}
EDIT - The solution above works if you really want to do one big query but it's also possible to execute as many queries as you wish and execute them separately.
$query1 = "Create temporary table A select c1 from t1";
$result1 = mysqli_query($link, $query1) or die(mysqli_error());
$query2 = "select c1 from A";
$result2 = mysqli_query($link, $query2) or die(mysqli_error());
while($row = mysqli_fetch_array($result2)) {
echo $row['c1'];
}
It seems you are not executing $query1 - $query3. You have just skipped to $query4 which won't work if the others have not been executed first.
Also
$query4 = "SELECT *, #rank_change = prev_rank - current_rank as rank_change from final_output";
should probably be
$query4 = "SELECT *, #rank_change := prev_rank - current_rank as rank_change from final_output";
or else the value of rank_change will just be a boolean, true if #rank_change is equal to (prev_rank - current_rank), false if it is not. But do you need #rank_change at all? Will you use it in a subsequent query? Maybe you can remove it altogether.
Even better, you could just combine all the queries into one like this:
SELECT
curr.player,
curr.rank AS current_rank,
#rank_change := prev.rank - curr.rank AS rank_change
FROM
main_table AS curr
LEFT JOIN main_table AS prev
ON curr.player = prev.player
WHERE
curr.date = X
AND prev.date = date_sub('X', INTERVAL 1 MONTH)
You should concatenate them:
<?php
$query = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X";
$query .= " CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH)";
$query .= " CREATE VIEW final_output AS SELECT current_rankings.player, current_rankings.rank as current_rank LEFT JOIN previous_rankings.rank as prev_rank
ON (current_rankings.player = previous_rankings.player)";
$query .= " SELECT *, #rank_change = prev_rank - current_rank as rank_change from final_output";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo $row['player']. $row['current_rank']. $row['prev_rank']. $row['rank_change'];
}
?>

How can i order by id ascending?

I want to order data by Id, how can i do this ?
if($_GET["grupid"]>0){
$DUZEN = array();
$sql = "SELECT * FROM siparis_ana WHERE grupid =".$_GET["grupid"];
$rsDuzen = mysql_query($sql, $conn) or die(mysql_error());
while ($r = mysql_fetch_assoc($rsDuzen)) {
$DUZEN[] = $r;
}
}
i can read all data with this code which have same group id. But data aline random.
You have to use mysql order clause in your query like order by id asc. Which you can use at the end of your query.
$sql = "SELECT * FROM siparis_ana WHERE grupid =".$_GET["grupid"]." order by id asc";
Your sql query should be like given below...
$sql = "SELECT * FROM siparis_ana where grupid = " . $_GET['grupid'] . " ORDER BY id asc ";

Add to string variable (string is a query)

i have a simple query who select me 3 news from table, but i wont to change this number from other file whith variable.
So this is query:
$query = 'SELECT * FROM news ORDER BY created_at DESC LIMIT 3';
I tried differently, but did not work...
Help please
My code(i can't answer on my question so i add it here)
$newsAmount = 3;
function get_news() {
$query = "SELECT * FROM news ORDER BY created_at DESC LIMIT $newsAmount";
$result = mysql_query($query);
$news = array();
while ($row = mysql_fetch_array($result)) {
$news[] = $row;
}
return $news;
if (!$result) {
trigger_error('Invalid query: ' . mysql_error() . " in " . $query);
}
}
This is this code.
Actually you can just do this:
$query = "SELECT * FROM news ORDER BY created_at DESC LIMIT $newsAmount";
But make sure to keep the string in double quotes so the variable can be evaluated, Single quotes will be printed out as it is.
Try to echo $query, you will notice that its being printed.
Try this:
$newsAmount = 3;
$query = 'SELECT * FROM news ORDER BY created_at DESC LIMIT ' + $newsAmount;
you cannot return an array like you did in your code.
I would suggest to do the query inside your main code instead of writing it in a function.

data from few MySQL tables sorted by ASC

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.

MySQL - A query based on another query

I write a lot of queries resembling the query example code below. I was wondering whether there was a more efficient code/script?
$query1 ="SELECT * FROM table1 WHERE date >= '$todaysdate' ";
$result1 = mysql_query($query1)
or die ("Error in query: $query1. " . mysql_error());
if (mysql_num_rows($result1) > 0) {
while($row1 = mysql_fetch_object($result1)) {
echo "$row1-date";
$query2 ="SELECT * FROM table2 WHERE table1ID >= '$row1-table1ID' ";
$result2 = mysql_query($query2)
or die ("Error in query: $query2. " . mysql_error());
if (mysql_num_rows($result2) > 0) {
while($row2 = mysql_fetch_object($result2)) {
echo "$row->datatable2";
}
}
}
}
Try using SQL JOINs, like the following example:
SELECT
*
FROM
table1
INNER JOIN
table2 ON (table2.table1ID = table1.ID)
WHERE
table1.date >= '2009-12-20';
I don't know about the structure of your tables, but I've modified your code so that it uses a join:
$query = 'SELECT table1.date, table2.datatable2 FROM table1, table2 WHERE table1.date >= \''.$todaysdate.'\' AND table2.table1ID >= table1.table1ID';
$result = mysql_query($query)
or exit('Error in query: '.$query.' '.mysql_error());
if (mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_object($result))
{
echo $row->date;
echo $row->datatable2;
}
}
In this case you select multiple tables with FROM separated with commas, but you can also use INNER/OUTER/LEFT/RIGHT JOIN (see the link in the first answer).
You can use PDO.
Your queries should look like this..
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_COLUMN);
// OR
$result = $sth->fetchAll(PDO::FETCH_OBJ);
var_dump($result);
PDO MANUAL: http://php.net/manual/en/book.pdo.php

Categories