I have a query that selects all appropriate record in a table 'hotels' and then for each hotel looks for booked room of certain type in table 'booked_rooms' and all of that for certain period.
So first I'm taking out all hotel_ids from 'hotel_table', based on the location provided from the search form, and for each hotel_id i loop through the 'booked_rooms' table.
Here's the code:
if(isset($_GET['book'])){
$sql=mysql_query("SELECT hotel_id FROM 'hotels' WHERE city='$city") or die(mysql_error());
while($row=mysql_fetch_array($sql)){
$sql_2=mysql_query("SELECT * FROM `booked_rooms` WHERE hotel_id='$hotel_id'
AND arrival_date BETWEEN '$arrival_date' AND '$departure_date'
OR departure_date BETWEEN '$arrival_date' AND '$departure_date'")
or die(mysql_error());
}
while($row_2=mysql_fetch_array($sql_2)){
print_r($row_2);
}
}
// $city, $arrival_date and $departure date are values retrieved from the search form
The problem is that I get a loop through 'hotel' table and get all the hotel_ids appropriate to the location, but got nothing with printing the $row_2 array.
I tried using JOINS in the SQL, 'foreach' loop, but no luck as well.
Not knowing PHP, can you do it in one query?
SELECT booked_rooms.*, hotels.* FROM 'hotels'
JOIN 'booked_rooms' ON hotels.hotel_id = booked_rooms.hotel_id
WHERE
hotels.city='$city" AND
(
booked_rooms.arrival_date BETWEEN '$arrival_date' AND '$departure_date' OR
booked_rooms.departure_date BETWEEN '$arrival_date' AND '$departure_date')
Check the '' quotes around your tables as necessary for the PHP strings etc...
Please don't put build SQL queries from outside, untrusted data. This is the Bobby Tables problem.
Please see a page like this one for details on using parameterized statements.
First of all, you have an error in your first SQL in that you haven't quoted your cityname properly. Then you don't fetch the hotel_id out of the resultset. And then you have the second loop in the wrong place.
Try the following:
if( isset($_GET['book']) ) {
$sql = mysql_query("SELECT hotel_id FROM 'hotels' WHERE city='".mysql_real_escape_string($city)."'") or die(mysql_error());
$arrival_date = mysql_real_escape_string($arrival_date);
$departure_date = mysql_real_escape_string($departure_date);
while( $row = mysql_fetch_assoc($sql) ) {
$hotel_id = $row['hotel_id'];
$sql_2 = mysql_query("SELECT *
FROM `booked_rooms`
WHERE hotel_id = ".$hotel_id."
AND (
arrival_date BETWEEN '".$arrival_date."' AND '".$departure_date."'
OR departure_date BETWEEN '".$arrival_date."' AND '".$departure_date."'
)")
or die(mysql_error());
while( $row_2 = mysql_fetch_assoc($sql_2) ) {
print_r($row_2);
}
}
}
// $city, $arrival_date and $departure date are values retrieved from the search form
I'd also recommend being more generous in your whitespace. It makes the PHP easier to read.
Related
This is my table:
All I want to do is to obtain the '75' int value from the 'expquim' column to later addition that number into another (75+25) and do an UPDATE to that camp (now it is 100).
Foremost, there are dozens of ways to accomplish what you want to do. If you're querying the table, iterating over results and doing some conditional checks, the following will work for you. This is pseudo code... Check out the function names and what parameters they require. $db is your mysqli connection string. Obviously replace tablename with the name of your table. The query is designed to only select values that are equal to 75. Modify the query to obtain whatever results you want to update.
This should get you close to where you want to be.
$query = "SELECT * FROM tablename WHERE idus='1'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['expquim'] == 75){
$query2 = "UPDATE tablename SET expquim='".$row['expquim']+25."' WHERE idus='".$row['idus']."' LIMIT 1 ";
$result2 = mysqli_query($db,$query2);
}
}
I am using php and mysql to create a page that displays all of the jobs we have in the database. The data is shown is a table and when a row is clicked a modal window triggers with the information of the clicked job inside. At the top of the page I want a simple counter that shows amount of paid jobs, invoiced jobs etc etc. I am using the code below but having no luck...
<?php
$con = mysql_connect("localhost","databaseusername","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("databasename", $con);
$result = mysql_query("select count(1) FROM jobslist");
$row = mysql_fetch_array($result);
$total = $row[0];
mysql_close($con);
?>
This code as far as I am aware is counting the amount of INT columns set to 1 rather than 0. No matter what I try I can't seem to get it to count the amount of 'paid' items in the database or 'invoiced' etc etc.
Once the count function is complete currently I am echoing out the outcome as below:
<?php echo "" . $total;?>
I am sure I am overlooking something simple, but any help is appreciated.
EDIT: TABLE STRUCTURE INCLUDED
http://i.stack.imgur.com/hcMJV.png
Assuming a column called paid you could restructure the query similar to the following. If you needed to sum the amounts involved that requires additional tweaking.
$result = mysql_query("select
( select count(*) from `jobslist` where `paid`=1 ) as 'paid',
( select count(*) from `jobslist` where `paid`=0 ) as 'unpaid'
from jobslist");
$rows = mysql_num_rows( $result );
while( $rs=mysql_fetch_object( $result ) ){
$paid=$rs->paid;
$unpaid=$rs->unpaid;
echo 'Total: '.$rows.'Paid: '. $paid.' Unpaid: '.$unpaid;
}
When I do this I usually name the COUNT result. Try this out:
$result = mysql_query("SELECT COUNT(*) AS total_rows FROM jobslist;");
$row = mysql_fetch_array($result);
$total = $row['total_rows'];
If you do not want to name the COUNT result, then give the following a go:
$result = mysql_query("SELECT COUNT(*) FROM jobslist;");
$row = mysql_fetch_array($result);
$total = $row['COUNT(*)'];
select count(1) FROM jobslist
This code as far as I am aware is counting the amount of INT columns set to 1 rather than 0.
No, this is just counting rows in your table and not filtering. If you want to count something with a specific filter you have to add that filter condition:
SELECT COUNT(*) AS `MyCount`
FROM `joblist`
WHERE `MyColumn` = 1; -- assuming MyColumn contains the INT you're looking for
You should stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
First you should change deprecated mysql_... to mysqli_... (look here how to). But it's not the reason you fail.
Unlike you seem to suppose, COUNT(1) will not look for an INT column having value 1.
Instead you must use COUNT(*) or COUNT(a_column_name) (same result), with adding a WHERE clause stating which condition is involved.
Here you seem wanting to count records where a given column (say the_column) has value 1. So you should:
SELECT COUNT(*)
FROM jobslist
WHERE the_column = 1
Last point: you don't need echo "" . in <?php echo "" . $total;?>.
Merely write <?php echo $total;?>.
How do I echo the latest values in column1? The below code echos the values before the update.
while($line = mysql_fetch_array($result)) {
$Student = $line["calss8"];
$querySf = "SELECT SUM(ABC) AS val1 FROM tbl1 WHERE student = '$Student'";
$resultSf = mysql_query($querySf);
$rSf = mysql_fetch_array($resultSf);
$totalSf = $rSf['val1'];
$totTMonth = $totalSf;
mysql_query("UPDATE tbl4 SET column1 = $totTMonth WHERE student = '$Student' LIMIT 1");
}
echo $line["column1"].",,";
As far as I know, you'll have to make a separate query to see what was just updated. I mean, run your select, perform your update, then do another select. You can get general information like how many rows were updated, but I don't think you can get specific information like the changed values in a column. Phil was right in suggesting that you should just print out the '$totTMonth' value since that is what you are updating your column with. That would be less overhead than doing another query to the database.
I think that problem starts before the code above. This code line will display the select results :echo $line["column1"].",,";. The variable $line is set before the code above. My solution is to do the following:
$result1 = mysql_query("SELECT column1 FROM student ..."); /* I insert the select query here */
While($row= mysql_fetch_array($result)) {
echo $row['column1'].",,";
}
I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}
The code below searches my mysql database and comes back with postcodes like IG6,RM11,RM8,RM4,RM2,RM6,RM7,RM1,RM5 and a distance using a stored procedure. (All ok)
PROBLEM: With these results, I want to search another table in same database that may have job information with those Postcodes (probably using LIKE).
What's the best way to get this working? I have tried many examples (implode, arrays, etc)
Is one connection to database correct? How do I query the variable as it does come back with 2 columns, postcode and Distance. Should I split in an array (how?)
END PRODUCT: HGV Driver RM5, Cleaner RM5, Teacher RM5
(SELECT title FROM jobinfo WHERE location IN results from other query);
<?php
include ("conn.php");
$first="RM5";
$result = mysql_query("select outcode, GetDistance(Lat, Lon, (SELECT Lat from postcodes where outcode = '$first' limit 1),(SELECT Lon from postcodes where outcode = '$first' limit 1)) as Distance from postcodes having Distance < 3 order by Distance DESC;");
while($row = mysql_fetch_array($result))
{
echo ($row['outcode']) ;
}
// This returns postcodes
$resultb = mysql_query("SELECT title FROM jobinfo WHERE location IN ($results[outcode]) ");
while($row = mysql_fetch_array($resultb))
{
echo ($row['title']) ;
}
mysql_close($con);
?>
Please help.....any reference to join table needs full explanation as all so far don't help!
First Prepare the output into the clause:
in the first while loop:
while($row = mysql_fetch_array($result))
{
$array[] = $row['outcode'] ;
}
Then prepare the array for the IN clause:
foreach ($array as $a) {$clause.= "'$a',";}
$clause=substr($clause,0,-1)
Finally use the clause for the IN statement:
$resultb = mysql_query("SELECT title FROM jobinfo WHERE location IN ($clause) "
===== EDIT === LIKE statement
For like.. you need multiple like statement OR together.. Using SQL LIKE and IN together
Change the prepare clause code to this:
foreach ($array as $a) {$clause.= " location LIKE '%$a%' OR";}
$clause=substr($clause,0,-3)
AND the sql becomes:
$resultb = mysql_query("SELECT title FROM jobinfo WHERE $clause ");
Of course you will want to addin some more error checking.. think of the possible injection.
I think you're trying to do something like this answer MySQL LIKE IN()?
Also, please use parametrized queries How can I prevent SQL injection in PHP?