I am using the following tables:
artists
related_artists
The idea is when I enter an artist's page with an artist_id I can use that id to load related artists. The following code works, but how do I put it in a single query? I can't figure it out.
To connect related_artists with artists I created the following code:
$sql = "SELECT related_artist_id FROM related_artists WHERE artist_id = 1";
$res = mysqli_query($db, $sql);
if (!$res) {
echo "Er is een fout opgetreden.";
exit;
} else {
while ($row = mysqli_fetch_array($res)) {
$query = 'SELECT * FROM artists WHERE artist_id = '.$row["related_artist_id"];
print_r($query."<br />\n");
$result = mysqli_query($db, $query);
if ($result) {
while ($test = mysqli_fetch_array($result)) {
echo $test["lastName"]."<br />\n";
}
} else {
echo "It doesn't work";
exit;
}
}
}
You can just try :
select *
from artists
where artist_id in (
select related_artist_id
from related_artists
WHERE artist_id = 1
);
You can use a LEFT JOIN, try this:
SELECT b.*
FROM related_artist a
LEFT JOIN artists b
USING(artist_id)
WHERE a.artist_id = 1
Should return * from artists, where I aliased artists as b and related_artist as a.
Didn't test, does it work for you / return the expected result?
SELECT * FROM artists where artists.arist_id = 1
INNER JOIN related_artist ON related_artist.artist_id = artists.artist_id
This provides a join on the artist_id columns of both tables, having artist_id = 1. I'm not sure if you need an Inner or a Left join
Related
I have 4 tables:
clients, pricelist, result and result_details
I want to generate a form where the transaction_id, name, test_name and result appear on it. I have done a select for the name but I can't figure out a select for the test_name and result.
I want something like this [pdf][5]
$result=mysqli_query($con,"SELECT r.transaction_Id,r.client_id,r.result_id,r.test_id,t.test_id,t.result,p.test_id,p.Name,c.Id,c.surName,c.firstName,c.dob,c.Gender FROM result r
JOIN result_details t
on r.test_id = t.test_id
left JOIN pricelist p ON r.test_id = p.test_id
left JOIN clients c ON r.client_id = c.Id")or die(mysqli_error());
$r=mysqli_query($con,"SELECT DISTINCT id,firstName,surName,Gender,dob FROM clients join result WHERE result.client_id=clients.Id")or die(mysqli_error());
while ($row = mysqli_fetch_array ($r)) {
$id=$row['id'];
$clientfirstname=$row['firstName'];
$surname=$row['surName'];
$gender=$row['Gender'];
$dob=$row['dob'];
$t=mysqli_query($con,"SELECT transaction_Id FROM transaction WHERE clientId=$id") or die(mysqli_error());
while ($test = mysqli_fetch_array ($t)) {
$transaction=$test['transaction_Id'];
$m=mysqli_query($con,"SELECT test_id,result_id from result where client_id=$id")or die(mysqli_error());
while ($q = mysqli_fetch_array ($m)) {
$test_id=$q['test_id'];
$result_id=$q['result_id'];
$z=mysqli_query($con,"SELECT Name from pricelist where test_id=$test_id")or die(mysqli_error());
while ($x = mysqli_fetch_array ($z)) {
$name=$x['Name'];
$query=mysqli_query($con,"SELECT result from result_details where result_id=$result_id")or die(mysqli_error());
while ($query1 = mysqli_fetch_array ($query)) {
$result=$query1['result'];
}
}
}
}
}
Just add:
GROUP BY AcctNo, OrderDate, Charge
HAVING COUNT(1) = 1
The GROUP BY groups all rows with the same field1, field2, ... and Charge together, then the HAVING COUNT(1) = 1 shows only the rows where there was just 1 progenitor. I hope it will work
I am building a recipe database with some of my friends and for that we need our users to be able to search within our site. Our database consists of 3 tables:
recipes - recipe_id (primary key), recipe_name
ingredients - ingredient_id (primary key), ingredient_name
recipe_ingredients - ingredient_id (foreign key), recipe_id (foreign key)
We want to be able to search the recipe_ingredients for a recipe or ingredient name and have our site show every ingredient connected to that recipe or every recipe connected to that ingredient. And so we made this query:
select ingredient_name, recipe_name, recipe_ingredients.*
from recipe_ingredients
inner join ingredients inner join recipes
on recipe_ingredients.ingredient_id = ingredients.ingredient_id
and recipe_ingredients.recipe_id = recipes.recipe_id
WHERE ingredient_name = 'Brød';
Which works fine for us. However, putting it into our search function in php, it gives 'There were no search results!' back every single time no matter what we searched. Here is the code. Would someone point out the mistake we made?
$output = '';
if (isset($_POST['work'])) {
$searchq = $_POST['work'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query
("select ingredient_name, recipe_name, recipe_ingredients.*
from recipe_ingredients
inner join ingredients inner join recipes
on recipe_ingredients.ingredient_id = ingredients.ingredient_id
and recipe_ingredients.recipe_id = recipes.recipe_id
WHERE ingredient_name LIKE '%searchq%' or recipe_name LIKE '%searchq%'")
or die ("Could not search");
$count = mysql_num_rows($query);
if($count == 0){
$output = 'There were no search results!';
}
else{
while ($row = mysql_fetch_array($query)) {
$recipe = $row[recipe_name];
$ingredient = $row[ingredient_name];
$id = $row[ingredient_id];
$output .= '<div>'.$recipe.' '.$ingredient.'</div>';
}
}
}
We don't understand why it won't work.
You can try the following. It uses mysqli_* functions and a better structure for the query joins.
$connection = mysqli_connect('localhost', 'root', 'your_password', 'your_database');
mysqli_set_charset($connection, 'utf8');
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
$output = '';
if (isset($_POST['work'])) {
$searchq = $_POST['work'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
$sql = "
SELECT ingredient_name, recipe_name, recipe_ingredients.*
FROM recipe_ingredients
INNER JOIN ingredients
ON recipe_ingredients.ingredient_id = ingredients.ingredient_id
INNER JOIN recipes
ON recipe_ingredients.recipe_id = recipes.recipe_id
WHERE ingredient_name LIKE '%$searchq%' or recipe_name LIKE '%$searchq%'";
$result = mysqli_query($connection, $sql);
if (!$result) {
die("SQL Error: " . mysqli_error($connection);
}
$count = mysqli_num_rows($result);
if ($count == 0) {
$output = 'There were no search results!';
} else {
while ($row = mysqli_fetch_array($result)) {
$recipe = $row[recipe_name];
$ingredient = $row[ingredient_name];
$id = $row[ingredient_id];
$output .= '<div>'.$recipe.' '.$ingredient.'</div>';
}
}
}
First - it depends on what version of PHP you are using, as Jens pointed out mysql_* has been deprecated.
Second - it does not appear that you are connecting to your database. You have to connect to your database first, then execute your query.
Check out this example on PHP's website, it should help you out a lot.
Good luck!
It seems like you re searching for "searchq" all the time and you probably dont have a recipe by that name and I would advise agajnst mysql_* funcs
$output = '';
if (isset($_POST['work'])) {
$searchq = $_POST['work'];
$searchq = preg_replace("#[^0-9a-z]#
i","",$searchq);
$query = mysql_query
("select ingredient_name, recipe_name, recipe_ingredients.*
from recipe_ingredients
inner join ingredients inner join recipes
on recipe_ingredients.ingredient_id = ingredients.ingredient_id
and recipe_ingredients.recipe_id = recipes.recipe_id
WHERE ingredient_name LIKE '%
$searchq%' or recipe_name LIKE '%
$searchq%'")
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'
I currently have this query with an array that outputs the variables within using a dynamic input in my form (term), this creates a Dynamic Search with auto complete to fill in all of the details for a product.
$return_arr = array();
$param = $_GET["term"];
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param'");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
//$row_array['category_id'] = $row ['category_id'];
$row_array['product_id'] = $row['product_id'];
$row_array['product_names'] = $row['name_en-GB'];
$row_array['jshop_code_prod'] = $row['product_ean'];
$row_array['_ext_price_html'] = number_format($row['product_price'],2);
if (!empty($row['product_thumb_image']) AND isset($row['product_thumb_image'])){
$row_array['image'] = $row['product_thumb_image'];
}else {
$row_array['image'] = 'noimage.gif';
}
array_push( $return_arr, $row_array);
}
mysql_close($conn);
echo json_encode($return_arr);
Unfortunately I also need to get the category_id which is not in the same table, I have tried to modify my query as such, but to no avail:
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param' AND `crd_jshopping_products_to_categories` = `product_id` ");
What step am I missing here ? The product_id's match in both tables?
try this query instead and try to understand what I have written in it:
$fetch = mysql_query("
SELECT
p.*,
c.category_id
FROM
crd_jshopping_products as p
INNER JOIN crd_jshopping_products_to_categories as c
ON p.product_id = c.product_id
WHERE
`p.name_en-GB` REGEXP '^$param'
");
This means:
SELECT:
Give me everything from p and the category_id from c.
FROM:
Do this from rows in the tables crd_jshopping_products (referred to as p) and crd_jshopping_products_to_categories (referred to as c), where the rows match on the count of p.product_id is the same as c.product_id.
WHERE:
Only return the rows where p.name_en-GB REGEXP '^$param'.
I have managed to create a JOIN query for three tables and can successfully echo out the results in a echoed table, here is my code:
<?php
$sql="SELECT a.product_id, a.Options_id, b.product_name, b.product_price, c.Options_name, c.Price_diff
FROM ProductOptions a
JOIN Products b ON a.product_id = b.product_id
JOIN Options c ON a.Options_id = c.Options_id
ORDER BY product_name DESC";
$result = mysql_query($sql);
if (!$result)
{
echo "An error occurred ".mysql_error();
exit;
}
echo "<table border=1>\n<tr><th></th><th bgcolor=\"#DFE8EC\">Name</th><th>Flavors & Size</th><th bgcolor=\"#DFE8EC\">Price</th><th>Price Difference</th><th bgcolor=\"#DFE8EC\"></th></tr>\n";
while ($line = mysql_fetch_array($result)) {
$name = $line["product_name"];
$price = $line["product_price"];
$options=$line["Options_name"];
$difference=$line["Price_diff"];
echo "<tr><td></td><td bgcolor=\"#DFE8EC\">$name</td><td>$options</td> <td bgcolor=\"#DFE8EC\">£$price</td><td>£$difference</td><td bgcolor=\"#DFE8EC\"></td></tr>\n";
}
echo "</table>\n";
?>
My table works but it shows duplicate entries for product_name and I do not know how to remove them.
You have to use a GROUP BY clause in your query like this:
$sql = "SELECT a.product_id, a.Options_id, b.product_name, b.product_price, c.Options_name, c.Price_diff
FROM ProductOptions a
JOIN Products b ON a.product_id = b.product_id
JOIN Options c ON a.Options_id = c.Options_id
GROUP BY product_name
ORDER BY product_name DESC";