PHP MySQL How to select 2 specific and 1 common value over 2 tables?

好久不见. 提交于 2020-01-24 13:09:12

问题


i have here two tables (only the important columns listed) :

table1: unique_code(INT), spediteur(VARCHAR also Names),

table2: unique_code(INT), versendet(timestamp)

I have here a SELECT but that don't work and if the value is true - that means: just let me into the IF WHEN: spediteur value is Name and versendet = 0000-00-00 00:00:00 and unique_code = $value (unique_code/$value must be equal in this two tables).

I have tried with this:

$pdo = new PDO('myconnectionworks')
$stmt = pdo->prepare("SELECT * FROM table1 WHERE spediteur = 'Name' AND unique_code = $value
UNION ALL 
SELECT * FROM table2 WHERE versendet = '0000-00-00 00:00:00' AND unique_code = $value");
$stmt->execute([$value]);
$result = $stmt->fetch();
if ($result){ "the unique_number exists in both tables and matches the id with the value spediteur 'Dachser' in table1 AND the value versendet ='0000-00-00 00:00:00' in table2" } else { "anything doesn´t work" } 

This does not work, as it don´t allow me to get into the if , just into the else section. IF is a response for a successful action (save a other value) and else was an Error Response.

Did you have hints for me?

EDIT with Solution. i have used a programm that helps me to figure out, what for a statement i can use. (dbForge QUery Builder for MySQL) Okay here ist the Statement:

$stmt = $pdo->prepare("SELECT
  table1.spediteur,
  table2.versendet,
  table2.unique_code,
  table1.unique_code
FROM table1
  INNER JOIN table2
    ON table1.unique_code = table2.unique_code
WHERE table1.unique_code = $scanned_number
AND table2.unique_code = $scanned_number
GROUP BY table1.spediteur,
         table2.versendet,
         table2.unique_code,
         table1.unique_code
HAVING table1.spediteur = 'Dachser'
AND table2.versendet = '0000-00-00 00:00:00'
");

$stmt->execute([$scanned_number]);
$result = $stmt->fetch();
if ($result) { 
?> the scanned number matches the given parameter 

<?php 
$sql = "UPDATE table2 SET versendet = date('Y-m-d H:i:s') WHERE unique_code = $scanned_number";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();

} else { 
?> the scanned number don´t matches 
<?php
}?>

And i very relieved, that this tool saved my time. And as a learn experience, i can now look to the statement to understood how this works. Awesome!

If someone has a other solution, please let me know. Thank you!

来源:https://stackoverflow.com/questions/59110040/php-mysql-how-to-select-2-specific-and-1-common-value-over-2-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!