Running mysql query on php multiple times but with different condition - php

screenshot: http://i.stack.imgur.com/mX29j.png
im currently making an invoice receipt. the numbers you see on the image, 4600 and 33, are the retrieved values from the checklist from the first page. As you can see, it only lists ONE charge where as it should be two.
this is the part of the code:
$procedures = $_SESSION['receipt'];
foreach($procedures as $key=>$procedureno)
{
$query = "select * from `charges` where `procedure_no` = $procedureno";
echo $procedureno;
$result2=mysql_query($query,$dbh1);
if(mysql_num_rows($result2) > 0 ){
while($row = mysql_fetch_array($result2)){
echo '
<tr>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>';
echo '</tr>';
}
}
}
I want this query $query = "select * from charges where procedure_no = $procedureno"; to be executed several times depending on how many the $procedureno is.

MySQL understands lists. Try this:
SELECT * FROM charges WHERE procedure_no IN (1, 5, 33, 78)

Create a method and pass the condition as a parameter.
Inside that method put your FOR cycle.

Related

Sorting PHP Results of a query on two fields

I'm just starting to learn php. Everything I've researched references an array for sorting but I can't figure out how to make that work in this situation since one of my fields is constantly changing so I can't create a fixed array. Remember, I'm a noob so please explain in detail.
I would like to sort based on two fields how the results are displayed.
The first field on which to sort should be based on "SortOrder" as it correlates to the "TaskSubType" field (Displayed as Ticket Type on forms. TaskSubType has the following values assigned and would work in an array:
MSP = 1
DEDICATED = 2
REMOTE SUPPORT = 3
EXPEDITED = 4
EXPEDITED - $25 = 4
STANDARD = 5
STANDARD - $25 = 5
So if the Ticket Type (TaskSubType) was selected as "Dedicated" then it would be sorted as "2" and if "Standard - $25" was selected as the Ticket Type (TaskSubType) then it would be sorted as "5".
The second field on which I want to sort is the Ticket Number (TicketNumber) field. The value in this field is constantly changing since we have new tickets created every day so I don't know how to sort on this field with an array.
Main Goal: I want to sort the results by Ticket Type according to the numeric value we have assigned to each type which is our repair priority and then sort within all the "Dedicated" or "Standard" to work each ticket in that group in the order it was created (each new ticket counts up by one).
The code below is what I have working up to this point and the weblink below shows how my results are currently displaying:
Webpage where results are shown:
https://fireytech.com/FireytechDatabase/hello.php
Code:
<?php
require '../../db_php/dbconnection.php';
$sql = "SELECT * FROM
Tickets
Left JOIN
Clients
ON Tickets.CustomerNumber=Clients.CustomerNumber
JOIN Contacts
ON Contacts.ContactID=Clients.CustomerNumber
JOIN Equipment
ON Equipment.ContactID=Clients.CustomerNumber
WHERE Equipment.PRINT = '-1' AND Contacts.DispatchContact = '-1' AND TicketStatus = 'Active' AND NOT TicketSubStatus = 'CUSTOMER PICKUP' AND NOT TaskSubType = 'ON-SITE'
";
$result = $conn->query($sql);
echo"<table border='1'>";
echo "<tr><td>Ticket Type</td><td>Ticket Number</td><td>Date Received</td><td>Last Edited</td><td>Last Name</td><td>Followup By</td><td>Sub Status</td><td>Repair Type</td><tr>";
if ($result->num_rows > 0){
while($row = $result->fetch_assoc() ){
$dr= date("m/d/Y", strtotime($row['DateReceived']));
$dl= date("m/d/Y", strtotime($row['DateLastEdited']));
echo "<tr><td>{$row['TaskSubType']}</td><td>{$row['TicketNumber']}</td><td>{$dr}</td><td>{$dl}</td><td>{$row['ContactLast']}</td><td>{$row['FollowupBy']}</td><td>{$row['TicketSubStatus']}</td><td>{$row['ItemType']}</td></tr>";
}
} else {
echo "0 records";
}
echo"</table>";
$conn->close();
?>
Murosadatul gave me the clarity I needed. I had tried the ORDER BY command but didn't realize I need to put it at the end of my SQL query. Below in bold is where I placed it in my code so it worked if anyone else runs into the same problem:
$sql = "SELECT * FROM
Tickets
Left JOIN
Clients
ON Tickets.CustomerNumber=Clients.CustomerNumber
JOIN Contacts
ON Contacts.ContactID=Clients.CustomerNumber
JOIN Equipment
ON Equipment.ContactID=Clients.CustomerNumber
WHERE Equipment.PRINT = '-1' AND Contacts.DispatchContact = '-1' AND TicketStatus = 'Active' AND NOT TicketSubStatus = 'CUSTOMER PICKUP' AND NOT TaskSubType = 'ON-SITE'
->->->->->->-> ORDER BY SortOrder, TicketNumber
"
;
$result = $conn->query($sql);

How to get specific data from table1, use it in table2

I'm trying to get specific rows in table 1 (stellingen). I want to store these rows to specify the rows im interested in for the second table (stelling). So lets say table 1 has 5 rows where stelling ID matches REGIOID = 5. These IDS from stelling ID I want to use to fetch the data from the second table. see the code to see what I tried. I'm not managing to find a way in order too make this happen.
So maybe too be clearer because people always say im not clear:
There are two tables. they both have a matching column. Im trying to tell the second table I want data but only if it matches the data of the first table. Like a branch of a tree. Then, I want to output some data that's in the second table.
I've tried something like this before:
SELECT
*
FROM
table2
LEFT JOIN
table1 ON
table1.ID = table2.table1_id
I've tried to create a while loop to get the data before(after the first if statement and the last += was for the variable $amountofstellinge):
$amountOfStellinge = 0;
while ($amountOfStellinge<5){
mysqli_data_seek($result, $amountOfStellinge);
Here is the code what it looks like now, its wrong, i've been messing with t a lot, but maybe it shows you what I'm trying to achieve better.
if($result = mysqli_query($con, "SELECT * FROM stellingen WHERE REGIOID=1;")) {
$row = mysqli_fetch_assoc($result);
$stellingid= $row["Stelling_ID"];
//checking.. and the output is obviously not what I want in my next query
printf($stellingid);
//defining the variable
$Timer=0;
$sql1="SELECT * FROM stelling WHERE stelling_iD=$stellingid ORDER BY Timer DESC;";
$records2 = mysqli_query($con, $sql1);
$recordscheck = mysqli_num_rows($records2);
//max 5 data
if ($recordscheck < 5){
while ($stelling = mysqli_fetch_assoc($records2)){
//At the end, i would like to only have the data that is most recent
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}}
$recordscheck+=1; } // this is totally wrong
EDIT:
I've tried this, #noobjs
$Timer=0;
$sql1="SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.ID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer LIMIT 5 DESC ;";
$records2 = mysqli_query($con, $sql1);
printf($records2);
while ($stelling = mysqli_fetch_assoc($records2)){
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}
with this error:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in
EDIT for more clarification
Here is some sample data
The expected results is:
every page has uses data from a different REGIOID. I expect the page to show data from the table stelling(Table 1). Accordingly to the REGIOID (Table2)
if i understand right:
SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.stellingID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer DESC LIMIT 5 ;

PHP/SQL How can I make my query include results that has no records in another table yet?

I have 2 php codes that performs room search. The user specifies no. of beds, check in date and check out date. The first code retrieves all rooms with the corresponding number of beds. The second code checks if the room has an existing booking, if it does and the booking dates do not clash with the user input dates the room is displayed, if it does not have an existing booking it is simply displayed.
My first php code:
$sql = "SELECT rooms.rid, beds, orientation, price FROM rooms
WHERE (beds = $nOfBeds)";
if ($rOrientation != "") {
$sql .= " AND orientation = '$rOrientation'";
}
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
My second php code:
<?php
while ($row = mysqli_fetch_array($results)) {
$sql2 = "SELECT rid, checkin, checkout FROM bookings";
$results2 = mysqli_query($conn, $sql2)
or die ('Problem with query' . mysqli_error($conn));
$row2 = mysqli_fetch_array($results2);
if ($row["rid"] == $row2["rid"]) {
if (($cInDate < $row2["checkin"] && $cOutDate <= $row2["checkin"]) ||
(($cInDate >= $row2["checkout"] && $cOutDate > $row2["checkout"]))) {
?>
<tr>
<td><?php echo $row["rid"]?></td>
<td><?php echo $row["beds"]?></td>
<td><?php echo $row["orientation"]?></td>
<td><?php echo $row["price"]?></td>
</tr>
<?php }
}
} ?>
currently it is working right in regards to filtering out clashing dates however it is also filtering out rooms that does not have an existing booking. another problem i encountered with this code is it does not seem to work for multiple bookings with the same room id (rid) so right now it is only filtering dates regarding the first booking.
this is my booking table: http://imgur.com/DGOko1f
this is rooms table: http://imgur.com/ED5KFES
You can use,
if($result != NULL) {
// Execute code
} else {
// Give NULL values or error
}
Other way is, if(count($result) > 0).
This way you can get error free results.
nanjero05
Several things with the code. In the second php code your are going to execute a query per each room. That is not so good because it will generate many requests to the database.
Also your are requesting ALL the bookings, and then filtering in memory the ones that corresponds to the room. That it is also not always goods. Your read all the bookings again and again per each room.
One solution is to add in the second query (second php code) a condition to select only the bookings for the current room.
$rid = $row["rid"]
$sql2 = "SELECT rid, checkin, checkout FROM bookings where rid = $rid";
(Note: read about SQL injection to improve this)
Then you know that if the $result has no records, there are no bookings for the room.
why you need multiple query try this simple one liner
$sql = "SELECT rooms.rid, beds, orientation, price FROM rooms
WHERE beds = $nOfBeds AND rid NOT IN (SELECT bookings.rid FROM bookings WHERE user_checkin between checkin and checkout or ('user_checkin <= checkin AND user_checkout >= checkout) )";

PHP sum of PHP and MySQL fields echo

I have a database with the follow tables:
sales
expenses
taxes
earnings
When I sell some product it adds a item to sales, the same to expenses while I add expenses, taxes are added automaticly when selling and earnings too. They are on the same database but different tables.
I need to sum those fields together. I do it one by one without problems like this:
<?php
$query = mysqli_query($db, "SELECT SUM(total) AS `total` FROM `sales`");
while($result = mysqli_fetch_assoc($query)){
echo number_format($result['total'],0,',','.');}
?>
and
<?php
$query2 = mysqli_query($db, "SELECT SUM(expense) AS `expense` FROM `expenses`");
while($result2 = mysqli_fetch_assoc($query2)){
echo number_format($result2['expense'],0,',','.');}
?>
How do I sum those two and echo a result example:
sales - expense = value ?
<?php
$query = mysqli_query($db, "SELECT SUM(total) AS `total` FROM `sales`");
$query2 = mysqli_query($db, "SELECT SUM(expense) AS `expense` FROM `expenses`");
$total_sales = 0;
$total_expenses = 0;
while($result = mysqli_fetch_assoc($query)){
$total_sales = $total_sales + $result['total'];
echo number_format($result['total'],0,',','.');
}
while($result2 = mysqli_fetch_assoc($query2)){
$total_expenses = $total_expenses + $result['total'];
echo number_format($result2['expense'],0,',','.');
}
?>
The sum would be $total_sales-$total_expenses.
Are you sure you will sum those two together?
There are at least good points you do those things separation.
Firstly, the logic is very clearly.
Secondly, if you have many data like those, when you sum them separately, those will not influence each other. Because when you select data and do some operation, if the data is not huge, it will be ok. But if it is huge data, both your database and your cpu and memory will have big pressure.
Thirdly, when you select in database, it is not suggested doing operations such as sum, sub, division and multiplication, although database can do it. Because these operations are really wasting performance of database and computer.
Anyway, you still want to do that. Then you can try to left joint or right joint your table. You can use some foreign keys to connect these two tables and then you can do things which you wanna to do.

Getting results from 2 consecutive queries (PHP, SQL)

I need to return data from 2 separate tables at the same time. The info I need from the 2nd table is determined by what is returned from the first table. Here's what I'm working with..
$query = "SELECT * FROM pending WHERE paymentid = '".$_GET['vnum']."'";
$result = mysql_query($query);
$num = #mysql_num_rows($result);
$linkid = $res['paymentid'];
if ($num==0) {
echo "Hello, ".$_SESSION['Fname']."<br />There was an error, I cannot find this payment in the records.";
} else {
$picquery = mysql_query("SELECT * FROM _uploads_log WHERE linkid = '".$linkid."'");
$numb = #mysql_num_rows($picquery);
if ($numb==0) {
echo "there is no picture"; }
else {
echo "<img src=\"".$res['log_filename']."\" width=\"100\">"; }
I don't understand how to return the results as an array, if $res[] returns the results for the first query, then what returns the results for the second one?
or is there a better way to do this entirely?
Thank you
You need to do a join, but in order to still get results from your first query even if there is no picture (I assume that's why you split it up) you want a left join.
select * from pending left join _uploads_log on pending.paymentID=$_GET['vnum'] and _uploads_log.linkid = pending.paymentID
(note: php markings removed for readability - you'll have to add them back in)
This should (untested since I don't have your tables) return the full row for your vnum variable and also include the picture data if there is one.

Categories