Run a query based on another query using mysql php - php

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?

Related

multi sql select then insert

i have a total of 6 different tables that i select from then insert to a table before i do another select i was wondering if there was a way to skip the insert part and just do a select and combine all table data. the problem with the select and insert then select aproach is it gets really slow when there are about 1k+ records inserted. it takes about 30sec to 1min or more
im trying something like this
$sql = "select 1";
$statement = $conn->query($sql);
$rowset = $statement->fetchAll();
$sql1 = "select 2";
$statement1 = $conn->query($sql1);
$rowset1 = $statement1->fetchAll();
$combine = array_merge($rowset,$rowset1);
foreach ($combine as $key => $part) {
$sort[$key] = strtotime($part['date']);
}
array_multisort($sort, SORT_DESC, $combine);
To me it seems that you are replicating in php what you could do in sql. The above code in sql looks sg like this:
(select 1)
union all
(select 2)
order by date desc
You may have to tweak the order by clause depending on what data you exactly have in the date field. Otherwise, the above sql code should produce the exactly same results as your php code.

Check information from another array

I have 2 tables in the database, the table circle and the table gossips.
The table circle has 3 columns: id, idfrom, idto.
The table gossips has id, userid, gossip.
My objectif is to echo all the gossips only if the userid of this gossip (idto) and the id of the pageuser(idfrom) are on the same row in the table circle.
I wrote this code,
$query = 'SELECT * FROM gossips ORDER BY id DESC';
$result = mysqli_query($cxn, $query)
or die("Couldn't execute query");
$querycircle = 'SELECT idfrom,idto FROM circle WHERE idfrom="{$pageuserid}" ';
$resultcircle = mysqli_query($cxn, $querycircle)
or die("Couldn't check if user in circle.");
while($row = mysqli_fetch_assoc($result))
{
while($rowcheck = mysqli_fetch_assoc($resultcircle))
{
if($row['userid'] == $rowcheck['idto'] || $row['userid'] == $_COOKIE['id']){
echo '<div class="gossip">'.$row['gossip'].'</div>';
}
}
}
But it doesn't seem to work properly.
Do you intend to get the same data with mysqli_fetch_assoc($resultcircle)) on each round of the first while-loop?
Then you should buffer this data in an array first, as executing mysqli_fetch_assoc will always give you the next data set on each successive call. It will not restart on top of the data.
(Btw, this is better: while(null !== ($rowcheck = mysqli_fetch_assoc($result))))
Another method to realize your objective is to do only one combined SQL request.
EDIT: Sudip Pal is fast, look at his answer for a combined request! ;)
Try the single SQL query for this and then try with one while loop.
Select A.gossip from gossips A, circle B where A.userid=B.idto and B.idfrom="{$pageuserid}" order by A.id DESC;
NOTE: you can also compare the COOKIE value by adding the extra comparison on the query, like and B.userid=$_COOKIE["id"] (better to save the cookie value in a variable)

MySQL row selection

I have a table as below,
ID Name Age
----------------------
100 A 10
203 B 20
Now how do i select only row1 using MySQL SELECT command and then I've to increase +1 to it to select row2. In short I'll be using for loop to do certain operations.
Thanks.
Sounds like you've got a mix up. You want to select all the rows you want to iterate through in your for loop with your query, and then iterate through them one by one using php's mysql functions like mysql_fetch_row
You should not try to use tables in a linear fashion like this. Set your criteria, sorting as appropriate, and then to select the next row use your existing criteria and limit it to one row.
SELECT * FROM `table` ORDER BY `ID` LIMIT 1
SELECT * FROM `table` ORDER BY `ID` WHERE ID > 100 LIMIT 1
You'd probably be better off retrieving all rows that you need, then using this. Note the LIMIT is entirely optional.
$query = mysql_query(' SELECT ID, Name, Age FROM table_name WHERE condition LIMIT max_number_you_want '))
while ($row = mysql_fetch_assoc($query)
{
// Do stuff
// $row['ID'], $row['Name'], $row['Age']
}
Lots of small queries to the database will execute much slower than one decent-sized one.
You should get the result into an array (php.net : mysql_fetch_*).
And after you'll can loop on the array "to do certain operations"
Yep, this is a pretty common thing to do in PHP. Like the others who have posted, here is my version (using objects instead of arrays):
$result = mysql_query("SELECT * FROM table_name");
while ($row = mysql_fetch_object($result)) {
// Results are now in the $row variable.
// ex: $row->ID, $row->Name, $row->Age
}

Subquery in PHP

Let's put an easy example with two tables:
USERS (Id, Name, City)
PLAYERS (Id_Player, Number, Team)
And I have to do a query with a subselect in a loop, where the subselect is always the same, so I would like to divide it into two queries and put the subselect outside the loop.
I explain. What works but it is not optimize:
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN (SELECT Id FROM USERS WHERE City='London')");
}
What I would like to do but it doesn't work:
$res1=mysql_query("SELECT Id from USERS where City='London'");
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN **$res1**");
}
Thanks!
Something like this should work.
<?
$sql = "SELECT Team from PLAYERS
JOIN USERS on (Id_player=Id)
WHERE Number BETWEEN $minID AND $maxID
AND City='London'
GROUP BY Team";
$results=mysql_query($sql) or die(mysql_error());
// $results contain all the teams from London
// Use like normal..
echo "<ul>\n";
while($team = mysql_fetch_array($results)){
echo "\t<li>{$team['Team']}</li>\n";
}
echo "</ul>";
Placing SQL quires in loops can be very slow and take up a lot of resources, have a look at using JOIN in you SQL. It's not that difficult and once you've got the hang of it you can write some really fast powerful SQL.
Here is a good tutorial worth having a look at about the different types of JOINs:
http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php
SELECT PLAYERS.*, USERS.City FROM PLAYERS, USERS WHERE USERS.City='London' AND PLAYERS.Number = $i
Not the best way to do it; maybe a LEFT JOIN, but it should work. Might have the syntax wrong though.
James
EDIT
WARNING: This is not the most ideal solution. Please give me a more specific query and I can sort out a join query for you.
Taking your comment into account, let's take a look at another example. This will use PHP to make a list we can use with the MySQL IN keyword.
First, make your query:
$res1 = mysql_query("SELECT Id from USERS where City='London'");
Then, loop through your query and put each Id field one after another in a comma seperated list:
$player_ids = "";
while($row = mysql_fetch_array($res1))
{
$player_ids .= $row['Id'] . ",";
}
$player_ids = rtrim($player_ids, ",");
You should now have a list of IDs like this:
12, 14, 6, 4, 3, 15, ...
Now to put it into your second query:
for($i = 0; $i<something; $i++)
{
$res2 = mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN $player_ids");
}
The example given here can be improved for it's specific purpose, however I'm trying to keep it as open as possible.
If you want to make a list of strings, not IDs or other numbers, modify the first while loop, replacing the line inside it with
$player_ids .= "'" . $row['Id'] . "',";
If you could give me your actual query you use, I can come up with something better; as I said above, this is a more generic way of doing things, not necessarily the best.
Running query in a loop is not a great idea. Much better would be to get whole table, and then iterate through table in loop.
So query would be something like that:
"SELECT Team from PLAYERS WHERE Number BETWEEN($id, $something)
AND Id_Player IN (SELECT Id FROM USERS WHERE City='London')"
$res1=mysql_query("SELECT Id from USERS where City='London'");
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN **$res1**");
}
Would work, but mysql_query() returns a RESULT HANDLE. It does not return the id value. Any select query, no matter how many, or few, rows it returns, returns a result statement, not a value. You first have to fetch the row using one of the mysql_fetch...() calls, which returns that row, from which you can then extract the id value. so...
$stmt = mysql_query("select ID ...");
if ($stmt === FALSE) {
die(msyql_error());
}
if ($stmt->num_rows > 0) {
$ids = array();
while($row = mysql_fetch_assoc($stmt)) {
$ids[] = $row['id']
}
$ids = implode(',', $ids)
$stmt = mysql_query("select TEAM from ... where Id_player IN ($ids)");
.... more fetching/processing here ...
}

SQL query in PHP: got nothing with printing the array

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.

Categories