php mysql join query - php

I need to pull data from 2 tables in my database. The data I pull from table 2 depends on the result of table 1.
I'm not amazing at all these JOINS and things, so if someone could just explain what kind of a JOIN i'd need here, and how it would look, i'd be grateful:
$sql_result = mysql_query("SELECT * FROM accounts WHERE id='$val'", $db);
$rs = mysql_fetch_array($sql_result); $name = $rs[name];
$sql_result2 = mysql_query("SELECT * FROM players WHERE name='$name'", $db);
$rs2 = mysql_fetch_array($sql_result2);

$sql="SELECT * FROM accounts JOIN players ON accounts.accounts_link_to_player_id_here=players.id WHERE accounts.id='$val'";

You can do something like this, depending on the structure of the table(s):
SELECT * FROM `accounts` INNER JOIN `players` USING (`name`) WHERE `accounts`.`id` = 'value';

SELECT * FROM accounts LEFT JOIN players USING (name) WHERE accounts.id = 'value';

You'll need a query that looks like this (this is known in SQL as a subselect):
"SELECT p.* FROM players p WHERE name IN ( SELECT n.name FROM accounts n WHERE n.id = '$val' )"

Related

How to JOIN MySQL tables with specific ID of each table with PHP

I don't know how to join tables and fetch informations from each of them. I have clients, who has made reservations and when I click on specific client I need not only information about him from clients table, but also need information related to him by id from reservations table.
This is my ER diagram for better database understanding:
In the overview table of all reservations, based on its status I am using this query:
<?php
$query = $conn->query("SELECT * FROM `reservations` NATURAL JOIN `clients` NATURAL JOIN `houses` WHERE `status` = 'Pending' ORDER BY firstName")
or die(mysqli_error());
hile($fetch = $query->fetch_array()){
?>
It works perfectly fine, but now I need to display the reservations related only to the specific user I clicked on via link based on ID, example:
<td> <a href = "./Client-Detail.php?client_id=<?php echo $fetch['client_id']?>">
<?php echo $fetch['firstName']." ".$fetch['lastName']?></a></td>
I am not quite sure the right way how to display the reservation data of specific client.
You need to put the client_id check in the WHERE clause instead of checking status.
$stmt = $conn->prepare("
SELECT *
FROM `reservations`
NATURAL JOIN `clients`
NATURAL JOIN `houses`
WHERE client_id = ?");
$stmt->bind_param("i", $_GET['client_id']);
$query = $stmt->execute();
while ($fetch = $query->fetch_array()) {
...
}
SELECT r.*, c.*, h.*
FROM `reservations` r
LEFT JOIN `clients` c ON (c.client_id = r.client_id)
LEFT JOIN `houses` h ON (h.house_id = r.house_id)
WHERE r.status = 'Pending' AND c.client_id = '$0'
ORDER BY c.firstName ASC
This should work and bind ID via PDO or MySQLi

Is there a better way to get info from 2 tables

In database the users have a row called weapon_id which determines what weapon he uses from another table with weapons.
Is there a better way to get that info like join table or something?
$user_get = mysqli_query($db, "SELECT * FROM members WHERE id = '".$_SESSION['sess_id']."'");
$user = mysqli_fetch_assoc($user_get);
$weapon_get = mysqli_query($db, "SELECT * FROM weapons WHERE weapon_id = '".$user['weapon_id']."'");
$weapon = mysqli_fetch_assoc($weapon_get);
use a join like this
$user_get = mysqli_query($db, "SELECT * FROM members m LEFT JOIN weapons w ON(w.weapon_id=m.weapon_id) WHERE m.id = '".$_SESSION['sess_id']."'");
$user = mysqli_fetch_assoc($user_get);
change the join type as per your requirement. the above query for only example
INNER JOIN: Returns all rows when there is at least one match in BOTH
tables
LEFT JOIN: Return all rows from the left table, and the matched rows
from the right table
RIGHT JOIN: Return all rows from the right table, and the matched
rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
more about join click here
AND also check this http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/
SELECT * FROM `weapon` as w
JOIN `user` as u
on w.weapon_id = u.weapon_id
and u.id = :session_id
How about this ?

mysql inner join query where id is obtained from $_GET['id']

I have two tables firm and contactdetails. I am trying to get the the firm name from firm and certain contact details from contactdetails. I am using $id =$_GET['id']; to get the id . In contactdetails i have fk_firm_id which is my foreign key. I am not sure how to use the inner join query. I am trying the following query:
$sql="SELECT firm.`name` ,`address_physical_line_1` , `fax_1` , `phone_1`
FROM contactdetails JOIN firm ON contactdetails.fk_firm_id='$id'";
echo $sql;
$result = mysql_query($sql);
but i am not getting the correct firm. Can anyone help me with this query, please.
You should use like this JOIN firm ON contactdetails.fk_firm_id = firm.id
$sql=" SELECT firm.`name` ,`address_physical_line_1` , `fax_1` , `phone_1`
FROM contactdetails
JOIN firm ON contactdetails.fk_firm_id = firm.id
WHERE contactdetails.fk_firm_id = '$id'
";
$result = mysql_query($sql);
This is assuming that your firm table has a primary key called id
$sql="SELECT firm.`name` ,`address_physical_line_1` , `fax_1` , `phone_1` FROM contactdetails JOIN firm ON `contactdetails`.`fk_firm_id`=`firm`.`id`
WHERE `firm`.`id` = '$id'";
echo $sql;
$result = mysql_query($sql);
There is a mistake about JOIN and WHERE statements:
$sql = "SELECT
f.name,
c.address_physical_line_1,
c.fax_1,
c.phone_1
FROM
contactdetails c JOIN firm f ON c.fk_firm_id= f.id
WHERE c.id = '$id'";
$sql="SELECT firm.`name` ,`address_physical_line_1` , `fax_1` , `phone_1` FROM
contactdetails JOIN firm ON contactdetails.fk_firm_id=firm.id where
contactdetails.fk_firm_id='$id'";
you should join on a firm's field such as firm.id
syntax: FROM table1 LEFT JOIN table2 ON table1.field1 compopr
table2.field2 compopr is : "=","<",">","<=",">=","<>"
You are missing the WHERE clause that limits the result set to only the firm you're interested in; now you're getting all firms joined with a single contact details record.
.. where firm.id=$id
For new applications, please use a database API that has prepared statements, like mysqli or pdo.
Use the following query for inner join
$sql="SELECT firm.name ,address_physical_line_1 , fax_1 , phone_1 FROM
contactctdetails INNER JOIN firm ON contactdetails.fk_firm_id=$id";

Nested queries syntax improvement

What's the correct syntax to achieve this using 1 query instead of 2?
$result = mysql_query(SELECT * FROM users);
while($row = mysql_fetch_array($result)){
$result = mysql_query(SELECT SUM(balance) FROM users_account WHERE uid=$row[id]);
}
You should inner join both tables and group by user table.
You can add more columns in SELECT clause, remember to add also same columns to GROUP BY clause to get a standard SQL statement.
$query = " SELECT u.uid, SUM(a.balance)
FROM users_account a
INNER JOIN users u
ON u.uid = a.uid
GROUP BY u.uid";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
...
Arrange $query concatenating strings if needed.
This will return all records form user_account table with user info :-
SELECT SUM(ua.balance),u.*,ua.* FROM users_account ua
left join users u on ua.users_account=u.id
GROUP BY u.id
$result = mysql_query(SELECT a.*, b.SUM(balance) AS user_balance FROM users a, users_account b WHERE uid=$row[id]);

php sql count from 3 tables

I need to get a count from a table, based on data from 2 other tables.
This is my tables structure:
table1 (id, name)
table2 (id, a, b, c)
table3 (id, blah)
Can i do it all in one statement? Something like this:
SELECT count(*) from table3 WHERE table2.x=table1.name
The hard part is the x column is the name of 'table1.name'. So i dont actually know what x is when im running the statement.
This makes me think i'd have to run a statement to find the name of x before i run this one.
Or... maybe some JOIN?
CURRENT CODE WHICH I USE:
if ($rs[firearm] != "") {
$sql_result2 = mysql_query("SELECT * FROM db_firearms WHERE name='$rs[firearm]'", $db);
$rs2 = mysql_fetch_array($sql_result2);
$sql_result3 = mysql_query("SELECT * FROM items_firearms WHERE player='$id'", $db);
$rs3 = mysql_fetch_array($sql_result3);
if ($rs3[$rs2[shortname]] < 1) {
mysql_query("UPDATE players SET firearm = '' WHERE id ='$id'");
}
}
Yeah, sounds like joins will be necessary.
SELECT count(*) AS num_rows
FROM table3
LEFT JOIN table1.name ON table1.name = table3.name
INNER JOIN table2 ON table2.x = table1.name

Categories