Join two MySQL tables with PHP - php

For example, I have created two pages and two MySQL tables.
Index.php & citys.php
citys
ID City Country Population
--------------------------------------
1 Amsterdam NL 1500000
2 Rotterdam NL 900000
3 Dusseldorf DE 1800000
comments
ID City Name Comment
---------------------------------
1 Dusseldorf Jack Great city!
2 Dusseldorf John Beautiful
3 Rotterdam Emy Love it
At the moment I only use the table citys like this:
index.php linking to citys.php with:
<a href='citys.php?cmd=menu&id=";echo $row['id'];echo "'>
And citys.php use this code to show the data from MySQL:
<?php
include "connect.php";
if(!isset($cmd))
{
if($_GET["cmd"]=="menu" || $_POST["cmd"]=="menu")
{
if (!isset($_POST["submit"]))
{
$id = $_GET["id"];
$sql = "SELECT * FROM citys WHERE id=$id";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
?>
<?php echo $row["City"] ?>
<br><br>
<?php echo $row["Country"] ?>
<br><br>
<?php echo $row["Population"] ?>
Until here everything is showing up and working fine.
But I also want to show the comments on page 2. So the query has to be edited to also get the right data from the table comments.
I tried different examples from internet that I have edited myself like:
<?php
include "connect.php";
if(!isset($cmd))
{
if($_GET["cmd"]=="menu" || $_POST["cmd"]=="menu")
{
if (!isset($_POST["submit"]))
{
$id = $_GET["id"];
$sql = "SELECT citys.*, comments.* FROM citys, comments WHERE citys.id=$id AND comments.city=citys.city";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
?>
But nothing works.
How can I fix this?
The query from VIPIN JAIN's answer works, but there is one problem left:
Query:
$sql = "SELECT * FROM citys LEFT JOIN comments ON comments.city=citys.city WHERE citys.id=$id";
If the table 'comments' has three rows, this code shows only the last two but not the first:
<?php
while($row = mysql_fetch_array($result)) {
echo "<br><br>";
echo $row['name'];
echo "<br>";
echo $row['comment'];
}
?>
And if I try this it only shows the first row.
<?php echo $row["name"] ?>
<br>
<?php echo $row["comment"] ?>
I don't know why the first record is left away in the loop.

Use this query
$sql = "SELECT * FROM citys LEFT JOIN comments ON comments.city=citys.city WHERE citys.id=$id";
Use leftjoin for this type of work

select * from citys
left join comments on comments.city = citys.city
where citys.id=$id

Related

Show records in the table with if - PHP

I have a plant table and a customer campaign table, I want to show only plants that are not associated with the customer campaign table.
through this if cycle, I would like to get a solution like if it is true not to show the plants that are associated if and it is false shows the plants that are not associated
it's possible?
<?php
session_start();
include 'connessione.php';
$var = true;
$var = 1;
$query = mysqli_query($connessione, "
SELECT *
FROM store_locator
INNER JOIN campagne_cliente
ON store_locator.id = campagne_cliente.impianto_id_campagna");
if (!$query)
{
die('Error: ' . mysqli_error($connessione));
}
if($var === true){
echo "email already exists";
}else{
echo "ok";
}
?>
but if i have only plants associated and nothing plants free i have always ok.
Why?
Correct:
<?php
session_start();
include 'connessione.php';
$id = $_SESSION['id'];
$query_string = "SELECT * FROM store_locator WHERE store_locator.id NOT IN (SELECT impianto_id_campagna FROM campagne_cliente);
";
$query = mysqli_query($connessione, $query_string);
?>
<?php
while($row = mysqli_fetch_assoc($query)){ ?>
<?php echo $row['id'] ;?>
<?php } ?>
USE NOT IN QUERY LIKE THIS....
AM Just Try to understand you,you can manage it according to your table structure.
SELECT * FROM `plant_table` not in (select customer_campaign.plant_id from customer_campaign);
Hope This will Help You.
Thanks
I got this result:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'not in (select campagne_cliente.impianto_id_campagna from campagne_cliente)' at line 2
this is a query:
SELECT * FROM `store_locator`
not in
(select campagne_cliente.impianto_id_campagna
from campagne_cliente);

News comments count

I'm tired of searching for the solution my news comment system.
What i have.
I have 2 different mysql tables item (id, title, category_id, details) and comments (id, item_id, comment)
If i have single news then counting is fine like here in picture:
Single news
Code:
if (!empty($comments)) {
$comm = count($comments);
} else {
$comm = 0;
}
But if i use same code category view, result is:
Category view
If i use code:
$sqls = mysql_query("SELECT c.item_id,
COUNT(c.comment)
FROM comments c
RIGHT JOIN items i
ON c.item_id = i.id
GROUP BY c.item_id");
$comm = mysql_num_rows($sqls);
$smarty->assign('comm',$comm);
Result is :Some number of comments
How to make possible to see the Category View the correct number of comments?
TRY this example. The result is the same as the screenshot below but with some background colour to distinguish the difference. Of course you should change to your own connection and layout.
<?php
$db = new PDO('sqlite:news.db');//change to your own
$sql = $db->prepare("
SELECT item.id, item.title, item.details, comments.comment, COUNT(comments.id) AS NumberOfComment
FROM item LEFT JOIN comments ON item.id = comments.item_id
GROUP BY item.id ORDER BY item.id");
$sql->execute();
$row = $sql->fetchAll();
//get comment
$comment = $db->prepare("SELECT comment FROM comments WHERE item_id = ?");
foreach ($row as $rows){
echo "<br>";
echo "Title: ".$rows['title'];
echo "<br>";
echo "Details: ".$rows['details'];
echo "<br>";
echo "<i>".$rows['NumberOfComment']." comments </i>";
echo "<br>";
$comment->execute(array($rows['id']));
$comments = $comment->fetchAll();
echo '<div style="background-color:pink;">';
foreach ($comments as $showcomment){
echo $showcomment['comment'];
echo "<br>";
}
echo "</div>";
echo "<br>";
}
?>
example item table
example comment table
and the result is...

showing relating records in website using mysql / php

Sorry for my lack of experience, but I try to explain my goal the best a can...
I have 2 MySQL tables with the following fields...
tbl_cars_clients
FIELDS
"client_name,
logo_img,
phone,address,email"
tbl_cars_items
FIELDS
"car_name,
client_name,cars_img"
I have a main page called index.php that contains the following code
$query_cake = mysql_query("select * from tbl_cars_clients", $connection);
while ($row = mysql_fetch_array($query_cars)) {
echo "<img class='img' src={$row['ad_img']} width='350px' height='225px'>";
I have another page called items-cars.php
<?php
if (isset($_GET['id'])) {
$client_id = $_GET['id'];
$query1 = mysql_query("SELECT * FROM tbl_cars_items WHERE client_name = '$client_id'", $connection);
while ($row1 = mysql_fetch_array($query1)) {
?>
<?php echo "$row1['cars_img']} width='250px' height='250px'>";?>
On index.php, When I click on any of these Image hyperlinks, it opens items-cars.php and only display records with the same client_name field from the 2 tables.
My goal is to not only show the relating records on items-cars.php, but to display the records from the tbl_cars_clients table.
EXAMPLE: If I click image hyperlink for TOYOTA on index.php, It currently opens up the following records on items-cars.php...
COROLLA,
PRIUS,
CAMRY,
TUNDRA,
Instead, I would like it to display results like...
TOYOTA
888-123-4567
123 Maple Dr.
info#toyota.com
COROLLA,
PRIUS,
CAMRY,
TUNDRA,
i think you want this...
<?php
if (isset($_GET['id'])) {
$client_id = $_GET['id'];
$query1 = mysql_query("SELECT * FROM tbl_cars_items WHERE client_name = '$client_id'", $connection);
while ($row1 = mysql_fetch_array($query1)) {
$query2 = mysql_query("SELECT * FROM tbl_cars_clients WHERE client_name = '$client_id'", $connection);
$row2 = mysql_fetch_array($query2);
?>
<?php echo $row2['client_name']; ?><br />
<?php echo $row2['phone']; ?><br />
<?php echo $row2['address']; ?><br />
<?php echo $row2['email']; ?><br />
<?php echo "$row1['cars_img']} width='250px' height='250px'>";?>
}

Need to combine 2 tables

Taking a deep breath, really don't know how to combine 2 tables from my MySQL,
I will show you the tables which I've and the rows which needed to be combinated.
Table called post:
As you see cat means Category, which category it is (see below category table nameID is same as cat here)
For example my page www.site.com/category.php?nameid=NAMEID(table category)&id=ID(table post) Need to be combined so if I go to ?nameid=1&id8 the page should be blanc or giving an error since id=8 is category 2 and not 1.
// BEGIN OF SHOWING CONTENT PAGE
if (isset($_GET['id'])){
$naamID = mysql_real_escape_string($_GET['nameID']);
$id = mysql_real_escape_string($_GET['id']);
$idnext = $id + 1;
$gn = (" SELECT * FROM category WHERE nameID='".$naamID."'") or die(mysql_error());
$go = (" SELECT * FROM post WHERE id='".$id."'") or die(mysql_error());
$gnn = mysql_query($gn) or die(mysql_error());
$goo = mysql_query($go) or die(mysql_error());
$gnnn = mysql_fetch_array($gnn);
$gooo = mysql_fetch_array($goo);
if(empty($gooo['youtube'])){
} else {
?> <h2> <?php echo htmlspecialchars($gooo["title"]); ?> </h2><br />
<?php
echo '<iframe width="560" height="315" src="//www.youtube.com/embed/'.$gooo["youtube"].'" frameborder="0" allowfullscreen></iframe><br />';
}
if(empty($gooo['pic'])){
} else {
?> <h2> <?php echo htmlspecialchars($gooo["title"]); ?> </h2><br />
<?php
echo '<img src="'.$gooo["pic"].'"/>';
}
}
?>
SELECT table1.keyid FROM table1
UNION
SELECT table2.keyid FROM table2
i wish this example help you ,try to understand how to combine 2 tables
I think i don't understand need of passing categid, as post id itself looks like primary key, so you must able to fetch particular post record, and can retrieve name of that category which is linked with requested post using something like(you just need to pass post id in parameter)
SELECT youtube,title,c.name,pic FROM post p
INNER JOIN categories c
ON c.nameid=p.cat
WHERE p.id=2
If you are trying to get requested post record along with all posts from requested category than you can write query like
SELECT youtube,title,c.name,pic
FROM post
INNER JOIN categories c
ON c.nameid=p.cat
WHERE (p.id=8 or cat=2)
Hope this will help!
Thanks
Suresh
Update:
Based on what I understood, following code snippet may solve your problem
$row = mysql_query("SELECT p.cat, c.nameID FROM post p INNER JOIN category c ON p.cat = c.nameID WHERE p.cat = '".$id."' AND c.nameID = '".$naamID."' LIMIT 1");
if(mysql_num_rows($row)==0)
{
echo("This post doesn't exist on this category")
}
Update 2:
<?if (isset($_GET['id']))
{
$naamID = mysql_real_escape_string($_GET['nameID']);
$id = mysql_real_escape_string($_GET['id']);
$row1 = mysql_query("SELECT p.cat, c.nameID FROM post p INNER JOIN category c ON p.cat = c.nameID WHERE p.cat = '".$id."' AND c.nameID = '".$naamID."' LIMIT 1");
if(mysql_num_rows($row1)==0)
{
echo("This post doesn't exist on this category");
}
else
{
$idnext = $id + 1;
$gn = (" SELECT * FROM category WHERE nameID='".$naamID."'") or die(mysql_error());
$go = (" SELECT * FROM post WHERE id='".$id."'") or die(mysql_error());
$gnn = mysql_query($gn) or die(mysql_error());
$goo = mysql_query($go) or die(mysql_error());
$gnnn = mysql_fetch_array($gnn);
$gooo = mysql_fetch_array($goo);
/*--------------your other display code when data is available-------------*/
}
}
?>

Displaying items from multiple tables on your webpage using php while loop

I am trying to dsiplay data from 2 different tables from my mysql database using a while loop.
Currently I can display the data from 1 table and limit the results to 3. I then want to display the first 5 records from another table. If I join the tables I can only display the same number of items from both using LIMIT?
I am using a while loop to display the content from a table called item, using the following code;
$query");
$result2 = #mysql_query($query, $connection)
or die ("Unable to perform query$query");
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['item'] ?>
<?php
}
?>
If I start another loop for the data from the next table called movie, however the data is not displayed using the following code;
<?php
while($row= mysql_fetch_array($result2))
{
?>
<?php echo $row['title'] ?>
<?php
}
?>
What is the best way to display the data from the 2 tables?
Many Thanks
I don't know if you forgot to paste a bit of code, but this should work:
<?php
$query = "select * from item order by date, time asc limit 0,3";
$result = mysql_query($query);
while($row= mysql_fetch_array($result))
{
echo $row['item'];
}
$query2 = "select * from movie limit 0,5";
$result2 = mysql_query($query2);
while($row= mysql_fetch_array($result2))
{
echo $row['movie'];
}
?>
You may be able to do it with one SQL Query too:
SELECT i.item, m.movie
FROM (SELECT * FROM item ORDER BY date, time ASC LIMIT 0,3) i,
(SELECT * FROM movie limit 0,5) m
Then in php:
<?php
while($row= mysql_fetch_array($result))
{
echo $row['item'];
echo $row['movie'];
}
?>
But that depends on how you want to format the output.

Categories