php MySQL INSERT值引用另一个表

时间:2015-02-25 21:31:00

标签: php mysql select insert

在下面的代码中,我最关心的是最后三个变量。 php变量($ae, $pe, and $de)将用户的全名表示为字符串。

我正在尝试将job_schedule用户的ID插入表users

目前我的结果将所有数据都插入到表中,但将“0”放入最后三列(AE,PE,DE)的每个记录中,好像它无法找到USERID。 / p>

使用PDO:

$res =  $db_qms->prepare("INSERT INTO `job_schedule` (`JID`, `HPL`, `WO`, `DESCRIP`, `MFG_LINE`, `CUSTOMER`, `AE`, `PE`, `DE`) VALUES (:jid, :hpl, :wo, :descrip, :mfg, :customer, :ae, :pe, :de)");
  $res->execute(array(
    ":jid" => $id,
    ":hpl" => $hpl,
    ":wo" => $wo,
    ":descrip" => $descrip,
    ":mfg" => $mfg,
    ":customer" => $customer,
    ":ae" => "SELECT `USERID` FROM `users` WHERE " . $ae . " LIKE (CONCAT(`users`.`FIRSTNAME`, ' ' , `users`.`LASTNAME`))",
    ":pe" => "SELECT `USERID` FROM `users` WHERE " . $pe . " LIKE (CONCAT(`users`.`FIRSTNAME`, ' ' , `users`.`LASTNAME`))",
    ":de" => "SELECT `USERID` FROM `users` WHERE " . $de . " LIKE (CONCAT(`users`.`FIRSTNAME`, ' ' , `users`.`LASTNAME`))"
  ));

我还试图查看我的SELECT语句是否正确。所以我将以下代码运行到phpMyAdmin SQL部分,我能够提取一个值。所以Select语句有效。

"SELECT `USERID` FROM `users` WHERE "John Doe" LIKE (CONCAT(`users`.`FIRSTNAME`, ' ' , `users`.`LASTNAME`))"

结果为USERID

提供了值

我不知道从哪里开始。当我获得用户的全名时,如何从users.USERID插入用户的ID?

2 个答案:

答案 0 :(得分:1)

请尝试使用INSERT SET语法。

$rest = $db_qms->prepare(
  "INSERT INTO `job_schedule` " .
  "SET " .
    "`JID` = :jid, " .
    "`HPL` = :hpl, " .
    "`WO` = :wo, " .
    "`DESCRIP` = :descrip, " .
    "`MFG_LINE` = :mfg, "
    "`CUSTOMER` = :customer, " .
    "`AE` = (SELECT `USERID` FROM `users` WHERE (:ae LIKE CONCAT(`users`.`FIRSTNAME`, ' ', `users`.`LASTNAME`))), " .
    "`PE` = (SELECT `USERID` FROM `users` WHERE (:pe LIKE CONCAT(`users`.`FIRSTNAME`, ' ', `users`.`LASTNAME`))), " .
    "`DE` = (SELECT `USERID` FROM `users` WHERE (:de LIKE CONCAT(`users`.`FIRSTNAME`, ' ', `users`.`LASTNAME`)));"
);
$res->execute(array(
  ":jid" => $id,
  ":hpl" => $hpl,
  ":wo" => $wo,
  ":descrip" => $descrip,
  ":mfg" => $mfg,
  ":customer" => $customer,
  ":ae" => $ae,
  ":pe" => $pe,
  ":de" => $de
));

答案 1 :(得分:0)

我从未见过sql语句在where子句中使用字符串。

我会以不同的方式编写sql:

":AE" => " SELECT USERID FROM users WHERE CONCAT(users.FIRSTNAME,'',users.LASTNAME)LIKE \"" 。 $ ae。 " \"&#34 ;;