MySQL Union Losing Table Names - php

I have a MySQL query where I am trying to search 2 tables simultaneously. This is for an autocomplete search box that searches for regular clients and business clients. Here is the code:
$query = mysql_query("SELECT * FROM clients WHERE lastname LIKE '$q%' AND agentid = '$agentid'
UNION
SELECT * FROM busclients WHERE busname LIKE '$q%' AND agentid = '$agentid'")or die(mysql_error());
if($query) {
while ($result = mysql_fetch_array($query)) {
$busname = $result['busname'];
print_r($result);
if(isset($busname)){
$description['id'] = 'viewbusiness.php?id=' . $result['ID'];
$description['value'] = $busname ;
array_push($return_arr,$description);
}
else
{
$description['id'] = 'viewclient.php?id=' .$result['ID'];
$description['value'] = $result['lastname'] . ", " . $result['firstname'] ;
array_push($return_arr,$description);
}
}
}
The problem is that the business clients get assigned the table names from the regular clients, so the code never uses the if(isset($busname)) because busname becomes lastname instead, and directs you to the veiwclient page.

SELECT
a.lastname ,
b.busname
FROM clients as a
INNER JOIN
busclients as b
on b.agent_id = a.agent_id
WHERE a.agent_id = $agent_id
AND (a.lastname LIKE '$q%' OR b.busname LIKE '$q%')

By specifically selecting the column names you want from that table, and selecting a blank string for the others, I believe you can get the results you're looking for using something like this:
SELECT firstname, lastname, '' AS busname FROM clients WHERE ... UNION SELECT '' AS firstname, '' AS lastname, busname FROM busclients WHERE ...

Related

Using a SELECT query to get data from two different tables in database

I am really struggling to understand what is wrong with my query. When I use var_dump($sqli); it just echos out the entire query without any data in it.
I want to create a query so when a user searches for a city the returned search result would be the attractions associated with that city. I realise that there is a few errors with my code, however if I get the query completed I will go from there and debug the rest of the code. If anyone has any ideas as to why my query isn't working I would greatly appreciate them.
require_once('config1.php');
error_reporting(E_ALL);
$output = '';
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$sqli = 'SELECT attraction_name, lat, long, cost FROM zz_attractions WHERE city_id IN SELECT city_id FROM zz_city WHERE city_name LIKE %searchq%' or die("could not search");
var_dump($sqli);
$result = mysqli_query($conn, $sqli);
$count = mysqli_num_rows($result);
if ($count == 0) {
$output = 'there was no search results';
} else {
while ($row = mysql_fetch_array($sqli)) {
$attraction_name = $row['attractionname'];
$lat = $row['latitude'];
$long = $row['longitude'];
$cost = $row['cost'];
$output .= '<div>'.$attraction_name.' '.$lat.' '.$long.' '.$cost.'</div>';
}
}
}
Your current query fails because you need the parentheses shown here:
SELECT attraction_name, lat, long, cost
FROM zz_attractions
WHERE city_id IN (SELECT city_id
FROM zz_city
WHERE city_name
LIKE '%searchq%')
But a better way to do it would be an inner join:
SELECT a.attraction_name, a.lat, a.long, a.cost
FROM zz_attractions a
INNER JOIN zz_city c ON a.city_id = c.city_id
WHERE c.city_name LIKE '%searchq%'
----
just an observation, nothing more...
Never quite understood why PHP coders tend to have every SQL query as a single row
$query = '
SELECT a.attraction_name, a.lat, a.long, a.cost
FROM zz_attractions a
INNER JOIN zz_city c ON a.city_id = c.city_id
WHERE c.city_name LIKE %searchq%
';
echo $query;

how to select data from a table useing values from another table

I want to select data from a table called tbl_users using a value from another table called mergeing and column called donator_1.
I tried the following:
$result = $DBcon->query("SELECT tbl_users.username, tbl_users.email, tbl_users.Phone_number FROM tbl_users,mergeing WHERE mergeing.donator_1= tbl_users.user_id AND mergeing._id = 6");
while($row = $result->fetch_array()) {
echo '<b>' . $l['user_id'] .'</b><b>' . $l['username'] . '</b>';
}
You can try nested queries:
SELECT username, email, Phone_number
FROM tbl_users
WHERE user_id = (SELECT donator_1 FROM mergeing WHERE _id = 6 )
or an inner join :
SELECT username, email, Phone_number
FROM tbl_users
JOIN mergeing ON tbl_users.user_id = mergeing.donator_1
WHERE mergeing._id = 6

How to retrieve data from multiple tables using a PHP form?

I want to retrieve data from multiple tables using dot operator/join where arguments are passed from an HTML/PHP form.
HTML CODE
<input name="rollno" type="text" placeholder="Roll Number" required>
<input name="submit_view_details" type="submit" value="Proceed">
PHP CODE
if(isset($_POST['submit_view_details']))
{
$rollno = (int) $_POST['rollno'];
$query = "select * from table1, table2 where table1.{$rollno}=table2.{$rollno}";
$result=mysqli_query($connection,$query);
}
In the browser if enter the input 1 and echo this query then it looks like follows:
select * from table1, table2 where table1.1=table2.1
and no row is fetched despite of having data in the table(s).
it only works if the query looks like follows:
select * from table1,table2 where table1.rollno=table2.rollno
However, in that case it fetches all the rows but I need only the row of the rollno that user entered in the above mentioned form.
I am just not able to work this out. Help would be much appreciated. Thanks!
Use the AND keyword to specify the rollno.
SELECT * FROM table1, table2 WHERE table1.rollno = table2.rollno
AND table1.rollno = {$rollno};
You could probably use the keyword JOIN instead like this :
SELECT * FROM table1 NATURAL JOIN table2
WHERE rollno = {$rollno};
You need joins
take a reference of joins from here,
i am sure it will help
http://www.tutorialspoint.com/mysql/mysql-using-joins.htm
You should use join like this
$query = "SELECT tbl1.*, tbl2.*
FROM tbl1
INNER JOIN tbl2 ON tbl1.id = tbl2.id
WHERE tbl1.column = value ";
foreach ($pieces_2 AS $value) {
$pieces_3[] ="(CONCAT_WS('|',$presql2) like '%$value%')"; //concat all columns from one table
}
$serch_jyouken = implode(" and ",$pieces_3); // for multiple keywords
$result1 = mysqli_query($connection, "select p.p_no from pfr_data p where (" .$serch_jyouken .")");
$res1 = array();
while($r1 = mysqli_fetch_array($result1){
$res1[] = $r1['p_no'] ; //fetch primary key from table and store it into array
}
foreach ($pieces_2 AS $value) {
$pieces_4[] ="(CONCAT_WS('|',$presql3) like '%$value%')"; // same as above
}
$serch_jyouken1 = implode(" and ",$pieces_4);
$result2 = mysqli_query($connection, "select p2.p_no from pfr_mod_inform p2 where (" .$serch_jyouken1 .")" );
$res2 = array();
while($r2 = mysqli_fetch_array($result2)){
$res2[] = $r2['p_no'];
}
$res_mrg = array_merge($res1 , $res2); //merge array
$result = implode("','",$res_mrg ); // array to sring
$sql5 = $presql ." from pfr_data p where p.p_no in ('$result') order by p.section_p,p.status,p.no";

How do I use two mysql tables in one statement

So, I've put in a favourite images table, and I can't figure out how to get it working properly
Basically, this is the setup:
ImageFavs
FavID, UserID, ImgID
ImageList
ImgID, SiteID
I'd like it to select 20 or so images from the favourites table, but only ones that match the siteid in the image list table
This is the code I have at the moment, but it dawned on me it'd select 20 images from favourites, then only display them if the matching site was actually checked.
#select matching sites
for($i=0;$i<count($sites)-1;$i++){
$siteinfo = explode("-",$sites[$i]);
$siteid = $siteinfo[0];
$sitegroup = $siteinfo[1];
$selection[$siteid]="exists";
if($i!=0){
$sqlextra .= " OR ";
}
else{
$sqlextra = "AND (";
}
$sqlextra .= "SiteID='".$siteid."'";
}
if(!empty($sqlextra)){
$sqlextra .= ")";
}
else{
$sqlextra = "AND SiteID='-1'";
}
#show favourites
if($_GET['f']==1){
$sql="SELECT * FROM ImageFavs WHERE UserID='".$_SESSION['User_ID']."' AND Active = '1' ORDER BY RAND() LIMIT 20";
#(rand is just me being lazy, eventually I'll figure out how to separate it onto pages)
$result = mysql_query($sql);
$num = mysql_numrows($result);
if($num>0){
while ($row=mysql_fetch_array($result, MYSQL_BOTH)){
if(empty($sqlextra2)){
$sqlextra2 = " AND (";
}
else{
$sqlextra2 .= " OR ";
}
$sqlextra2 .= "ImgID='".$row['ImgID']."'";
}
$sqlextra2 .= ")";
}
}
#don't show favourites
if(empty($sqlextra2)){
$sqlextra2 = " ORDER BY RAND() LIMIT 20";
}
$sql="SELECT * FROM ImageList WHERE Valid='1' ".$sqlextra.$sqlextra2;
This output $sql from this seems like it could be so much neater though, an example of it is like this
SELECT * FROM ImageList WHERE Valid='1' AND (SiteID='6') AND (ImgID='5634' OR ImgID='8229' OR ImgID='9093' OR ImgID='5727' OR ImgID='7361' OR ImgID='5607' OR ImgID='7131' OR ImgID='5785' OR ImgID='7339' OR ImgID='5849' OR ImgID='7312' OR ImgID='5641' OR ImgID='8921' OR ImgID='7516' OR ImgID='7284' OR ImgID='5873' OR ImgID='8905' OR ImgID='7349' OR ImgID='7392' OR ImgID='8725')
Also, while I'm here, would there be a non resource heavy way to count the number of favourites for a user per website?
It's not for anything big, just messing around on a personal website to see what I can do.
You can INNER JOIN your two tables to get the results you want. INNER is used when you want results from both tables. It's best to use aliases to keep your tables straight.
SELECT l.*
FROM ImageFavs f
INNER JOIN ImageList l ON f.ImgID = l.ImgID
WHERE l.SiteID = [your site ID]
AND f.UserID='" . $_SESSION['User_ID'] . "'
AND f.Active = '1'
ORDER BY RAND() LIMIT 20
To get a count by site you can use GROUP BY. I think this should get you that count
SELECT COUNT(f.ImgID)
FROM ImageFavs f
INNER JOIN ImageList l ON f.ImgID = l.ImgID
WHERE f.UserID='" . $_SESSION['User_ID'] . "'
AND f.Active = '1'
GROUP BY l.SiteID
you want to use "JOIN"
SELECT * FROM ImageFavs LEFT JOIN ImageList ON ImageFavs.ImgID = ImageList.ImgID WHERE ImageList.SiteID = <your_site_id>
This works-
//Assuming $site_id contains the site ID/
$query = "select *.IF from ImageFavs as IF, ImageList as IL where IL.ImgId = IF.ImgId and IL.SiteId = $site_id LIMIT 20"

Looping through a mysqli result

I'm trying to display a list of status updates from artists that a logged in user is following.
So far I have this:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
}
But i'm not sure how to loop through and display the returned status updates?
This isn't a strong point of mine, so any pointers would be greatly appreciated!
What prevented you from doing similar to what you'd already done for the first query? Something like follows:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
while($status_result_row = mysqli_fetch_assoc($status_result)) {
echo $status_result_row['mycol']; // This is where you know better than us
}
}
Or if those two tables artist_likes and status_updates have artist_id in common then you could just use one query with a join. (But don't know if you are asking for that).
Just for avoiding multiple query, you can use one query like this:
SELECT l.*, s.*
from artist_likes l, status_updates s
WHERE
l.artist_id = s.artist_id and
l.user_id = '1'
or
SELECT l.*, s.*
from artist_likes l
JOIN status_updates s on (l.artist_id = s.artist_id)
WHERE
l.user_id = '1'

Categories