Query Two Databases at once using Prepared statements - php

I have function called getData($Books, $Users, $InputID); that receives two database connections and User ID.
On the User Database, I have a table called Users
-----------------
UserID | UserName
-----------------
On the Books Database, I have a table called Books
------------------------------
BookID | BookName | BookUserID
------------------------------
What I want to do is to write ONE query that will:
Select the the User on the Users table with UserID = $InputID, and also select the book on Books Table where BookUserID = $InputID;
This must be done using a Prepared Statement..
This is what i have tried.
function getData($Books, $Users, $InputID){
$fetch_results = prepare('SELECT * from UsersDB.Users U LEFT JOIN BooksDB.Books B ON B.BookUserID = U.UserID Where UserID = :InputID');
$fetch_results->execute(array(':userID' => $InputID));
return $Data;
}

if your both DB(UserDb, BooksDB) on same server then query will be like.
SELECT u.UserName, b.BookName
FROM UserDB.dbo.Users u
INNER JOIN BooksDB.dbo.Books b
ON b.UserId = b.BookUserId
WHERE u.UserId = $InputID
OR BookUserID = $InputID;
If your both DB(UserDB, BooksDB) on different server then.
First you need to create link for other server then fire the following like query with link name, Let your link Name is LinkServer2 and you are firing query from server1.UserDB. Make sure to use fully qualified name for linked server.
SELECT u.UserName, b.BookName
FROM UserDB.dbo.Users u
INNER JOIN LinkServer2.BooksDB.dbo.Books b
ON b.UserId = b.BookUserId
WHERE u.UserId = $InputID
OR BookUserID = $InputID;
if you want to use LEFT JOIN and retrieve all number of columns(SELECT *) then you can do it no problem.

Related

join 3 tables with where clause

This query performs three JOIN operations with 3 tables. But is not ok i see..i'm trying to output all the rows in echo, but i have bad luck.
Mysql table columns:
tours
------
titlu_slider | desc_slider | poza_slider | poza_articol | pret
tours_review
----------
name | time_added | review_text
tours_overview
------------
descriere | titlu_box1 | desc_box1 | titlu_box2 | desc_box2 | titlu_box3 | desc_box3 | titlu_box4 | desc_box4
Php code:
<?php
$db = mysqli_connect("localhost", "root", "fidodido", "antonytravel");
$q = mysqli_query($db,"SELECT * FROM tours INNER JOIN tours_review INNER JOIN tours_overview WHERE id = ".$_GET['id']."");
while ($row = mysqli_fetch_assoc($q)) {
$titlu_slider=$row['titlu_slider'];
$desc_slider=$row['desc_slider'];
$poza_slider=$row['poza_slider'];
$poza_articol=$row['poza_articol'];
$pret=$row['pret'];
## Review table
$name_review=$row['name'];
$time_added=$row['time_added'];
$review_text=$row['review_text'];
## Overview table
$descriere=$row['descriere'];
$titlu_box1=$row['titlu_box1'];
$desc_box1=$row['desc_box1'];
$titlu_box2=$row['titlu_box2'];
$desc_box2=$row['desc_box2'];
$titlu_box3=$row['titlu_box3'];
$desc_box3=$row['desc_box3'];
$titlu_box4=$row['titlu_box4'];
$desc_box4=$row['desc_box4'];
echo '<section class="parallax_window_in" data-parallax="scroll" data-image-src="'.$poza_slider.'" data-natural-width="1400" data-natural-height="470">
<div id="sub_content_in">
<div id="animate_intro">
<h1>'.$titlu_slider.'</h1>
<p>"'.$desc_slider.'"</p>
</div>
</div>';
Some help needed..thanx.
You need to specify how how the tables relate to each other which might look something like the on conditions shown below (which are just guesses)
SELECT *
FROM tours t
INNER JOIN tours_review trev ON t.id = trev.tour_id
INNER JOIN tours_overview tovr ON = t.id = tovr.tour_id
WHERE t.id = $whatever
You then face the issue of what type of join because if you have a tour with no reviews then you probably still want to list it. For that type of relationship you need an "outer join".
SELECT *
FROM tours t
LEFT OUTER JOIN tours_review trev ON t.id = trev.tour_id
INNER JOIN tours_overview tovr ON = t.id = tovr.tour_id
WHERE t.id = $whatever
If every every tour has an "overview" then that can remain an "inner join"
EDIT: Please note that you need to prefix EVERY column reference with a table name or table alias (I have used table aliases to make the query shorter). If you don't do this your query may fail, e.g. if every table has a column id and you just ask for where id = 123 the query will not know which table to use and the query would error.
INNER join shows the records if there are matching record. Use OUTER join to show all records if it does not exists on other tables.
You are missing a few things in your query. Specifically related to the fields that link the tables. To do these joins the best practice is to name each table and then use that name to in an ON statement to JOIN the tables
So
SELECT * FROM tours
INNER JOIN tours_review
INNER JOIN tours_overview
WHERE id = ".$_GET['id'].""
Should be:
SELECT * FROM tours AS t
INNER JOIN tours_review AS r ON r.somefield = t.somefield
INNER JOIN tours_overview AS o ON o.somefield = t.somefield
WHERE id = ".$_GET['id'].""
MySQL can't join tables if it doesn't know what is connecting them.

How to JOIN 2 tables on mySql?

I have two tables: publick_feed and users
I want to SELECT all from public_feed and also SELECT a three columns from users whose id is the same of user_id in public_feed
and assign the rows returned from public_feed to the column in users table ( correspondent)
I try this:
<?php
$sql = "
SELECT * FROM public_feed
WHERE user_id IN
(SELECT id FROM users) AND
(SELECT Firstname,Lastname,Avatar FROM users WHERE id IN(SELECT user_id FROM public_feed))
";
$query = mysqli_query($dbc_conn,$sql);
if(mysqli_num_rows($query) > 0){
while($row = mysqli_fetch_assoc($query)){
//echo rows with correspondent details from the users table
echo $row['user_id'];
}
}
<?
Please any help will be much appreciated.
Thank you.
Or version with left join in case if there is no user in public_feed, and you still want to fetch user data
SELECT
u.*, f.*
FROM
public_feed f LEFT JOIN
users u ON f.user_id = u.id;
Because author asked for explanation, here it is:
First we are going to use table name alias to make query shorter
public_feed f
and
users u
we are saying that want to refer to tables with an alias. Of course * means that we want to select all columns
SELECT users.*, public_feed.*
is equal to
SELECT u.*, f.*
Of course you can use any other letters as an alias
Next we are saying that public_feed.user_id must be equal to users.id. But when public feed entry does not exists just display columns with null values. This is why we are using LEFT JOIN instead of INNER JOIN. In general JOINS are used to fetch related data from more than one related tables.
ON keyword is saying values from which columns in the tables must be equal to satisfy the request
I think doing a join would be cleaner than using a complicated subquery:
SELECT u.Firstname,
u.Lastname,
u.Avatar,
COALESCE(pf.User_id, 'NA'),
COALESCE(pf.Post, 'NA'),
COALESCE(pf.Date, 'NA')
FROM users u
LEFT JOIN public_feed pf
ON u.Id = pf.User_id
I chose a LEFT JOIN of users against public_feed on the assumption that every feed will have an entry in the users table, but not necessarily vice-versa. For those users who have no feed entries, NA would appear in those columns and that user would appear in only a single record.

display data together from 2 different SQL table

I need to display details from 2 different tables
Table 1- user table
Table 2-bicycle table
I can show a list of users and bicycle.
But can't show a list that show which bicycle belongs to who.
Bicycle table,
user table
You need to use a LEFT JOIN. The query below will connect your user table to your bicycle table based on the userIDand return all of the bicycle and user fields
SELECT b.*, u.*
FROM registered_users u
LEFT JOIN registered_bicycle b ON (u.userID = b.userID)
If you want specific bicycle fields just prefix them with b. Example:
SELECT b.brand, b.model, b.color...
Click on SQL tab and type this:
SELECT * FROM `registered_bicycle` JOIN `registered_users` ON `registered_users`.`userID` = `registered_bicycle`.`userID`
and run it
You have to make a foreign key from user_table to bicycle_table like this.
user_table has user_id = user_1,name=John Richard
bicycle_table has user_id = user_1,description = Bicycle1
to fetch the data:
select a.user_id, a.name,b.description from
(select user_id, name from user_table) as a
left join
(select user_id,description from bicycle_table) as b
on a.user_id = b.user_id

SQL query optimization for MySql database

I have 3 table: user , company and deal.
One user may own several companies. Deal is made between the 2 companies. I need a list of deals, which involved my company.
Deals must contain the following fields: partner_company_id,my_company_id,partner_photo,partner_name,deal_about.
Language code: PHP.
Database: Mysql.
1.List of my company I can get by user ID.
user_id = 22;
companyList = query('SELECT company_id FROM company WHERE user_id = ?', user_id);
2. Then i get deal list where my_company_id is company_first_id
list1 = query('SELECT u.name AS partner_name, u.photo AS partner_photo, d.first_company_id AS
my_company_id , d.second_company_id AS partner_company_id,d.about AS deal_about FROM deal AS d
INNER JOIN company AS c ON c.company_id = d.second_company_id
INNER JOIN user AS u ON u.user_ud = c.user_id
WHERE d.company_first_id IN (?)', companyList);
3. Then i get deal list where my_company_id is company_second_id
list2 = query('SELECT u.name AS partner_name, u.photo AS partner_photo, d.first_company_id AS
partner_company_id , d.second_company_id AS my_company_id,d.about AS deal_about FROM deal AS d
INNER JOIN company AS c ON c.company_id = d.first_company_id
INNER JOIN user AS u ON u.user_ud = c.user_id
WHERE d.company_second_id IN (?)', companyList);
4. then i marge to array and set limit list
list = array_marge(list1,list2);
result = array_slice (list ,0 , 10);
HELP please optimize this queries.
THANKS.
DATABASE SCHEME
user | company | deal |
--------------------------------------------------
user_d | company_id | deal_id
photo | user_id |first_company_id
name | about |second_company_id
| |description
Are your queries so slow? They don't look slow (provided you have indexes on all IDs of course).
However, you can save one database access by combining the two deal queries. Either you simply select query1 UNION ALL query1 or you do it in one pass:
select
u.name AS partner_name,
u.photo AS partner_photo,
d.my_company_id,
d.partner_company_id,
d.about AS deal_about
from
(
select
about,
case when company_first_id in (?) then
company_first_id
else
company_second_id
end as my_company_id,
case when company_first_id in (?) then
company_second_id
else
company_first_id
end as partner_company_id
from deal
where company_first_id in (?) OR d.company_second_id in (?)
) as d
inner join company as c on c.company_id = d.partner_company_id
inner join user as u on u.user_ud = c.user_id

Mysql query, select join two table

I have a LIKE table and a BOOK table and my user_id.
I want to pull only i have liked from BOOK table with BOOK NAMES and AUTHOR
My json will:
{book_id:1,bookname:sample,author:sean,user_id:111}
tables
-----------BOOK TABLE------------
ID ---- BOOK AUTHOR ---- BOOK NAME
1
2
...................................
USERS TABLE
ID-------NAME
1
2
.............
LIKE TABLE---------------------------
ID-----BOOK ID-------LIKER USER ID---
1
2
.....................................
$stmt = $mysqli->prepare("SELECT book.*, users.*, like.* FROM like INNER JOIN
users ON like.liker_user_id = users.id INNER JOIN
book ON like.book_id = book.id WHERE
users.id = ?
");
$stmt->bind_param( "d", $user_id);
$stmt->execute();
$stmt->bind_result($col1);
// then fetch and close the statement
For getting all the data related to likes you can run this sql command.
The result set you can loop and generate the JSON.
Make sure in the query you have all your column names correctly given.
select
b.book_id,
b.bookname,
b.author,
u.user_id
from
`like` l
inner join book b on b.book_id = l.book_id
inner join users u on u.user_id = l.user_id
If you need to filter data just add a where condition after the last JOIN as
where u.user_id = {your user id}

Categories