Mysql Query Getting Item as ID in 2 different tables - php

Im sorry for my bad english but this is the best i can.
I am trying to make a script that get's the item values of one line in my
for this example i'll be using the row with ID 2.
The first query is working correctly and getting the 2 values of 1items and 2items and deletes the ; that comes with it.
But the second part seems a little bit harder and i can't solve it.
The query is getting id, base_item from the table
The last 2 Outputs marked red are the one's that are matching 1items & 2items
I'm trying to let the if statement filter the $item1 as id in the item table and output the baseitem of the found row
same goes for item2
I'm using MySQL & MySQLi because this cms doesnt support newer versions of PHP yet.
<?php
$query = "SELECT * FROM logs_client_trade ORDER by id DESC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$item1 = rtrim($row['1items'],"; ");
$item2 = rtrim($row['2items'],"; ");
echo("<tr>");
echo("<td>" . $row['id'] . "</td>");
echo("<td>" . $row['1id'] . "</td>");
echo("<td>" . $row['2id'] . "</td>");
$userinfo = "SELECT id, base_item FROM items LIMIT 1";
$result2 = mysql_query($userinfo) or die(mysql_error());
while($row2 = mysql_fetch_assoc($result2)){
echo("<td>");
if($row2['id'] == $item1){ echo $row2['baseitem']; } else echo "Not available";
echo ("</td>");
echo("<td>");
if($row2['id'] == $item1){ echo $row2['baseitem']; } else echo "Not available";
echo ("</td>");
}
$tradetime = $row['timestamp'];
$date = date("d M Y - H:i:s", $tradetime);
echo("<td>$date</td></tr>");
}
?>

You forgot the while loop for the second query:
$userinfo = mysql_query("SELECT id, base_item FROM items");
while($get2 = $userinfo->fetch_assoc()) {
$baseid = $get2['id'];
$baseitem = $get2['baseitem'];
echo("<tr>");
[...]
}
In addition to that, your code is a mess. In the second loop you are still listing the rows from the logs table... I suggest you to review carefully your code, being careful on how you are using the different $row and $get2 arrays.

You can use a JOIN to get all of the info with one SQL statement:
SELECT *
FROM `logs_client_trade` a
LEFT JOIN `items` b
ON REPLACE(a.`1items`,';','') = b.`id`
LEFT JOIN `items` c
ON REPLACE(a.`2items`,';','') = c.`id`
ORDER by a.`id` DESC
UPDATE:
Here's the PHP code that will run the query and output the table rows. I've specified the column names based on the code in the original question.
<?php
$query = "SELECT
a.`id`,
a.`1id`,
a.`2id`,
a.`1items`,
a.`1items`,
IFNULL(b.`baseitem`,'Not Available') as `baseitem1`,
IFNULL(c.`baseitem`,'Not Available') as `baseitem2`,
DATE_FORMAT(a.`timestamp`,'%d %m %Y - %H:%i:%s') as `tradetime`
FROM `logs_client_trade` a
LEFT JOIN `items` b
ON REPLACE(a.`1items`,';','') = b.`id`
LEFT JOIN `items` c
ON REPLACE(a.`2items`,';','') = c.`id`
ORDER by a.`id` DESC
";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$item1 = rtrim($row['1items'],"; ");
$item2 = rtrim($row['2items'],"; ");
echo "<tr>\r\n";
echo " <td>" . $row['id'] . "</td>\r\n";
echo " <td>" . $row['1id'] . "</td>\r\n";
echo " <td>" . $row['2id'] . "</td>\r\n";
echo " <td>" . $row['baseitem1'] . "</td>\r\n";
echo " <td>" . $row['baseitem2'] . "</td>\r\n";
echo " <td>" . $row['tradetime'] . "</td>\r\n";
echo("</tr>\r\n");
}
?>

Related

Group by with rollup does not change column name to TOTAL when using IFNULL or COALESCE

How do i replace column name 'product_name' to 'TOTAL' and other column name 'inv_date' to 'TOTAL'. Tried with as below but to no avail.
$query = "SELECT IFNULL(pm.product_name,'TOTAL') product_name,IFNULL(pt.inv_date,'TOTAL') inv_date, SUM(pt.qty) as total_qty,(SUM(pt.amount)/SUM(pt.qty)) as avg_rate, SUM(pt.amount) as total_amount1,SUM(pt.tcs) as total_tcs, SUM(pt.total_amount) as total_amount_net,
am.acc_name,pgm.product_group,psgm.sub_product_group,pim.pre_insp_name, ptm.purch_type_name, pt.* FROM purch_tble pt LEFT JOIN product_master pm ON pm.product_id = pt.product_id LEFT JOIN acc_master am ON am.acc_id = pt.acc_id LEFT JOIN purch_type_master
ptm ON ptm.purch_type_id = pt.purch_type_id LEFT JOIN prod_group_master pgm ON pgm.prod_group_id = pm.prod_group_id LEFT JOIN prod_sub_group_master psgm ON psgm.prod_sub_group_id = pm.prod_sub_group_id LEFT JOIN pre_insp_master pim ON pim.pre_insp_id
= pt.pre_insp_id $where GROUP BY pt.product_id, DATE_FORMAT(pt.inv_date,'%Y-%m') WITH ROLLUP"; $retval = mysql_query($query); $num_row = mysql_num_rows($retval); echo mysql_error(); if($num_row >= 1){ while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{ echo "
<tr>"; echo "
<td>" . date('m-Y',strtotime($row['inv_date']))."</td>"; echo "
<td>" . $row['product_name']."</td>"; echo "
<td>" . round($row['total_qty'])."</td>"; echo "
<td>" . round($row['avg_rate'],2)."</td>"; echo "
<td>" . round($row['total_tcs'])."</td>"; echo "
<td>" . round($row['total_amount1'])."</td>"; echo "
<td>" . round($row['total_amount_net'])."</td>"; echo "</tr>"; } // while loop finishes } // if statement finishes
I also tried with following but to no avail.
COALESCE(pm.product_name,'TOTAL') product_name,
COALESCE(pt.inv_date,'TOTAL') inv_date,
LASTLY, I also tried with following but to no avail.
IF(GROUPING(pm.product_name),'TOTAL',pm.product_name) product_name,
IF(GROUPING(pt.inv_date),'TOTAL',pt.inv_date) inv_date,
The picture is self explanatory.
I am stuck don't where am I going wrong.
Hope I have been able to express question clearly.

SUM function generates error in SQL query

I'm trying to get information about an SQL table via a php script however, whenever I add a SUM function I get the following error "Notice: Trying to get property 'num_rows' of non-object"
I don't know what's going on but if anyone can please explain/point me in the right direction as to how to fix this problem that would be greatly appreciated
Here's the 'broken' code
<?php
require("connect.php");
$inNo = $_POST["inNo"];
$sql = "SELECT invoice.invoice_no, invoice.date, invoice.cust_id, invoice.emp_id, invoice_line.prod_id,
invoice_line.qty, product.cost_price, (product.cost_price * invoice_line.qty) AS `multi`,
customer.first_name AS `customer_fname`, customer.last_name AS `customer_lname`,
employee.first_name AS `emp_fname`, employee.last_name AS `emp_lname`,
product.name AS `proname`
FROM invoice INNER JOIN invoice_line ON invoice.invoice_no = invoice_line.invoice_no
INNER JOIN product ON invoice_line.prod_id = product.id
INNER JOIN customer ON invoice.cust_id = customer.id
INNER JOIN employee ON invoice.emp_id = employee.id, SUM(multi) AS `invoicetotal`
WHERE cust_id = '" . $inNo . "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//open table
echo '<table class="table table-striped" id="outTable">';
echo "<tr><th>Product</th><th>Qty</th><th>Price</th><th>Total cost</th></tr>";
// output data of each row
$ctr = 0;
while($row = $result->fetch_assoc()) {
if ($ctr == 0)
{
echo "<h1>Invoice Number: " . $row["invoice_no"]. "</h1>";
echo "<p>Customer: " . $row["customer_fname"]. " " . $row["customer_lname"]."</p>";
echo "<p>Employee: " . $row["emp_fname"]. " " . $row["emp_lname"]. "</p>";
echo "<p>Date: " . $row["date"]. "</p>";
}
echo "
<tr>
<td>" . $row["proname"]. "</td>
<td>" . $row["qty"]. "</td>
<td>" . $row["cost_price"]. "</td>
<td>" . $row["multi"]. "</td>
</tr>";
$ctr++;
}
} else {
echo "0 results";
}
$conn->close();
?>
You need to insert the SUM() in the SELECT part above FROM:
SELECT
invoice.invoice_no,
invoice.date,
invoice.cust_id,
invoice.emp_id,
invoice_line.prod_id,
invoice_line.qty,
product.cost_price,
(product.cost_price * invoice_line.qty) AS `multi`,
customer.first_name AS `customer_fname`,
customer.last_name AS `customer_lname`,
employee.first_name AS `emp_fname`,
employee.last_name AS `emp_lname`,
product.name AS `proname`,
SUM(multi) AS `invoicetotal`
FROM invoice
INNER JOIN invoice_line
ON invoice.invoice_no = invoice_line.invoice_no
INNER JOIN product
ON invoice_line.prod_id = product.id
INNER JOIN customer
ON invoice.cust_id = customer.id
INNER JOIN employee
ON invoice.emp_id = employee.id` WHERE cust_id = 99
BTW, it's wise to format code - SQL code too - fine.

php mysql using nested query

I am trying to find if two runners have ever ran in the same race. The two runners are Peter Smith and Diane Peters.
$resultRaceType = mysqli_query($db,"SELECT DISTINCT date,time FROM results where runner = 'Peter, Smith' ");
while($row = mysqli_fetch_array( $resultRaceType ))
{
$resultRaceType1 = mysqli_query($db,"SELECT * FROM results where date = ' " . $row['date'] . " ' and time = ' " . $row['time'] . " ' and runner = 'Diane, Peters'");
while($row1 = mysqli_fetch_array( $resultRaceType1 ))
{
echo "<tr >";
echo "<td>";
echo $row1['date'];
echo " - " . $row1['time'];
echo "</td>";
echo "<tr>";
}
}
The above code works, but only if I limit the first select to LIMIT 50. So I can see that it is timing out. My table has over 100K rows. I know I am doing something wrong but cant see what it is.
Thanks for any help you guy's can give me.
Try:
SELECT a.date, a.time FROM results a
JOIN results b ON (a.date = b.date AND a.time = b.time)
WHERE a.runner='Peter, Smith' AND b.runner='Diane, Peters';

Multiple While Loops within a While Loop?

Total newbie trying to learn... thanks for all the help so far!
UPDATE - updated code below - Thanks Phill
I'm now trying to get the relevant horse information from a table horses which I can join to race_form with the horse_name field. I want to then display the information for each horse in the race below the while($racecard) info. Does this make it a bit clearer?
I thought I could just do another query and then a while loop with mysql_fetch_array below the one I have already and that would display it and then move onto the next race, but that apparently doesn't work...?!
I'm wondering if you can run 2 while loops after each other inside a while loop? I am working on a horse racing formguide - I can display each race list, but underneath I want to display individual horse details on each horse in the race. Anyway if you look at this page you can see what I'm trying to do:
http://tasmanianracing.com/superform/formguide.php?meetingID=21042011LAUN&Submit=View+Form
Problem is, any time I put a second while loop after the race list, it won't show up. I'm trying to run a query to get the horse details from my horse table and then run a while for each horse in the race, but nothing shows up.
I hope this is clear enough ... my snippet of code is below - please let me know if I've missed out something important:
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $row['race_number'] . " at " . $row['start_time'] . " " . $row['class'] . " over " . $row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $row['raceID'] . "')");
while($row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $row['number'] . "</td><td>" . $row['past10'] . "</td><td>" . $row['horse_name'] . "</td></tr>";
}
echo "</table><br>";
echo "<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
echo "</table>";
You'll probably need to change the names of some of the $row variables, they may interfere with each other.
For example:
while($row_races = mysql_fetch_array($totalraces)){
while($row_details = mysql_fetch_array($racedetails)){
while($row_card = mysql_fetch_array($racecard)){
I think you can get rid of one of your queries:
The first query gets the number of races by selecting a COUNT, This returns one record with the count value.
// This returns one record with the count
$total_races = "SELECT COUNT(race_number) AS totalraces
FROM race_info WHERE meetingID = ('".$safemeetingID."') ";
Next you iterate over the the same records as the rows returned for the race details are the same as the count.
// This looks to return the record(s) with the race details
$race_details = "SELECT * FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')";
I think you can just use this to get the desired results: (I agree to rename the $row variable(s) to something descriptive for each while loop)
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($details_row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $details_row['race_number'] . " at " . $details_row['start_time'] . " " . $details_row['class'] . " over " . $details_row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $details_row['raceID'] . "')");
while($rc_row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $rc_row['number'] . "</td><td>" . $rc_row['past10'] . "</td><td>" . $rc_row['horse_name'] . "</td></tr>";
}
echo "</table><br>";
echo "Testing<br>Testing<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
NOT TESTED/PSEUDO CODE
"SELECT *
FROM horses AS h,
INNER JOIN race_info AS ri ON race_form.raceID = race_info.raceID
WHERE horse_name IN (
SELECT horse_name
FROM race_form AS srf
WHERE h.horse_name = srf.horse_name
)
AND race_form.raceID = ('" . $details_row['raceID'] . "')"
The idea is to join the two queries into one, I know this is not the correct syntax but it might give you an idea on how to go about it.
Or you can do another query while loop for the horse names
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($details_row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $details_row['race_number'] . " at " . $details_row['start_time'] . " " . $details_row['class'] . " over " . $details_row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $details_row['raceID'] . "')");
while($rc_row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $rc_row['number'] . "</td><td>" . $rc_row['past10'] . "</td><td>" . $rc_row['horse_name'] . "</td></tr>";
$horses = mysql_query("SELECT *
FROM horses
WHERE horse_name = ('" . $rc_row['horse_name'] . "')");
while($horse_row = mysql_fetch_array($horses))
{
// echo horse details here
}
}
echo "</table><br>";
echo "Testing<br>Testing<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
I theory you could and in practice you can, but a while in a while in a for in a while seems a little bit over the top...
I'm sure we can help you make it more efficient if you explain what it is you're trying to do.

PHP and Multiple DB Selects

I've got two tables from which I need to extract information, but the data from the second table depends on the information I get from the first one. Is there an easy way to handle this?
<?php
mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('stadium') or die(mysql_error());
$result = mysql_query("SELECT * FROM events");
$result2 = mysql_query("SELECT name FROM competitions WHERE id='$row[competition_id]' ");
while($row = mysql_fetch_array($result)) {
echo "<tr id=\"" . $row['id'] . "\"> \n<td>" . $row['name'] . "</td>";
echo "<td>" . $row['competition_id'] . "</td>";
echo "<td>" . $row['date'] . "</td></tr>";
}
?>
Use a JOIN.
SELECT e.*, c.name as competition_name FROM events e LEFT JOIN competitions c on c.id = e.competition_id

Categories