One query instead of two? - php

Here I'm making two queries with PHP. Is there something more simple? One query instead of two?
$id = mysql_real_escape_string($_GET["id"]);
$result = mysql_query("SELECT * FROM questionstable WHERE id=$id");
$row = mysql_fetch_assoc($result);
$category = $row['category'];
$main = mysql_query("SELECT name FROM categorytable WHERE id=$category");

SELECT questionstable.*, categorytable.name
FROM questionstable
INNER JOIN categorytable
ON categorytable.id = questionstable.category
WHERE questionstable.id=$id
As an aside, assuming your questionstable.id is numeric, you could use $id = (int)$_GET["id"] and save some writing. (It's also probably a safer bet. Just because it's escaped doesn't mean it's completely safe--especially when it's not within quotes [gives you a LOT of options for SQL injection]. ;-))

Please try:
SELECT name
FROM categorytable
WHERE id = (
SELECT category
FROM questionstable
WHERE id = $id
)

$id = mysql_real_escape_string($_GET["id"]);
$main = mysql_query("SELECT c.name FROM categorytable c inner join questionstable q on c.category = q.category WHERE q.id = $id");

Do not use inner join use left join instead, it won't return any result if the category is not found
SELECT questionstable.*, categorytable.name
FROM questionstable
LEFT JOIN categorytable
ON categorytable.id = questionstable.category
WHERE id=$id

Related

Use INNER JOIN / JOIN for multiple query

What I have at the moment is to match the case from law_case, as in the database scheme below.
My code:
$query1 = "SELECT * FROM law_case WHERE id =?";
$query1vals = array($_GET['id']);
$ids = $adb->selectRecords($query1, $query1vals, false);
$a = $ids['case_type_id'];
$b = $ids['funding_pref'];
#
$query2 = "SELECT type_name FROM case_type WHERE id =?";
$query2vals = array($a);
$ids1 = $adb->selectRecords($query2, $query2vals, false);
$d = $ids1['type_name'];
#
$query3 = "SELECT * FROM expertise WHERE expertise_desc =?";
$query3vals = array($d);
$ids2 = $adb->selectRecords($query3, $query3vals, false);
$c = $ids2['id'];
#
$query4 = "SELECT * FROM individual_expertise WHERE expertise_id =?";
$query4vals = array($c);
$ids3 = $adb->selectRecords($query4, $query4vals, false);
$e = $ids3['individual_id'];
#
$query5 = "SELECT * FROM individual WHERE id =?";
$query5vals = array($e);
$ids4 = $adb->selectRecords($query5, $query5vals, false);
$f = $ids4['network_member_id'];
#
$query6 = "SELECT * FROM network_member WHERE id =?";
$query6vals = array($f);
$ids5 = $adb->selectRecords($query6, $query6vals, false);
And what it does is it only gets one network_member.
I want to use INNER JOIN, JOIN or LEFT JOIN and use a while looking to get the different member_name and the URL for each network_member or who's individual has the same expertise_id from the individual_expertise table.
I'm new to JOIN and tried this code but it doesn't work:
$sql = "SELECT member_name, url
FROM individual_expertise
LEFT JOIN individual
USING (individual_id)
LEFT JOIN network_member
USING (network_member_id)
WHERE expertise_id = ?";
$ids3 = $adb->selectRecords($sql, $query4vals, false);
echo $ids3['member_name'];
You need to get an overview of JOIN types. You have to build a query using INNER, LEFT, RIGHT, FULL joins depending on your logical requirements. You can assume that INNER join is equal to && or AND operators in conditional statements, I mean records must match in both tables.
While, LEFT join will return all rows from left table of join and matched rows from right table of join. And RIGHT is inverse of LEFT.
And FULL join is an example of || or OR in operators in conditional statements. I mean either a match in both tables.
So you have to join depending on logic you require.
See here
Do you know the difference between INNER JOIN and LEFT JOIN? I think you don't. You need an INNER JOIN here.
I think this is the right solution for your question:
SELECT
network_member.member_name,
network_member.url
FROM
network_member
INNER JOIN
individual ON individual.network_member_id = network_member.id
INNER JOIN
individual_expertise ON individual_expertise.individual_id = individual.id
WHERE
individual_expertise.expertise_id = ?

php pdo where clause

I have the following code for selecting from multiple tables where the order number matches.
$orderNumber = $_GET['orderNumber'];
$sql = $db->prepare("
SELECT
*
from `KC_Orders`
INNER JOIN
`KC_Payments`
on KC_Orders.orderNumber = KC_Payments.orderNumber
INNER JOIN
`KC_OrderStatus`
on KC_Orders.orderNumber = KC_OrderStatus.orderNumber
INNER JOIN
`KC_Statuses`
on KC_OrderStatus.statusID = KC_Statuses.statusID
WHERE
orderNumber= :orderNumber");
$sql->execute(array(':orderNumber' => $orderNumber));
$orderInfo = $sql->fetchAll();
Now when I var_dump($orderInfo); it returns: array(0) { } What is wrong? All the tables include the same $orderNumber field within it. If I take the WHERE part out it works just fine except it returns every row not just one. (obviosly).
Please help us!
You need to specify what the OrderNumber is from, and the * is from (what table). So try this new code:
$sql = $db->prepare("SELECT KC_Orders.* from `KC_Orders` INNER JOIN `KC_Payments` on KC_Payments.orderNumber = KC_Orders.orderNumber INNER JOIN `KC_OrderStatus` on KC_OrderStatus.orderNumber = KC_Order.orderNumber INNER JOIN `KC_Statuses` on KC_Statuses.statusID = KC_OrderStatus.statusID WHERE KC_Orders.orderNumber= :orderNumber");
Ordernumber in where clause should have table prefix if it exists in multiple tables
Try this
$orderNumber = (int)$_GET['orderNumber'];
Then where :ordernumber is put $orderNumber
Then execute

SQL Error when trying to JOIN tables

I'm trying to run this query:
$query = $conn->query("SELECT * FROM $table
LEFT JOIN vacatures ON bedrijven.id = vacatures.id
WHERE id = '$id'
AND bedrijfID = '$bedrijf_id'");
But it fails for some reason. I get this error.
Syntax error or access violation: 1066 Not unique table/alias
When I leave the JOIN part, the query is succesful. Why is this happening?
I'm using PHP & PDO to fetch the queries.
Thanks.
EDIT: I wrote the query thanks of the answers given. This is working:
$query = $conn->query("SELECT * FROM bedrijven
LEFT JOIN vacatures v ON bedrijven.id = v.bedrijfID WHERE v.bedrijfID = $bedrijf_id AND v.id = $id");
You need to specify one table or the other in WHERE id = '$id', even though they're equal to each other in this case.
You also need to make sure your LEFT JOIN includes $table:
$query = $conn->query("SELECT * FROM $table
LEFT JOIN vacatures ON $table.id = vacatures.id
WHERE $table.id = '$id'
AND bedrijfID = '$bedrijf_id'");
or:
$query = $conn->query("SELECT * FROM bedrijven
LEFT JOIN vacatures ON bedrijven.id = vacatures.id
WHERE bedrijven.id = '$id'
AND bedrijfID = '$bedrijf_id'");
Your question isn't super clear, but if you're just trying to do a simple join where the id on table 1 = id on table 2, then the below statement would work. If that's what you're attempting to do, then the AND statement is redundant. Hard to know what you're going for without a clearly defined question with clearly defined variables. Also, use prepared statements as shown below rather than inserting variables directly into your statement. And avoid SELECT * whenever possible. Only select what is absolutely necessary.
$query = $conn->prepare("SELECT * FROM bedrijven b
LEFT JOIN vacatures v
ON b.id = v.id
WHERE v.id = :id");
$query->bindValue(':id', $id);
$query->execute();
The '$id' will be treated as string not as variable.and you need to specify the id as table.id if both of the tables have a field called id.
$query = $conn->query("SELECT * FROM $table LEFT JOIN vacatures ON bedrijven.id = vacatures.id WHERE $table.id = $id AND bedrijfID = $bedrijf_id");

PHP/MySQL INNER JOIN Triples the amount of rows?

I have a system where I getting images out of my database, but when it does that, there is 3x of the same images.
I have tried with different ways, DISTINCT and such, but I have no clue how I fix this.
Here is my query code:
<?php
$id = $_GET['id'];
$query = "SELECT DISTINCT * FROM billeder INNER JOIN album ON fk_album_ID = $id";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($result))
{
$thumb_src = 'billeder/thumb_'.$row['billeder_sti'];
$full_src = 'billeder/'.$row['billeder_sti'];
echo "
<div class='ikon'>
<a href='$full_src'>
<img src='$thumb_src' alt='' />
</a>
</div>
";
}
?>
Hope someone can help me on the way to fix this :)
Without being able to see your table structure I won't be able to give an exact answer but the likely reason is because your INNER JOIN is not setup correctly.
SELECT DISTINCT *
FROM billeder
INNER JOIN album
ON (billeder.fk_album_ID = album.pk_album_ID)
WHERE
billeder.fk_album_ID = $id
Something like the above would be the correct way to JOIN a table and using a WHERE clause to then limit the date received.
JOIN must be used with two tables columns. See example:
SELECT * FROM tableA a INNER JOIN tableB b ON a.id = b.a_id;
What you're trying to make is something like this:
"SELECT DISTINCT * FROM billeder INNER JOIN album ON
billeder.fk_album_ID = album.album_id WHERE billeder.id = $id"
You shouldn't pass an argument to the JOIN. The arguments must be used on the WHERE clause.

Joining two tables to get a count

I am attempting to count comments on a particular page with the following problematic sql query:
$query = "SELECT * FROM `comments` WHERE is_approved = '1' AND page_id = '943'"
$query = mysql_query($query);
$total = mysql_num_rows($query);
echo $total;
the problem is it is outputting 0 and not 2.
The tables are as follows:
pages:
id:1 page_id:943
id:2 page_id:978
id:3 page_id:977
comments:
id:2 page_id:1 "hello"
id:3 page_id:1 "great"
id:4 page_id:3 "super"
So really the original query should be getting each comment's true page_id from the page_id as set in the pages tables, as joined by comments.page_id = pages.id
What would the final code look like to either make that join, and/or get that count? Thank you.
Try:
SELECT c.* FROM `comments` c
JOIN `pages` p on c.page_id = p.id
WHERE c.is_approved = '1' AND p.page_id = '943'
"SELECT * FROM comments, pages WHERE comments.page_id = pages.id AND is_approved = '1' AND comments.page_id = '943'"
Try using:
SELECT count(*) as cnt
FROM `comments` c join pages p on c.page_id = p.id
WHERE c.is_approved = '1' AND p.page_id = '943'
It seems like a very poor database design to have two columns with the same name in different tables that mean different things. You should probably change the name of pages.page_id to something else.
And, this returns the count directly, so you can read the value from the row. If you just want the count, there is no reason to return all the matching rows.
no join is needed:
$query = "SELECT * FROM `comments` WHERE is_approved = '1' AND WHERE page_id IN (SELECT id WHERE page_id = '943')"
$query = mysql_query($query);
$total = mysql_num_rows($query);
echo $total;
ofcourse i would suggest a count statement if you do not need/use the data:
$query = "SELECT COUNT(*) as total FROM `comments` WHERE is_approved = '1' AND WHERE page_id IN (SELECT id WHERE page_id = '943')"
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$total = $row['total'];
echo $total;

Categories