Get data from two different tables in the same query - php

I'm starting to learn php. I'm able to extract the list of CD from the SQL query in [in this table][1] but there's another query which contains the Category which is linked via ID in this table.
How do I get all the columns in the same result set using one query?
<?php
include 'database_conn.php';
$sql = "SELECT id, title, year, price FROM table_cd";
$queryresult = mysqli_query($conn, $sql)
or die (mysqli_error($conn));
while($row = mysqli_fetch_assoc($queryresult)) {
$iid = $row['id'];
$title = $row['title'];
$year = $row['year'];
$price = $row['price'];
echo "<div>
$title
</div>\n";
echo $row['year'];
echo $row['price'];
}
?>
editCDForm.php:
<?php
$code = $_GET['itemCode'];
$sql = "SELECT * FROM table_cd WHERE table_category.ID = $code
JOIN table_category ON (table_category.Desc = table_cd.ID)";
?>

What you're looking for is called a JOIN which allows you to merge the rows from two or more tables into the same result set.
You can modify your query as illustrated below, by using a LEFT JOIN of the nmc_cd table and the nmc_category table on the catID column, as the common primary attribute between them, giving you the desired result set...
$sql = "SELECT nmc_cd.CDID, nmc_cd.CDTitle, nmc_cd.CDYear,
nmc_cd.CDPrice, nmc_category.catDesc
FROM nmc_cd
JOIN nmc_category on nmc_cd.catID = nmc_cd.catID";
Here's a nice article that may help you visualize what a JOIN looks like in your SQL.
Syntax for joins:
SELECT * FROM table1
JOIN table2 ON (table2.colunmname = table1.columnname)

use can get the data from both tables when joining them:
$sql = "SELECT FT.CDID, FT.CDTitle, FT.CDYear, FT.CDPrice,
ST.catDesc FROM nmc_cd AS FT LEFT JOIN nmc_category as ST ON
FT.catID=ST.catID";

Related

1 JSON object, 2 queries, 2 tables

Here is my simple query:
$sql = "SELECT * FROM donations Order By userid";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()){
$json[] = $row;
}
$data['data'] = $json;
I use it to display all data from the 'donations' in a table. Fields are: userid,date,amount.
In that same table, I'd like to add firstname and lastname of corresponding userid which are stored in mymembers table. The condition should be WHERE donations.userid = mymembers.id.
I need help adding that condition for every row resulting from the $sql query.
Use join and change query to
SELECT * FROM donations
INNER JOIN mymembers on (donations.userid = mymembers.id)
Order By donations.userid

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";

join more than tables in json

I have problem when I want to display data by json file. If I display data in one table it is ok, but when I want to join more than tables no data displayed
<?php
mysql_connect($hostname,$username, $password) or die ("<html><script language='JavaScript'>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script></html>");
mysql_select_db($dbname);
$query = "SELECT Product.Product_Name, Product.Price, Product.Image, Gender.Description, Age.Description, Status.Availability from Product join Age on Age.Age_ID join Gender on Gender.Gender_ID join Status on Status.ID";
$result = mysql_query($query);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['Product_Name'] = $row['Product_Name'];
$row_array['Price'] = $row['Price'];
$row_array['Image'] = base64_encode($row["Image"]);
$row_array['Description'] = $row['Description'];
$row_array['Description'] = $row['Description'];
$row_array['Availability'] = $row['Availability'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db)
?>
Your last join on Status.ID is the issue. Status table doesn't have ID column. Based on you diagram, you have Status.Status_ID (you don't have Status.ID) Also, your data have to have related data where each table has values in common, otherwise, you will get empty results
Your Diagram:
Change your Query
SELECT
Product.Product_Name,
Product.Price,
Product.Image,
Gender.Description,
Age.Description,
Status.Availability
FROM
Product
JOIN
Age ON Age.Age_ID
JOIN
Gender ON Gender.Gender_ID
JOIN
Status ON Status.ID
to
SELECT
Product.Product_Name,
Product.Price,
Product.Image,
Gender.Description,
Age.Description,
`Status`.Availability
FROM
Product
JOIN
Age ON Product.Age_ID = Age.Age_ID
JOIN
Gender ON Product.Gender_ID = Gender.Gender_ID
JOIN
`Status` ON Product.Status_ID = `Status`.Status_ID

Combine sub query with multiple results into one

How can I achieve the following using only one database query?
$query = "SELECT `email`, `name` FROM `customers`";
$result = mysqli_query($link,$customer_query);
while($row = mysqli_fetch_array($result)){
echo "<p>".$row['name']."</p>";
echo "<ul>";
$query2 = "SELECT `sku` FROM `orders` WHERE `email` = '".$row['email']."'";
$result2 = mysqli_query($link,$query2);
while($row2 = mysqli_fetch_array($result2)){
echo "<li>".$row2['sku']."</li>";
echo "<li>".$row2['cost']."</li>";
}
echo "</ul>"
}
Use INNER JOIN on email field for this:
SELECT c.name, o.sku, o.cost FROM customers c INNER JOIN orders o ON o.email = c.email
Don't forget to add MySQL INDEX on email field for performance.
But this only select customers which have orders.
If you need to select all customers (even which does not have orders) use LEFT JOIN instead. In this case sku and cost fields for users without orders will be null.
Use this picture as hint for this.

How to Get another value in another table using a dynamic call

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'.

Categories