I had an assessment on pulling data from a table but i had to use two tables to do a calculation, i figured out a way to do it but it doesn't look good neither it would be good to keep using this way
$query = mysqli_query($connection, "SELECT * FROM metal");
$query2 = mysqli_query($connection, "SELECT * FROM conversion WHERE type = 'EUR'");
$data2 = mysqli_fetch_array($query2);
$query3 = mysqli_query($connection, "SELECT * FROM conversion WHERE type = 'USD'");
$data3 = mysqli_fetch_array($query3);
while($data = mysqli_fetch_array($query)){
echo "<tr>" . "<td>" . $data['metal'] . "</td>" . "<td>" . $data['cost'] . "</td>" . "<td>" . ($data['cost'] * $data3['amount']) . "</td>" . "</tr>";
}
This grabs cost on metal type then using another table calculates cost in Euro and USD, I don't want to use 3 querys and fetch them 3 times as it isn't computationaly effective is there a better way to do it
You'd need at least two, since you're fetching from two essentially unrelated tables
SELECT * FROM metal
SELECT * FROM conversion WHERE type IN ('EUR', 'USD')
the second query will fetch BOTH records, and then you'll just need some extra code to sort out which record is which.
Could you please post your overall table structure? In case you have a relation between these two table you could just join it.
Related
EDIT: I've just thought I could run this as one query with something like this:
SELECT * FROM clubs
JOIN match_request_archive
ON (SELECT COUNT (clubs.id) AS requests FROM match_request_archive)
I appreciate though my syntax is horrendous I've just whipped this up and will tweak it now.
I have a basic script for displaying data in a table. I've got a problem I can't solve which is I need to run one simple query to show all the data to the user. But in the last column I need to run a separate query to get the result.
Basically the first column in my table has the unique ID of a Rugby Club on the database. In a separate table on the database is a list of all requests made by clubs to players. I want to display how many requests each club has made in the last column of my script below which means running this query:
SELECT * FROM match_request_archive WHERE club_id LIKE "$row['id']"
The $row['id'] is from the PHP script below:
<?php
include 'credentials.php';
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM clubs";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc())
{
echo "
<tr>
<td>" . $row['id'] . "</td>
<td>" . $row['club_name'] . "</td>
<td>" . $row['club_captain'] . "</td>
<td>" . $row['club_captain_number'] . "</td>
<td>" . $row['club_captain_email'] . "</td>
<td>TBC</td>
</tr>
";
}
} else {
echo "<tr><td>0 results</td></tr>";
}
$conn->close();
?>
To solve this I tried embedding a second script in the echo command but it's my understanding you can't do this and in any case it did cause a fatal error. I can run this query separately and have it displayed in a different table, my problem is I need this to be all in one table. I hope that all makes sense.
Executing query in loop is bad practice because it has very slow performance.
So you should try get all data by one query if it possible:
SELECT *, COUNT(*) FROM clubs
LEFT JOIN match_request_archive
ON match_request_archive.club_id = clubs.id
GROUP BY clubs.id
I am not sure how to get the result of a Mysql SUM into your while loop THEN into a variable for displaying in an HTML table.
Firstly I pass a list of codes ie ("1111", "33311", "43433") to a HTML form textarea then implode those codes into a variable called $in. I then pass the list of codes (represented by $in) to my SQL Query.
Mysql Query
SELECT tbl1.code, tbl1.name, tbl1.cost, tble.price, tbl1.vat, sum(tbl2.onhand) as onhand
FROM tbl1
INNER JOIN tbl2 ON tbl1.code=tbl2.code
WHERE (tbl2.name='AC' OR tbl2.name='WH')
AND tbl1.code IN ($in)
NOTE The query works if I do this instead (without the SUM and brackets) BUT it still shows an empty table cell for $stock:
tbl1.vat, tbl2.onhand AS onhand
I am then attempting to pass the value of the Mysql SUM function to a variable, then display that value within a table with php echo.
PHP
$result = $mysqli->query($sql);
if ($result = mysqli_query($mysqli, $sql)) {
while($row = $result->fetch_array()) {
$code = $row['code'];
$name = $row['name'];
$cost = $row['cost'];
$price = $row['price'];
$vat = $row['vat'];
$stock = $row['onhand']; **Result from the Mysql SUM**
...........}
HTML TABLE
echo "<td>" . $name . " </td>";
echo "<td>" . $cost . " </td>";
echo "<td>" . $price . " </td>";
echo "<td>" . $vat . " </td>";
echo "<td>" . $stock . " </td>";
The Mysql query does work as I've tested it in Mac Terminal Mysql but when I attempt to replicate that in php, the $stock is not getting echoed to the table cell??
Cheers
I'm pretty sure your missing a group by in your sql. Maybe changing it to
SELECT tbl1.code, tbl1.name, tbl1.cost, tbl1.price, tbl1.vat, sum(tbl2.onhand) as onhand
FROM tbl1
INNER JOIN tbl2 ON tbl1.code=tbl2.code
WHERE (tbl2.name='AC' OR tbl2.name='WH') AND tbl1.code IN ($in)
GROUP BY tbl1.code, tbl1.name, tbl1.cost, tbl1.price, tbl1.vat
might work.
Also notice how I changed tble.price to tbl1.price since it looks like a typo
just wanna point out a fact...
hope you are aware that sum is an aggregate function...so using it without a group by clause will cause it to return a just a single row containing the sum total of all the records
SELECT tbl1.code, tbl1.name, tbl1.cost, tbl1.price, tbl1.vat, sum(tbl2.onhand) as onhand
FROM tbl1
INNER JOIN tbl2 ON tbl1.code=tbl2.code
WHERE (tbl2.name='AC' OR tbl2.name='WH') AND tbl1.code IN ($in)
GROUP BY tbl1.code, tbl1.name, tbl1.cost, tbl1.price, tbl1.vat
I have 2 tables called 0_vrs_american and 0_vrs_europe, and I need to display the rows of these tables in a single html table. So I wrote this code:
<?php
$con=mysqli_connect("localhost","aaa","bbb","my_mk7vrlist");
$result = mysqli_query($con,"SELECT 0_vrs_american.*, 0_vrs_europe.* FROM 0_vrs_american, 0_vrs_europe ORDER BY `vrs` DESC LIMIT 0 , 200");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $x . "</td>";
echo "<td>" . $row['playername'] . "</td>";
echo "<td>" . $row['contactable'] . "</td>";
echo "<td>" . $row['vrs'] . "</td>";
echo "</tr>";
$x = $x+1;
}
mysqli_close($con);
?>
I am pretty new with MySQL and so I googled about this topic and I found a syntax like the one you can see above. By the way I have no results in my page because the table is empty.
So: I must display in a HTML table the content of both sql tables, and the rows must be sorted according with the vrs (number that goes from 50000 to 99000). How could I solve my problem?
An alternative to the above is to select all the rows from those two tables as an inner select, and then order by vrs in the returned result set.
SELECT *
FROM
(
SELECT * FROM 0_vrs_american
UNION
SELECT * FROM 0_vrs_europe
) AS a
ORDER BY vrs
at first U need to define $x before the loop
then use the query like this
$result = mysqli_query($con,"SELECT 0_vrs_american.*, 0_vrs_europe.* FROM 0_vrs_american, 0_vrs_europe ORDER BY `vrs` DESC LIMIT 0 , 200") or die (__LINE__." ".mysqli_error($con));
so you will see the error and the line of the query
i just add or die (__LINE__." ".mysqli_error($con))
Separate the 2 queries and their results
merge both results into an array
sort the array as needed
output the array (generate table rows)
I have a table with two collumns (shortened), NAME and CATEGORY.
I want to output the number of distinct categorys. For an examle: Sport : 5 , Houses : 10.
I use this one:
$test = mysqli_query($con,"SELECT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
This work then I run the code in SQL Shell, but I have no clue on how to output it in PHP. I have searced Google up and down without any successfull solution.
Any help?
I want to output it in a table format.
EDIT: Here is my full code: (tablename is changed, and $con is removed)
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
while($row = mysql_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
echo "<table border='1'>";
while($row = mysqli_fetch_array($test)) {
echo "<tr>";
echo "<td>" . $row['lkategori'] . "</td>";
echo "<td>" . $row['count'] . "</td>";
echo "</tr>";
}
echo "</table>";
This will output all the categories and the count returned by the sql statement into a table. Also as a sidenote you should look into PDO.
EDIT: to make sure you do get the distinct values you should use the DISTINCT keyword in your sql statement:
$test = mysqli_query($con,"SELECT DISTINCT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
use this
while($row = mysqli_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
Thanks
Have 3 different mysql tables, my script queries the DB using JOINS to output the most recent results from each of the 3 tables. All works like it is supposed to but the way mysql databases allow for JOINS, the ORDER BY will order the results as you list the tables, resulting in the finished output not being ordered by date correctly, since the results are from 3 different MYSQL tables.
The results instead are ordered by date correctly only next to the other results form the same table. See the script and results below: (I am limit 1 for the output for simplicity)
$username = $_SESSION['username'];
$result = $mysqli->query("
SELECT
accounts.account_name,
cases.case_subject,
tasks.task_title,
accounts.accounts_date_last_edited,
cases.cases_date_last_edited,
tasks.tasks_date_last_edited
FROM
accounts,
cases,
tasks
WHERE
accounts.username = cases.username
AND cases.username = tasks.username
ORDER BY
accounts.accounts_date_last_edited DESC,
cases.cases_date_last_edited DESC,
tasks.tasks_date_last_edited DESC
LIMIT 1
");
if (!$result) { echo "Error Result5: " . $mysqli->error; } else {
echo "<table>";
echo "<tr><th>Item</th><th>Date</th></tr>";
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['account_name'] . "</td><br>";
echo "<td>" . $row['accounts_date_last_edited'] . "</td><br>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['case_subject'] . "</td><br>";
echo "<td>" . $row['cases_date_last_edited'] . "</td><br>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['task_title'] . "</td><br>";
echo "<td>" . $row['tasks_date_last_edited'] . "</td><br>";
echo "</tr>";
}
echo "</table>";
The Results are below: they will list 1 item from each table listed above. Again I am trying to sort by the date_last_edited regardless of which table the values are from.
Item Date
Shorley Homes 2013-11-02 04:02:34
Techical Testing Case Open 2013-11-03 07:17:36
Icons 2013-11-03 07:28:02
If I read correctly (and I'm not sure of that) your
...sort by the date_last_edited regardless of which table the values are from...
then you might want to use UNION instead of JOIN
SELECT account_name item, accounts_date_last_edited date
FROM accounts
UNION ALL
SELECT case_subject, cases_date_last_edited
FROM cases
UNION ALL
SELECT task_title, tasks_date_last_edited
FROM tasks
ORDER BY date DESC
Here is SQLFiddle demo