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);"
Related
i have made a query to select only the last date for each user. It works in phpmyadmin but when i want to execute it in a mysqli_query() in PHP it doesnt give anything back, not even an error.
the code is:
select * from table t inner join ( select User_ID, max(Date) as MaxDate from table group by User_ID ) tm on t.User_ID = tm.User_ID and t.Date = tm.MaxDate
If you have any idea why please let me know :)
EDIT
the PHP code is :
$id = $_SESSION["ID"];
$SqlQuery = "SELECT * from 'tablename' t inner join ( select 'User_ID', max('Date') as 'MaxDate' from 'tablename' group by 'User_ID' ) tm on 't.User_ID' = 'tm.User_ID' and 't.Date' = 'tm.MaxDate'";
$Result = mysqli_query($link, $SqlQuery) or die ("not possible to execute query: $sql on $link");
if ($Result->num_rows > 0) {
while($row = $Result->fetch_assoc()) {
echo "<br> id: ". $row['Sick_ID']. " - UserID: ". $row['User_ID']. "- Reason " . $row['Reason'] . "<br>";
}
} else {
echo "0 results";
}
Add the schema owner prefix to the select query. It usually happens when executing mysql queries on PHP.
Select * from data.table_name as t1 inner join data.table_name_2 as t2 .....
Better if:
Select data.t1.id, data.t2.name from data_table_name as t1 .....
How can I achieve the following using only one database query?
$query = "SELECT `email`, `name` FROM `customers`";
$result = mysqli_query($link,$customer_query);
while($row = mysqli_fetch_array($result)){
echo "<p>".$row['name']."</p>";
echo "<ul>";
$query2 = "SELECT `sku` FROM `orders` WHERE `email` = '".$row['email']."'";
$result2 = mysqli_query($link,$query2);
while($row2 = mysqli_fetch_array($result2)){
echo "<li>".$row2['sku']."</li>";
echo "<li>".$row2['cost']."</li>";
}
echo "</ul>"
}
Use INNER JOIN on email field for this:
SELECT c.name, o.sku, o.cost FROM customers c INNER JOIN orders o ON o.email = c.email
Don't forget to add MySQL INDEX on email field for performance.
But this only select customers which have orders.
If you need to select all customers (even which does not have orders) use LEFT JOIN instead. In this case sku and cost fields for users without orders will be null.
Use this picture as hint for this.
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.
i m developing a dynamic website but i have a problem with a query. I m trying to build a map dynamically by retrieving date from the database. I enclose the db structure:
countries (code, name)
data (user_id, dateaction, container)
users (user_id, country_code)
I want to display a list of the AVG container for each country, but the average value should be calculated from last action of each user and the data should be submitted the current day. In the case of non-value of "container" for any country the value is 0. I tried many queries but i couldnt achieve the target. I attach some of the queries i tried.
$query = "SELECT AVG(data.container), data.user_id, users.country_code ".
"FROM data, users ".
"WHERE data.user_id = users.user_id AND dateaction >= '".date('Y-m-d').' 00:00:00'."' AND date < '".date('Y-m-d').' 23:59:59'."'".
"GROUP BY users.country_code ";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$cid=$row['country_code'];
$queryy=mysql_query("select * FROM Countries WHERE country_code='$cid'") or die("Error Occured,plz try again1");
$rowy = mysql_fetch_array( $queryy );
$cname=$rowy['country_name'];
echo '<area title="'.strtoupper($cname).'" mc_name="'.strtoupper($cid).'"></area>'; }
Please may you help me to solve this logical problem?
$query = "SELECT a.user_id, ifnull(a.country_code, 0) as country_code, avg(a.container) ".
"FROM data a INNER JOIN ".
"(SELECT data.user_id, max(dateaction) dateaction ".
"FROM data".
"WHERE dateaction >= '".date('Y-m-d').' 00:00:00'."' AND date < '".date('Y-m-d').' 23:59:59'."'".
"GROUP BY data.user_id) b ".
"ON a.user_id = b.user_id and a.date_action = b.date_action ".
"GROUP BY a.user_id, ifnull(a.country_code, 0) "
i need to select one row where slot_left is the biggest. i tried
for ( $i=1;$i<3;$i++) {
$sql5 = "SELECT * from user u where (
select max(slot_left) from company c,user u
where c.id=u.company_id and c.id='$name'
)";
$result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
while($row=mysqli_fetch_array($result5)) {
// echo the id which the slot_left is the biggest
echo $i['slot_left'];
}
}
but still cannot. please help!
You have to use GROUP BY in your query.
And query execution in Loop is not recommended, it will decrees performance.
Try this.
$sql5 = "select c.id, max(slot_left) from company c,user u
where c.id=u.company_id and c.id='$id' GROUP by c.id";
$result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
while($row=mysqli_fetch_array($result5)) {
echo $row['slot_left'];
}
SQL can be. You select all rows from DB.
$sql5 = "select max(slot_left) AS slot_left from company c,user u where c.id=u.company_id and c.id='$name' GROUP by u.company_id";
$name variable used in query not set
Variable $i is not array. Array is $row
echo $row['slot_left'];