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
I have attacked this from many different ways today, I have no figured out the best way to display my data is with a single query that can be displayed in one table. The problem is I have three queries I am trying to combine, and it is not going very well. I feel like its close but clearly not correct.
$sql = (SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber UNION select dataplan as currentplan from maindata
GROUP BY phonenumber UNION SELECT DISTINCT phonenumber AS value_sum1 FROM maindata);
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)){
echo "<TABLE id='display'>";
echo "<td><b>Data Usage This Period: ". ROUND ($row["value_sum"],2) . "MB</b></td> ";
echo "<td><b>Data Plan: ". $row["currentplan"] . "</b></td> ";
echo "<td><b>Phone Number: ". $row["value_sum1"] . "</b></td> ";
echo "</TABLE>";
}
The Problem is I want three columns of data and I get just one column with all data
UNION adds extra rows to the query. It looks like you just want multiple columns. See if this query gets you any closer; if not please show some sample data and expected results:
SELECT
phonenumber AS value_sum1
dataplan AS currentplan,
SUM(datamb) AS value_sum
FROM maindata
GROUP BY
phonenumber,
dataplan
Also, consider not aliasing the phonenumber and dataplan columns - the aliases in this case just confuse things. You'll need to change the index values in the PHP code accordingly.
First replace this line :
$sql = (SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber UNION select dataplan as currentplan from maindata GROUP BY phonenumber UNION SELECT DISTINCT phonenumber AS value_sum1 FROM maindata);
By
$sql = "(SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber UNION select dataplan as currentplan from maindata GROUP BY phonenumber UNION SELECT DISTINCT phonenumber AS value_sum1 FROM maindata);"
is it possible to retrieve an array of data from more than one table within one query? For example , I am getting an array from table1, but I want to retrieve data from several other tables too:
<?php
$con = mysql_connect($hostname,$username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $con);
$today = date('Y-m-d H:i:s', time());
$today1DayAgo = date('Y-m-d H:i:s', strtotime("$today -1 day"));
$query = "SELECT * FROM table1 WHERE omtr_date BETWEEN '$today1DayAgo' AND '$today'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo $row["omtr_page_view"]);
}
mysql_close($con);
?>
Thanks
Use Mysql Joins.
Here is an example:
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT family.Position, food.Meal ";
$query .= "FROM family INNER JOIN food ";
$query .= "WHERE family.Position = food.Position";
//Execute query
$result = mysql_query($query) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
echo $row['Position']. " - ". $row['Meal'];
echo "<br />";
}
?>
More examples of mysql joins are listed here: http://phpweby.com/tutorials/mysql/32
You can use joins to do this:
E.g.
SELECT t1.*, t2.id, t2.someothercolumn FROM table1 t1 LEFT JOIN table2 t2 ON t1.id=t2.t1_id WHERE omtr_date BETWEEN '$today1DayAgo' AND '$today'
(Untested)
Might be worth reading up on them.. http://www.sitepoint.com/understanding-sql-joins-mysql-database/
If your tables have something in common, like 1 column of table1 is the primary key of table2, or any kind of a relation (like same column), you can use JOINS.
Otherwise you can use UNION as well, like
SELECT omtr_date1.a AS a1, omtr_date1.b AS b1 FROM table1 WHERE omtr_date1 BETWEEN '$today1DayAgo' AND '$today'
UNION
SELECT omtr_date2.c AS a1, omtr_date2.d AS b1 FROM table1 WHERE omtr_date2 BETWEEN '$today1DayAgo' AND '$today'
But both the select statements must produce same number of columns with same column names.
That will do you good.
Is there a way to grab the columns name of a table in MySQL using PHP?
You can use DESCRIBE:
DESCRIBE my_table;
Or in newer versions you can use INFORMATION_SCHEMA:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
Or you can use SHOW COLUMNS:
SHOW COLUMNS FROM my_table;
Or to get column names with comma in a line:
SELECT group_concat(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
The following SQL statements are nearly equivalent:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
[AND table_schema = 'db_name']
[AND column_name LIKE 'wild']
SHOW COLUMNS
FROM tbl_name
[FROM db_name]
[LIKE 'wild']
Reference: INFORMATION_SCHEMA COLUMNS
I made a PDO function which returns all the column names in an simple array.
public function getColumnNames($table){
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table";
try {
$core = Core::getInstance();
$stmt = $core->dbh->prepare($sql);
$stmt->bindValue(':table', $table, PDO::PARAM_STR);
$stmt->execute();
$output = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$output[] = $row['COLUMN_NAME'];
}
return $output;
}
catch(PDOException $pe) {
trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
}
}
The output will be an array:
Array (
[0] => id
[1] => name
[2] => email
[3] => shoe_size
[4] => likes
... )
Sorry for the necro but I like my function ;)
P.S. I have not included the class Core but you can use your own class.. D.S.
There's also this if you prefer:
mysql_query('SHOW COLUMNS FROM tableName');
This solution is from command line mysql
mysql>USE information_schema;
In below query just change <--DATABASE_NAME--> to your database and <--TABLENAME--> to your table name where you just want Field values of DESCRIBE statement
mysql> SELECT COLUMN_NAME FROM COLUMNS WHERE TABLE_SCHEMA = '<--DATABASE_NAME-->' AND TABLE_NAME='<--TABLENAME-->';
I needed column names as a flat array, while the other answers returned associative arrays, so I used:
$con = mysqli_connect('localhost',$db_user,$db_pw,$db_name);
$table = 'people';
/**
* Get the column names for a mysql table
**/
function get_column_names($con, $table) {
$sql = 'DESCRIBE '.$table;
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row['Field'];
}
return $rows;
}
$col_names = function get_column_names($con, $table);
$col_names now equals:
(
[0] => name
[1] => parent
[2] => number
[3] => chart_id
[4] => type
[5] => id
)
It's also interesting to note that you can use
EXPLAIN table_name which is synonymous with DESCRIBE table_name and SHOW COLUMNS FROM table_name
although EXPLAIN is more commonly used to obtain information about the query execution plan.
How about this:
SELECT #cCommand := GROUP_CONCAT( COLUMN_NAME ORDER BY column_name SEPARATOR ',\n')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
SET #cCommand = CONCAT( 'SELECT ', #cCommand, ' from my_database.my_table;');
PREPARE xCommand from #cCommand;
EXECUTE xCommand;
Look into:
mysql_query('DESCRIBE '.$table);
The MySQL function
describe table
should get you where you want to go (put your table name in for "table"). You'll have to parse the output some, but it's pretty easy. As I recall, if you execute that query, the PHP query result accessing functions that would normally give you a key-value pair will have the column names as the keys. But it's been a while since I used PHP so don't hold me to that. :)
The mysql_list_fields function might interest you ; but, as the manual states :
This function is deprecated. It is
preferable to use mysql_query() to
issue a SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead.
You may also want to check out mysql_fetch_array(), as in:
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
//$row[0] = 'First Field';
//$row['first_field'] = 'First Field';
}
in mysql to get columns details and table structure by following keywords or queries
1.DESC table_name
2.DESCRIBE table_name
3.SHOW COLUMNS FROM table_name
4.SHOW create table table_name;
5.EXPLAIN table_name
you can get the entire table structure using following simple command.
DESC TableName
or you can use following query.
SHOW COLUMNS FROM TableName
$col = $db->query("SHOW COLUMNS FROM category");
while ($fildss = $col->fetch_array())
{
$filds[] = '"{'.$fildss['Field'].'}"';
$values[] = '$rows->'.$fildss['Field'].'';
}
if($type == 'value')
{
return $values = implode(',', $values);
}
else {
return $filds = implode(',', $filds);
}
this worked for me..
$sql = "desc MyTableName";
$result = #mysql_query($sql);
while($row = #mysql_fetch_array($result)){
echo $row[0]."<br>";
}
I have write a simple php script to fetch table columns through PHP:
Show_table_columns.php
<?php
$db = 'Database'; //Database name
$host = 'Database_host'; //Hostname or Server ip
$user = 'USER'; //Database user
$pass = 'Password'; //Database user password
$con = mysql_connect($host, $user, $pass);
if ($con) {
$link = mysql_select_db($db) or die("no database") . mysql_error();
$count = 0;
if ($link) {
$sql = "
SELECT column_name
FROM information_schema.columns
WHERE table_schema = '$db'
AND table_name = 'table_name'"; // Change the table_name your own table name
$result = mysql_query($sql, $con);
if (mysql_query($sql, $con)) {
echo $sql . "<br> <br>";
while ($row = mysql_fetch_row($result)) {
echo "COLUMN " . ++$count . ": {$row[0]}<br>";
$table_name = $row[0];
}
echo "<br>Total No. of COLUMNS: " . $count;
} else {
echo "Error in query.";
}
} else {
echo "Database not found.";
}
} else {
echo "Connection Failed.";
}
?>
Enjoy!
mysqli fetch_field() worked for me:
if ($result = $mysqli -> query($sql)) {
// Get field information for all fields
while ($fieldinfo = $result -> fetch_field()) {
printf("Name: %s\n", $fieldinfo -> name);
printf("Table: %s\n", $fieldinfo -> table);
printf("Max. Len: %d\n", $fieldinfo -> max_length);
}
$result -> free_result();
}
Source: https://www.w3schools.com/pHP/func_mysqli_fetch_field.asp
The easy way, if loading results using assoc is to do this:
$sql = "SELECT p.* FROM (SELECT 1) as dummy LEFT JOIN `product_table` p on null";
$q = $this->db->query($sql);
$column_names = array_keys($q->row);
This you load a single result using this query, you get an array with the table column names as keys and null as value.
E.g.
Array(
'product_id' => null,
'sku' => null,
'price' => null,
...
)
after which you can easily get the table column names using the php function array_keys($result)
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