running 2 SQL select statements - php

I am trying to run 2 SQL Select queries to retrieve data from 2 different tables and then echo the fields from both tables. The code I am trying doesn't seem to work, any help would be appreciated.
$ModelID = $_GET['model_id'];
$result = mysqli_query($con, "SELECT RegNumber, Colour FROM Car WHERE ModelID = '$ModelID'
UNION ALL
SELECT CarModel, CarMake, CostPerDay FROM Model WHERE ModelID = '$ModelID'");
while($row = $result->fetch_assoc())
{
echo $row["CarModel"];
echo $row["CarMake"];
echo $row["CostPerDay"];
echo $row["RegNumber"];
echo " - " .$row["Colour"];
}

You can change request :
SELECT c.RegNumber, c.Colour , m.CarModel, m.CarMake, m.CostPerDay FROM Car c INNER JOIN Model m ON m.ModelID=c.ModelID WHERE c.ModelID = '$ModelID'

try with LEFT JOIN
$result = mysqli_query($con,
"SELECT c.RegNumber, c.Colour, m.CarModel, m.CarMake, m.CostPerDay
FROM Car AS c
LEFT JOIN Model as m ON c.ModelID = m.ModelID
WHERE c.ModelID = '".$ModelID."'"
);

Related

How can i join Three tables and Create a table using Select statement

I have three table in Mysql database MIITEM, DEMAND, MIILOC tables i want to select field from these three table display as a table .
i tried this but the join doesnt work for me
$sql = "SELECT demand.itemid, demand.qty, MIITEM.descr FROM demand
INNER JOIN MIITEM ON MIITEM.itemId = demand.itemid
WHERE demand.itemid = MIITEM.itemId
ORDER BY demand.itemid DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["itemid"]. " - demand: " . $row["qty"]. " - sales: " . $row["sales"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
select dt.*, three_table.* from (
SELECT demand.itemid, demand.qty, MIITEM.descr FROM demand
INNER JOIN MIITEM ON MIITEM.itemId = demand.itemid
ORDER BY demand.itemid DESC) as dt inner join three_table on (dt.itemid = three_table.itemid)
you create the first select inner join 2 table wrap it with new select and inner join with the last table,
i didn't check the code... also you dont need the "where" you already doing inner join...

php mysql query dynamic Group by value

Hi I have a mysql query that I want to get results by different order by values.
here is the code.
$strQuery =
"SELECT
category.short_description AS category,
asset.asset_code AS code,
asset_model_number.short_description AS model,
asset_custom_field_helper.cfv_1 AS mnfserial,
asset_custom_field_helper.cfv_6 AS proctype,
asset_custom_field_helper.cfv_7 AS hdd,
asset_custom_field_helper.cfv_8 AS type,
asset_custom_field_helper.cfv_9 AS cond,
asset_custom_field_helper.cfv_10 AS drive,
asset_custom_field_helper.cfv_12 AS os,
asset_custom_field_helper.cfv_13 AS cpu,
asset_custom_field_helper.cfv_14 AS ram,
COUNT(*) AS total
FROM
asset_transaction
LEFT JOIN asset
ON asset_transaction.asset_id = asset.asset_id
LEFT JOIN asset_model
ON asset.asset_model_id = asset_model.asset_model_id
LEFT JOIN asset_model_number
ON asset.asset_model_number_id = asset_model_number.asset_model_number_id
LEFT JOIN asset_custom_field_helper
ON asset.asset_id = asset_custom_field_helper.asset_id
LEFT JOIN user_account
ON asset.created_by = user_account.user_account_id
LEFT JOIN category
ON asset_model.category_id = category.category_id
WHERE asset_transaction.transaction_id = ($txnid)
GROUP BY model";
$objDatabase = QApplication::$Database[1];
// Perform the Query
$objDbResult = $objDatabase->Query($strQuery);
This section I want to get results group by model
echo "<h3>Total Model No<br></h3><strong>";
while ($mixRow = $objDbResult->FetchArray()) {
echo $mixRow['model']. " = " .$mixRow['total'];
echo "<br><strong>";
}
Below section I want the results group by type
echo "<h3>Total Products<br></h3><strong>";
echo "<br>";
while ($row = $objDbResult->FetchArray()) {
echo $row['type']. " = " .$row['total'];
echo "<br><strong>";
I want to avoid writing the sql query each time, instead want to use this query and define my order by value somewhere. How can I do this?
I hope this helps you :)
function getQuery( $order_by_string )
{
return $query = 'Your query .... ORDER BY '.$order_by_string
}
$query = getQuery("something");
You should consider making a query builder class, so you can create queries more freely.
Anyhow, to just set the group by, you can create the function getQueryGroupBy($query,$type) as following:
function getQueryGroupBy($query, $type) {
return $query . 'GROUP BY ' . $type;
}
Your query would be:
$strQuery = "SELECT
category.short_description AS category,
asset.asset_code AS code,
asset_model_number.short_description AS model,
asset_custom_field_helper.cfv_1 AS mnfserial,
asset_custom_field_helper.cfv_6 AS proctype,
asset_custom_field_helper.cfv_7 AS hdd,
asset_custom_field_helper.cfv_8 AS type,
asset_custom_field_helper.cfv_9 AS cond,
asset_custom_field_helper.cfv_10 AS drive,
asset_custom_field_helper.cfv_12 AS os,
asset_custom_field_helper.cfv_13 AS cpu,
asset_custom_field_helper.cfv_14 AS ram,
COUNT(*) AS total
FROM
asset_transaction
LEFT JOIN asset
ON asset_transaction.asset_id = asset.asset_id
LEFT JOIN asset_model
ON asset.asset_model_id = asset_model.asset_model_id
LEFT JOIN asset_model_number
ON asset.asset_model_number_id = asset_model_number.asset_model_number_id
LEFT JOIN asset_custom_field_helper
ON asset.asset_id = asset_custom_field_helper.asset_id
LEFT JOIN user_account
ON asset.created_by = user_account.user_account_id
LEFT JOIN category
ON asset_model.category_id = category.category_id
WHERE
asset_transaction.transaction_id = ($txnid)";
You would then call the function like this:
$query = $this->setGroupBy($strQuery, 'model');
or
$query = $this->setGroupBy($strQuery, 'type');
EDIT
So you would probably end up with this:
$baseQuery =
"SELECT
category.short_description AS category,
asset.asset_code AS code,
asset_model_number.short_description AS model,
asset_custom_field_helper.cfv_1 AS mnfserial,
asset_custom_field_helper.cfv_6 AS proctype,
asset_custom_field_helper.cfv_7 AS hdd,
asset_custom_field_helper.cfv_8 AS type,
asset_custom_field_helper.cfv_9 AS cond,
asset_custom_field_helper.cfv_10 AS drive,
asset_custom_field_helper.cfv_12 AS os,
asset_custom_field_helper.cfv_13 AS cpu,
asset_custom_field_helper.cfv_14 AS ram,
COUNT(*) AS total
FROM
asset_transaction
LEFT JOIN asset
ON asset_transaction.asset_id = asset.asset_id
LEFT JOIN asset_model
ON asset.asset_model_id = asset_model.asset_model_id
LEFT JOIN asset_model_number
ON asset.asset_model_number_id = asset_model_number.asset_model_number_id
LEFT JOIN asset_custom_field_helper
ON asset.asset_id = asset_custom_field_helper.asset_id
LEFT JOIN user_account
ON asset.created_by = user_account.user_account_id
LEFT JOIN category
ON asset_model.category_id = category.category_id
WHERE asset_transaction.transaction_id = ($txnid)";
$objDatabase = QApplication::$Database[1];
// Create the query
$modelQuery = getQueryGroupBy($baseQuery, 'model');
// Perform the Query
$objDbResultByModel = $objDatabase->Query($modelQuery);
echo "<h3>Total Model No<br></h3><strong>";
while ($mixRow = $objDbResultByModel->FetchArray()) {
echo $mixRow['model']. " = " .$mixRow['total'];
echo "<br><strong>";
}
// Create the query
$typeQuery = getQueryGroupBy($baseQuery, 'type');
// Perform the Query
$objDbResultByType = $objDatabase->Query($typeQuery);
echo "<h3>Total Products<br></h3><strong>";
echo "<br>";
while ($row = $objDbResultByType->FetchArray()) {
echo $row['type']. " = " .$row['total'];
echo "<br><strong>";
}
function getQueryGroupBy($query, $type) {
return $query . ' GROUP BY ' . $type;
}

Using PHP to get data from multiple database tables

I am trying to query five tables. I am able to query one of the tables with
$query = "SELECT * FROM Stats_player WHERE player='$user'";
However, when I try to query another table with
$query = "SELECT * FROM Stats_player, Stats_block WHERE player='$user'";
the website breaks. Here is the code I am using to echo the data on the screen
<?php
if ($result = $mysqli->query($query)) {
echo "<img src=\"https://minotar.net/avatar/{$user}/100\"><h1>{$user}</h1><br/>";
while ($row = $result->fetch_assoc()) {
//variables
$play_time = $row['playtime']/3600;
$play_time = round($play_time, 1);
$xpgained = $row['xpgained'];
$damagetaken = $row['damagetaken'];
$toolsbroken = $row['toolsbroken'];
$itemscrafted = $row['itemscrafted'];
$itemseaten = $row['omnomnom'];
$commandsused = $row['commandsdone'];
$teleports = $row['teleports'];
$itemspickedup = $row['itempickups'];
$itemsdroped = $row['itemdrops'];
$lastseen = date("F j, Y ", strtotime($row['lastjoin']));
//end of variables
echo "<p>Time on Server: {$play_time} HRS</p>";
echo "<p>Last Seen: {$lastseen}";
echo "<p>Commands Used: {$commandsused}";
echo "<p>XP Gained: {$xpgained}";
echo "<p>Blocks broken: {$row['blockID']}"; //this is data from the table Stats_block
}
$result->free();
}
$mysqli->close();
?>
Any ideas on how I might do this?
Table structor of Stats_player:
| counter | player | Playtime |
Stats_block is:
| counter | player | blockID |
$query = "SELECT * FROM Stats_player, Stats_block WHERE player='$user'"
That's very likely wrong. You should use a JOIN operator.
Here, you are just doing a cartesian products of the two tables, that's hardly what you want. And that may overrun your resource (memory etc.) if the tables have a lot of rows.
Something like
$query = "SELECT * FROM Stats_player p, Stats_block b
WHERE p.block_id = b.id AND p.player='$user'"
or
$query = "SELECT * FROM Stats_player p INNER JOIN Stats_block b ON p.block_id = b.id
WHERE p.player='$user'"
or maybe LEFT OUTER JOIN...
The exact query will depend on your schema.
Without seeing the structure of both tables, something like this could work.
SELECT columnList
FROM Stats_player a
LEFT JOIN Stats_block b ON b.player = a.player
WHERE a.player = '$user'
Have you tried something like this:
SELECT
table1.field1, table1.field2, table2.field1, table2.field2
FROM
table1, table2
WHERE
table1.field1 = " " and table2.field1 = " ";

total sum of a row

I have this query which gives me the transactions for a user, and the output is a table with the information. There is this row named basket_value which contains some numbers, and I need to get the sum of those numbers. Could you please help me?
$query3 = 'SELECT users.first_name,users.last_name,users.phone,
retailer.date, SUM(retailer.basket_value),
retailer.time,retailer.location,retailer.type_of_payment
FROM users ,retailer
WHERE users.user_id="'.$id_user.'"
AND users.user_id=retailer.user_id GROUP BY users.user_id';
$result3 = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result3)) {
echo "Total ". $row['user_id']. " = $". $row['SUM(basket_value)'];
echo "<br />";
}
I suppose that also your query have some problem and suppose that you have an id to retrieve users, I would do in that way
$query3 = 'SELECT users.user_id,users.first_name,users.last_name,
users.phone, retailer.date,
SUM(retailer.basket_value) as total_sum,
retailer.time,retailer.location,retailer.type_of_payment
FROM users ,retailer WHERE users.user_id="'.$id_user.'"
AND users.user_id=retailer.user_id
GROUP BY users.user_id,users.first_name,users.last_name,
users.phone, retailer.date,retailer.time,retailer.location,
retailer.type_of_payment '
$result = $mysqli->query($query3);
Now if you want the sum for each user:
while ($row = $result->fetch_row()) {
echo "Player: ".$row['user_id']." total: ".$row['total_sum'];
}
If you want the WHOLE GLOBAL sum, you have to way:
Modify your query in that way:
SELECT SUM(retailer.basket_value) as total_sum
FROM retailer
Sum into while loop like: $total += $row['total_sum'];
You're missing a GROUP BY on your query. You most likely want to add GROUP BY users.user_id
Try this query:
SELECT u.first_name, u.last_name, u.phone, SUM(r.basket_value) as total_sum
FROM users u
JOIN retailers r
ON u.user_id = r.user_id
WHERE u.user_id="'.$id_user.'"
GROUP BY u.user_id
You can omit all other columns in the select list and only have the sum() aggregate run on the set to avoid the GROUP BY clause.
$query3 = 'SELECT SUM(retailer.basket_value) as total_sum
FROM users ,retailer WHERE users.user_id="'.$id_user.'"
AND users.user_id=retailer.user_id';

Join MySQL Table then filter result as column name

here is my code i am using to fetch mysql result from 4 different tables
SELECT DISTINCT c.title as CourseTitle, t.title as TopicTitle, l.title as LessonTitle, r.title as ResourceTitle, r.location, r.type, r.duration
FROM j17_lessons l, j17_topics t, j17_courses c, j17_resources r
WHERE
CONCAT(c.title, t.title, l.title, r.title, r.type, r.location) LIKE '%Fatih%'
AND c.id = t.course_id
AND l.topic_id = t.id
AND r.lesson_id = l.id
ORDER BY c.title, t.id, l.id, r.id;
Here is screen shot of my fetch result
http://i40.tinypic.com/2v1w0ib.png
Now what i need is to create a HTML Tables for each 'CourseTitle' in database.
Using SQL statement and PHP Code i can get result for first query but i need a second query to split table foreach 'CourseTitle'
/* connect to the db */
$connection = mysql_connect('localhost','root','123');
mysql_select_db('alhudapk',$connection);
/* show tables */
$result = mysql_query('SELECT DISTINCT c.title as CourseTitle, t.title as TopicTitle, l.title as LessonTitle, r.title as ResourceTitle, r.location, r.type, r.duration
FROM j17_lessons l, j17_topics t, j17_courses c, j17_resources r
WHERE
CONCAT(c.title, t.title, l.title, r.title, r.type, r.location) LIKE '%Taleem%'
AND c.id = t.course_id
AND l.topic_id = t.id
AND r.lesson_id = l.id
ORDER BY c.title, t.id, l.id, r.id',$connection) or die('cannot show tables');
while($tableName = mysql_fetch_row($result)) {
$table = $tableName[0];
echo '<h3>',$table,'</h3>';
$result2 = mysql_query('SELECT '.$table . 'AS' .$table);
if(mysql_num_rows($result2)) {
Please guide me to build a correct and better code
What I would do is put the database results into a big array structure with the data arranged in the same sort of order it should be printed out. This makes maintaining the code a bit easier.
// run the query as you did in the question
$courses = array();
// use mysql_fetch_assoc as it makes the code clearer
while($row = mysql_fetch_assoc($result)) {
$ct = $row['CourseTitle'];
// Found a new Course Title? If so create an array to put the data rows in
if(!isset($courses[$ct]))
$courses[$ct] = array();
// add this row to the end of its course array
$courses[$ct][] = $row;
}
// now print the results out
foreach($courses as $title =>$course) {
echo "<h3>$title</h3>";
echo "<table>";
foreach($course as $line) {
echo "<tr><td>" . $line['TopicTitle'] . "</td><td>"
. $line['LessonTitle'] . "</td></tr>";
echo "</table>";
}
The code above is only printing out the first 2 columns
, but if you can get it to work you should be able to add the rest quite easily.
add:
GROUP BY c.title
to the end of your SQL statement.

Categories