How to compare two fields in two tables in PHP? - php

Table_1
ID | Username
1 John
2 Mike
3 Chase
4 Shane
Table_2
ID | Username
1 | John
2 | Kenny
3 | Chase
4 | Shane
I want to get ID from Table_1. Then find that ID in table_2. Then i need it to look at the field Username in both tables. and if they match do nothing, If they don't match then update it to the username in Table_2 and run some code (like email me)
I need to to check every row in Table_1 everytime I run the script.

You have to use INNER JOIN in case to find the matching ID in both the tables and if you got one then update.
$sql = mysql_query("SELECT table_1.id as id_one,table_1.name as name_one,table_2.name as name_two FROM table_1 INNER JOIN table_2 ON (table_1.id = table_2.id)") or die(mysql_error());
if(mysql_num_rows($sql) > 0)
{
while($fetch = mysql_fetch_assoc($sql))
{
if($fetch['name_one'] != $fetch['name_two'])
{
// UPDATE table_1 'name' FIELD
mysql_query("UPDATE table_1 SET name = '".$fetch['name_two']."' WHERE id = ".$fetch['id_one']) or die(mysql_error());
// DO WHATEVER YOU WANT
}
}
}

My MySQL is a little rusty, but it can be done with a single Update statement. The following should update the usernames in Table_1 only where they differ from Table_2. You may have to tweak the syntax a little...
update Table_1 t1
join Table_2 t2
on t2.id = t1.id
and t2.Username <> t1.Username
set t1.Username = t2.Username;
You can query beforehand to generate any email you need.

Related

MYSQL and PHP where any related row contains string

I am having a small issue with MYSQL relations.
There is for every 1 value in table 1, there can be a multitude of values (0+) in table 2.
I am able to get all the data correctly, however, the issue comes when some values in table 2 differ, specifically the "taken up" field.
$sql = "
SELECT
accounts.name AS business,
accounts.industry AS style,
accounts_cstm.renewaldate_c AS ren_date,
accounts_cstm.nolongercontact_c AS NLC,
accounts_cstm.contactname_c AS person,
campaigns.name AS campaign,
users.first_name AS exec_fn,
users.last_name AS exec_sn,
email_addr_bean_rel.bean_id AS bean_id,
email_addresses.email_address AS email,
qs_quotationinformation.takenup AS takeup,
email_addr_bean_rel.email_address_id AS email_id
FROM
accounts
LEFT JOIN
campaigns ON accounts.campaign_id = campaigns.id
LEFT JOIN
users ON accounts.assigned_user_id = users.id
INNER JOIN
accounts_cstm ON accounts.id = accounts_cstm.id_c
LEFT JOIN
email_addr_bean_rel ON accounts.id = email_addr_bean_rel.bean_id
LEFT JOIN
email_addresses ON email_addr_bean_rel.email_address_id = email_addresses.id
LEFT JOIN
qs_quotamation_accounts_c ON accounts.id = qs_quotamation_accounts_c.qs_quot108funts_ida
LEFT JOIN
qs_quotationinformation ON qs_quotamation_accounts_c.qs_quotdb81tion_idb = qs_quotationinformation.id
WHERE
accounts.deleted = 0";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if($row["NLC"] == 1 || $row["takeup"] == 1){$NLC = "No";}else{$NLC = "Yes";}
echo '<tr><td>'.$row['business'].'</td><td>'.$row["style"].'</td><td>'.$row["ren_date"].'</td><td>'.$NLC.'</td><td>'.$row["person"].'</td><td>'.$row["campaign"].'</td><td>'.$row["exec_fn"].' '.$row["exec_sn"].'</td><td>'.$row["email"].'</td><td>'.$row["takeup"].'</tr>';
}
} else {
echo "0 results";
}
In this case Table 1 is "accounts" and Table 2 is "qs_quotationinformation".
There are some accounts in Table 1 which have multiple records in Table 2, and some of the "takenup" records in Table 2 (relating to the same account) can be 1 and some be 0.
So what I need to do is have it so that if any of the records in Table 2 = 1, then all of the variables of $NLC need to = "No".
I don't know if this is possible, or if there is a better way to get this information. The html table is missing data that gets pulled, but that's because the table is just a visual representation of the most important data to the user.
EDIT Tables (excluding personal data):
Table 1:
+----+---------+---------+
| id | name | deleted |
+----+---------+---------+
| 1 | example | 0 |
+----+---------+---------+
Table 2:
+----+---------+
| id | takenup |
+----+---------+
| 1 | 0 |
+----+---------+
| 2 | 1 |
+----+---------+
| 3 | 0 |
+----+---------+
All of the rows in Table 2 relate to the row in Table 1. But because there is a row with takenup = 1 $NLC needs to return "No" and not "Yes" (which it currently does because the last related row is 0)
So, if you understand you correctly, if you have an account, that has a corresponding qs_quotationinformation.takenup value of 1, then the query should return "No" for accounts_cstm.nolongercontact_c AS NLC for all records with the same account id, regardless of the value of qs_quotationinformation.takenup field in the other records.
In this case you need to get the list of accounts that have qs_quotationinformation.takenup=1 and you can use a subquery to return this information, which can be left joined to the main query. accounts_cstm.nolongercontact_c AS NLC would be changed to a case expression to return the "No" value based on the subquery.
SELECT
accounts.name AS business,
accounts.industry AS style,
accounts_cstm.renewaldate_c AS ren_date,
case
when no_nlc.qs_quot108funts_ida is null then accounts_cstm.nolongercontact_c
else 'No'
end AS NLC,
accounts_cstm.contactname_c AS person,
campaigns.name AS campaign,
users.first_name AS exec_fn,
users.last_name AS exec_sn,
email_addr_bean_rel.bean_id AS bean_id,
email_addresses.email_address AS email,
qs_quotationinformation.takenup AS takeup,
email_addr_bean_rel.email_address_id AS email_id
FROM
accounts
LEFT JOIN
campaigns ON accounts.campaign_id = campaigns.id
LEFT JOIN
users ON accounts.assigned_user_id = users.id
INNER JOIN
accounts_cstm ON accounts.id = accounts_cstm.id_c
LEFT JOIN
email_addr_bean_rel ON accounts.id = email_addr_bean_rel.bean_id
LEFT JOIN
email_addresses ON email_addr_bean_rel.email_address_id = email_addresses.id
LEFT JOIN
qs_quotamation_accounts_c ON accounts.id = qs_quotamation_accounts_c.qs_quot108funts_ida
LEFT JOIN
qs_quotationinformation ON qs_quotamation_accounts_c.qs_quotdb81tion_idb = qs_quotationinformation.id
LEFT JOIN
(SELECT
qs_quot108funts_ida
FROM
qs_quotamation_accounts_c
INNER JOIN
qs_quotationinformation ON qs_quotamation_accounts_c.qs_quotdb81tion_idb = qs_quotationinformation.id
WHERE
qs_quotationinformation.takenup = 1) no_nlc ON accounts.id = no_nlc.qs_quot108funts_ida
WHERE
accounts.deleted = 0
The case expression assumes that accounts_cstm.nolongercontact_c field is of a string type (char, varchar, etc). If this is not the case, then you need to cast the value of accounts_cstm.nolongercontact_c field to char using the cast() function.

PHP SQL get data from 2 tables and output wanted information

i am trying to achieve the following result. (i am sorry for the horrible explanation but i find it very hard to explain :P)
I need data from 2 tables.
Table1
id, table2_id, user_id
Table2
id, Name
Table1 example information
ID 1 Table2_id 1 user_id 3
ID 2 Table2_id 2 user_id 3
ID 3 Table2_id 5 user_id 3
Table2 Example Information
ID 1 Name TEST
ID 2 Name Hello
ID 3 Name Helpme
ID 4 Name Please
ID 5 Name IamLost
i Would like to output everything tied user_id 3. This would be my ideal end result
TEST
Hello
IamLost
I have this as code
$id = "3";
$sth = $db->prepare("SELECT table2_id, user_id, naam FROM table1, table2 where user_id = $id ");
$sth->execute();
$result = $sth->fetchAll();
foreach( $result as $row ) {
echo $row['table2_id'] . ' ';
echo $row['naam'] . '<br>';
}
But this just outputs everything but then twice. like this
TEST
TEST
Hello
Hello
Helpme
Helpme
Please
Please
IamLost
IamLost
A LEFT JOIN should do the trick:
SELECT `table1`.`table2_id`, `table1`.`user_id`, `table2`.`name`
FROM `table1`
LEFT JOIN `table2`
ON `table1`.`Table2_id` = `table2`.`id`
WHERE `table1`.`id` = $id
MySQL JOIN Syntax
Use Joins in SQL.
The SQL Query should look like this:
SELECT T1.USER_ID, T2.NAME
FROM TABLE1 AS T1
JOIN TABLE2 AS T2
ON T1.TABLE2_ID = T2.ID
WHERE T1.USER_ID = 3
these two table must be related to each other. When you select , returned rows should be equal this two tables. This why we use table joins e.g
SELECT a.user_id,a.table_id,b.name FROM table1 as a, table2 as b
RIGHT OUTER JOIN table 1
ON b.ID = a.table2_id
AND table1.user_id = 3
I believe you just need to be more precise:
$sth = $db->prepare("SELECT table2_id, user_id, name
FROM table1
LEFT JOIN table2
ON table1.Table2_id = table2.id
WHERE user_id = $id ");
A simple right outer join will help you here.
SELECT * FROM table2
RIGHT OUTER JOIN table 1
ON table2.ID = table1.table2_id
AND table1.user_id = 3

Update two table row from a post value

I have here two tables, I need to update both table row field from a post value. table1.item and table2.item update from post value. I didn't know how to set both table field equal to post value.
Any help will appreciate.
Table1
| pr_id | item |
----------------
| 1001 | pen |
Table2
| pr_id | item |
----------------
| 1001 | pen |
Query
<?php
$pr = $mysqli->real_escape_string($_POST["pr_id"]);
$item= $mysqli->real_escape_string($_POST["item"]);
$mysqli->query("UPDATE table1 LEFT JOIN table2 ON table1.pr_id = table2.pr_id WHERE table1 .pr_id = '$pr' ");
?>
Try this:
update table1 inner join table2
on table1.pr_id=table2.pr_id
//your changes
set table1.item ='some thing', table2.item ='some thing'
where table2 .pr_id ='$pr' ;
Try this:
Query:
UPDATE table1 T1 LEFT JOIN
table2 T2 ON T1.pr_id = T2.pr_id
SET T1.Item= '$item', T2.Item = '$item'
WHERE T1.pr_id = '$pr'
With php:
$mysqli->query("UPDATE table1 T1 LEFT JOIN table2 T2 ON T1.pr_id = T2.pr_id SET T1.Item= '$item', T2.Item = '$item' WHERE T1.pr_id = '$pr' ");
According to my opinion it is better to use Compound Trigger for updating 2 diffenent tables at the same time. Try to use that.

Save selected in variable and then use that variable for next select

I have multiple tables in my database. Let's say the table users looks like this:
Users:
|id|name|gender|access|id_ext|
|1 | a | m | 1 | 32 |
|3 | b | m | 3 | 33 |
|4 | c | m | 1 | 34 |
|5 | d | f | 1 | 35 |
I would like to select the user with for example id_ext = 32 and then run another select statement using that selected users fields.
I can solve this by first getting the user with a query and then create another query with users info, but there must be a way to do this in the same query?
This is the query i use now:
SELECT * FROM users NATURAL JOIN
(SELECT id FROM ages WHERE age BETWEEN
(SELECT limit_age_l FROM users WHERE id=17)
AND (SELECT limit_age_h FROM users WHERE id=17)) as a
WHERE NOT id = 17
AND locale = 'en_US'
AND limit_gender = 1
AND visible = 0
AND NOT EXISTS (SELECT view_id FROM matches WHERE user_id = 17 AND view_id = a.id)
LIMIT 1
Problem is that the values id=17, limit_gender=1 and locale = 'en_US' in the query are not known. These are taken from the user with id_ext = '32'.
SELECT * FROM Users WHERE id in (SELECT id FROM Users WHERE id_ext='32');
Yes - assuming your subsequnt query is of the form:
select field1, field2, ...
from Table1
join Table2 on ...
where ...
and Table1.id = N /* previously selected id from users */
Then either by using the first query as a subquery:
select field1, field2, ...
from Table1
join Table2 on ...
where ...
and Table1.id = (select id from users where id_ext ='32')
/* replace = with IN if more than one id will be returned */
Or by joining to the results of the first query as part of the subsequent query:
select field1, field2, ...
from users
join Table1 on Table1.id = users.id
join Table2 on ...
where ...
and users.id_ext ='32'
(Note that both of these forms assume that users is not already being joined in the existing query - if it is, just add the users.id_ext ='32' condition to the existing query.)
EDIT: If I have understood the requirements correctly, the required query could be written as:
SELECT u.*
FROM users u
join ages a on u.id = a.id and
u.age between limit_age_l and limit_age_h
join users ul on ul.id = 17 and
ul.id <> u.id and
ul.locale = u.locale and
ul.limit_gender = u.limit_gender and
ul.visible = u.visible
AND NOT EXISTS (SELECT NULL
FROM matches m
WHERE m.user_id = ul.user_id AND m.view_id = a.id)
LIMIT 1
SELECT * FROM users WHERE id = (SELECT id FROM users WHERE id_ext = '32');
Select * from users as user inner join userinfo as usinfo on usinfo.id=user.id_ext where user.id_ext='32'

selecting author in table1 and count published book in table2 mysql

I have two tables in a database that looks like this
members table1
id | memberid | name | password
-------------------------------
Journal table2
id | memberid | title | desc
-----------------------------
i want to select all members from table one, joining with the result journal_count of each member in table 2. Am trying to count the number of times each memberid appears in table2
Am using mysql and php, can someone help me with this query
thanks
select m.memberid,m.name,count(j.memberid) as total
from members as m
left join journal as j
on m.memberid = j.memberid
group by m.memberid
P.S. If your table has a field named desc, beware that this is a reserved word and it would be better to rename it. Otherwise you'll always have to put it within backticks.
select m.memberid,m.name,count(j.memberid) as total
from members as m
left join journal as j
on m.memberid = j.memberid
where m.memberid = $memberid
group by m.memberid
select members.name, count(journal.memberid) as journal_count from members, journal where members.memberid = journal.memberid group by journal.memberid

Categories