Find Non Duplicate Values in Two Tables - php

I want to create a procedure that checks the data in 'Table1' against the data in 'Table2'. I have used this query to perform the procedure.
$sq_query = 'SELECT * FROM Table1 WHERE NOT EXISTS (SELECT * FROM Table2 WHERE Table1.name = Table2.name)';
$result = mysqli_query($conn, $sq_query);
if (!$result) {
die ('SQL Error: ' . mysqli_error($conn));
}
BTW, I want to find out any name which isn't in 'Table2' but is in 'Table1'. I have been unsuccessful in locating missing files so far.

You can try using left join
SELECT * FROM table1 left join
Table2 on Table1.name = Table2.name
where Table2.name is null

Related

How to display data from database table independently

Problem desc.
I have databese called demo. In this databse i have columns. Two of them are otk and zamestnanci.
/*zamestnanci = employees*/
So i have some data in otk table:
/*otk columns: id_otk|ciarovy_kod|cislo_zakazky|zamestnanci|*/
/*id_otk = autoincrement*/
/*zamestnanci can be only number*/
INSERT INTO otk (ciarovy_kod, cislo_zakazky, zamestnanci) VALUES ('65464', '564', '1');
And now i have some data in zamestnanci:
/*zamestnanci columns: id_zamestnanci|titul|meno|titulz|*/
/*id_zamestnanci = autoincrement*/
INSERT INTO zamestnanci (titul, meno, titulz) VALUES ('ads', 'John', 'das');
And now here is my code for displaing and searching data from otk:
if(isset($_GET['hladat']))
{
$hladatHodnotu = $_GET['hladatHodnotu'];
// hladat v setkych stlpcoch
// pouzitie concat funkcie pre vyhladanie iba urciteho stlpca
$sql = "SELECT * FROM otk JOIN zamestnanci ON zamestnanci.id_zamestnanci=otk.zamestnanci
JOIN zariadenia ON zariadenia.id=otk.zariadenie
JOIN stav ON stav.id=otk.stav
JOIN technologie ON technologie.id=otk.technologie
JOIN obrazky ON obrazky.id_obrazky=otk.obrazok
WHERE CONCAT(`ciarovy_kod`) LIKE '%".$hladatHodnotu."%'";
$vysledokHladania = filtrovatTabulku($sql);
}
//Zobrazovanie dat z viacerych tabuliek do jednej
/* JOIN zamestnanci ON zamestnanci.id_zamestnanci=otk.zamestnanci
JOIN zariadenia ON zariadenia.id=otk.zariadenie
JOIN stav ON stav.id=otk.stav
JOIN technologie ON technologie.id=otk.technologie
JOIN obrazky ON obrazky.id_obrazky=otk.obrazok*/
else {
$sql = "SELECT * FROM otk JOIN zamestnanci ON zamestnanci.id_zamestnanci=otk.zamestnanci
JOIN zariadenia ON zariadenia.id=otk.zariadenie
JOIN stav ON stav.id=otk.stav
JOIN technologie ON technologie.id=otk.technologie
JOIN obrazky ON obrazky.id_obrazky=otk.obrazok";
//$sql = "SELECT * FROM zariadenia, otk WHERE zariadenia.id=otk.zariadenie";
$vysledokHladania = filtrovatTabulku($sql);
}
// funkcia na pripojenie a spustenie $sql
function filtrovatTabulku($sql)
{
//Zahrnut pripojenie k db
include'../db/dbinfo.php';
$vysledokHladania = mysqli_query($con, $sql);
return $vysledokHladania;
}
And now when i empty table "zamestnanci" it will not display data from "otk" with id of that "zamestnanci" because he do not exist. So i want to ask you if there is way how to display if "zamestnanci" is not exist.
You're using the wrong JOIN.
You should learn how each join works before using them, read more about them here http://www.sql-join.com/sql-join-types/

How to use UNION in this case (MySQL) [duplicate]

This question already has answers here:
SQL query return data from multiple tables
(6 answers)
Closed 6 years ago.
I have two tables in a DB (table_1 and table_2), Each of them has a mutual column called Name.
I am currently using the following code to import some data (Name,status) only from table_1:
/* database section start */
$mysqli = new mysqli("z","z","z","z");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* database section end */
// Choose Relevant items, and turn them into an array
$item_array = array(
'item1',
'item2',
'item3'
);
//implode items, turn into string
$item_implode = join("','", $item_array);
//declare an overall array for result
$product = array();
$result = $mysqli->query("SELECT Name, Status as status from table_1 where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");
while($row = $result->fetch_assoc()) {
$product_name = $row['Name'];
// find all keys in $item_array which value is the products
$keys = array_keys($item_array, $product_name);
foreach ($keys as $key) {
// add values for these keys
$product[$key + 1]["Name"] = $row['Name'];
$product[$key + 1]["status"] = $row['status'];//
}
}
What should I add to this code if I want to import data from table_2 as well (e.g., columns named color, date_added)?
My objective is to have these keys:
$product[$x]["Name"]
$product[$x]["status"]
$product[$x]["color"]
$product[$x]["date_added"]
EDIT:
That long thread doesn't answer my question. The code isn't similar to the code I'm using, and I want to know how to apply the UNION exactly in this concrete case.
I've tried using:
$result = $mysqli->query
("(SELECT Name, status as status from table_1 )
UNION
(SELECT Name, color as color from table_2 )
where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");
while($row = $result->fetch_assoc()) {
But I get fatal error on the last line.
EDIT2:
Still getting an error:
$result = $mysqli->query
("(SELECT Name, status as statu table_1 where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode') )
UNION (SELECT color from table_2 where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode') );");
while($row = $result->fetch_assoc()) {
$result = $mysqli->query("SELECT table_1.Name, table_1.Status,table_2.color,table_2.date_added from table_1 inner join table_2 on table_1.Name=table_2.Name where table_1.Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");
(SELECT Name, Status as status FROM table_1 t1)
UNION
(SELECT color, date_added FROM table_2 t2)
Change your query, and try to use: INNER JOIN table_2
I can`t make the query for you, because I don't have your data...
Build your Query with a join.
$query="SELECT t1.Name, t1.Status as status, t2.color, t2.date_added) from "
."table_1 t1 "
."LEFT JOIN table_2 t2 ON t2.Name "
."where t1.Name IN ('$item_implode') "
."AND t2.Name = t1.Name "
."ORDER BY FIELD (t1.Name, '$item_implode');";

Multiple mysql table joins with php?

Honestly I have no idea how to do what I am trying to do. I am not overly experienced in php nor in Mysql but I am trying and could use some help, preferably with working example code.
Problem: I have 3 tables
members
customfields
customvals
members contains:
membername | Id
customfields contains:
rank | name
customvals contains
fieldid | userid | fieldvalue
Table columns match at
customvals.userid=members.id
customvals.fieldid=members.rank
What I need to do is match the data so that when page.php?user=membername is called it displays on the page
Table1.membername:<br>
Table2.name[0] - Table3.fieldvalue[0]<br>
Table2.name[1] - Table3.fieldvalue[1]<br>
etc...
(obviously displaying only the information for the said membername)
The more working the code, the more helpful it is for me. Please don't just post the inner join statements. Also it is most helpful to me if you could explain how and why your solution works
So far here is what I have for code:
$profileinfocall = "SELECT Table1.`membername`, Table2.`name`, Table3.`fieldvalue`
FROM members AS Table1
LEFT JOIN customvals AS Table3 ON Table1.`id` = Table3.`userid`
LEFT JOIN customfields AS Table2 ON Table3.`fieldid` = Table2.`rank`
WHERE Table1.`membername` = $username;";
$membercall = "SELECT * FROM members WHERE membername=$username";
$profileinfo = mysql_query($profileinfocall, $membercall);
while($row = mysql_fetch_array($profileinfo)) {
echo $row['membername'];
}
Obviously this doesn't work as I get the following errors:
Warning: mysql_query() expects parameter 2 to be resource, string given on line 534.
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in on line 535
While this is a very broad question and you have not provided any PHP code, you might want to break it down into various sections:
Establishing a connection to the database (with mysqli) and sending a query:
$c = mysqli_connect("localhost","user","password","db");
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
else {
$result = mysqli_query($c,"SELECT * FROM members");
while($row = mysqli_fetch_assoc($result)) {
echo "{$row['membername']}";
}
}
mysqli_close($c);
Tieing your tables together:
It is better to start off with a clear structure (including line breaks) when getting into the MySQL syntax. One way would be to have some sort of query skeleton:
SELECT tablealias.column, table2alias.field3
FROM table AS tablealias
LEFT|RIGHT|INNER JOIN table2 AS table2alias ON table.id=table2.id
WHERE (this and that = true or false, LIKE and so on...)
Breaking it down to your specific problem this would be:
SELECT Table1.`membername`, Table2.`name`, Table3.`fieldvalue`
FROM members AS Table1
LEFT JOIN customvals AS Table3 ON Table1.`id` = Table3.`userid`
LEFT JOIN customfields AS Table2 ON Table3.`fieldid` = Table2.`rank`
WHERE Table1.`Id` = 'UserID to be searched for'
Improvements & Security measures:
But there is even more to it than meets the eye. If you have just begun, you might as well dive directly into prepared mysqli- statements. Given the query to get your members, the only changing part is the ID. This can be used for a prepared statement which is much more secure than our first query (though not as fast). Consider the following code:
$sql = "SELECT Table1.`membername`, Table2.`name`, Table3.`fieldvalue`
FROM members AS Table1
LEFT JOIN customvals AS Table3 ON Table1.`id` = Table3.`userid`
LEFT JOIN customfields AS Table2 ON Table3.`fieldid` = Table2.`rank`
WHERE (Table1.`Id` = ?)";
$c = mysqli_connect("localhost","user","password","db");
$stmt = $c->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_params("i", $userid);
$stmt->execute();
while ($stmt->fetch()) {
//do stuff with the data
}
$stmt->close();
}
$mysqli->close();
This SQL query should do it:
SELECT a.membername, a.Id, b.fieldid, b.userid, b.fieldvalue, c.rank, c.name
FROM members AS a
LEFT JOIN customvals AS b ON a.id = b.userid
LEFT JOIN customfields AS c ON b.rank = c.fieldid
WHERE a.Id = #MEMBERIDHERE#;

Error: Join in MySql, PHP

I have two tables in mysql one is quote and the fields are quote_id, status, created and submit_by. in submit_by field i am saving username of the employee and in employee table the fields are firs_name, last_name, username, password. I want to show in a php table the employee first name instead of username of the employee.
full quote table stucture
full employee table sructure
this is the code i am using but not getting any result
$sql = "SELECT q.quote_id, q.client_name, q.status, e.first_name
FROM `quote` AS q
LEFT JOIN `employee` AS e ON q.submit_by = e.username";
Use this one
$sql = "SELECT * , employee.first_name FROM quote
LEFT JOIN employee ON quote.submit_by = employee.username ORDER BY quote.client_name";
$result = $dbLink->query($sql);
try this:
SELECT quote.quote_id, quote.client_name, quote.status, employee.first_name FROM quote
LEFT JOIN employee ON quote.submit_by = employee.username ORDER BY quote.client_name;
You can use below Query to get the result.
SELECT q.`quote_id`, q.`client_name`, q.`status`, e.`first_name` FROM `quote` q , `employee` e WHERE q.`submit_by` = e.`username`;

joining two tables and fetching values from them error

i am joining the two tables but is giving me error that mysql_fetch_array() expects parameter 1 to be resource,
<?php
$result=mysql_query("SELECT * FROM `photo_gallery`.`photographs` WHERE id=1");
$result .=mysql_query("SELECT * FROM `photo_gallery`.`users` WHERE id=1");
while($row=mysql_fetch_array($result))
{
echo 'You are Welcome'.'<br/>';
$Id=$row['id'];
$Name=$row['username'];
$Batch=$row['password'];
$Address=$row['first_name'];
$Course=$row['last_name'];
$filename=$row['filename'];
$type=$row['type'];
echo 'your ID is'.$Id.'<br/>'.'username '. $Name.'<br/>'.'your password '. $Batch.'<br/>'.'yor first name'. $Address. '<br/>'.'last'.$Course.'<br/>'.'file name is'.'<br/>'.$filename.'<br/>'.'type is '.$type;
}
?>
Here is the most easy syntax to use join function
$query=mysql_query("SELECT * FROM `databasename`.`firstablename` JOIN `seconddatabasename` ON firsttablename.id = secondtablename.id ");
If you want to work with join array than visit this link http://www.w3schools.com/php/func_string_join.asp.
I hope you get what join function is used for.
Try this.
$query = "SELECT * FROM photographs INNER JOIN users ON photographs.id = users.id";
$result = mysql_query($query);
you cannot chain mysql queries in php that way. you have 2 options.
create a real mysql join.
you can use the shorthand syntax:
SELECT * FROM `photographs` p, `users` u WHERE p.id = u.id AND id=1
or a real join:
SELECT * FROM `photographs` p INNER JOIN `users` u WHERE p.id = u.id AND id=1
might i suggest reading more about mysql joins:
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

Categories