插入变量和SELECT FROM的表名

时间:2018-11-09 21:54:15

标签: mysql pdo

我正在尝试使用发布的变量和另一个表中的内容将一个项目插入表中。我不太确定我要去哪里错了,因为没有东西被添加到表中。我很困惑。这是我的代码:

$stmt = $conn->prepare("INSERT INTO Student_Choices (Username,T1_Choice,T2_Choice,T3_Choice,Current_DB)
                      VALUES (:username,:t1choice,:t2choice,:t3choice, db.DB)
                      SELECT DB FROM Current_DB as db
                      ");
$stmt->bindParam(':username', $_SESSION['username']);
$stmt->bindParam(':t1choice', $_POST["term1sport"]);
$stmt->bindParam(':t2choice', $_POST["term2sport"]);
$stmt->bindParam(':t3choice', $_POST["term3sport"]);
$stmt->execute();

2 个答案:

答案 0 :(得分:1)

SELECT DB FROM Current_DB as dbINSERT句子中无效。只需先执行此查询,然后将DB的值放入一个变量中,然后像其他参数一样,将其与bindParam()一起使用即可:

/* Get the database name. */

$stmt = $conn->prepare("SELECT DB FROM DB_Year");
$stmt->execute();
$res = $stmt->fetchAll();
$db = $res[0]['DB'];

/* Execute the insert statement. */

$stmt = $conn->prepare(
    "INSERT INTO Student_Choices (Username, T1_Choice, T2_Choice, T3_Choice, Current_DB)
     VALUES (:username, :t1choice, :t2choice, :t3choice, :db)"
);

$stmt->bindParam(':username', $_SESSION['username']);
$stmt->bindParam(':t1choice', $_POST["term1sport"]);
$stmt->bindParam(':t2choice', $_POST["term2sport"]);
$stmt->bindParam(':t3choice', $_POST["term3sport"]);
$stmt->bindParam(':db', $db);
$stmt->execute();

答案 1 :(得分:0)

要设计此INSERT查询,请先使用SELECT创建要插入的结果集。

                  SELECT :username AS Username,
                         :t1choice AS t1choice,
                         :t2choice AS t2choice,
                         :t3choice AS t3Choice, 
                         DB 
                    FROM Current_DB

然后将结果集用作插入的数据源。

      INSERT INTO Student_Choices 
                  (Username,T1_Choice,T2_Choice,T3_Choice,Current_DB)     
           SELECT :username AS Username,
                  :t1choice AS t1choice,
                  :t2choice AS t2choice,
                  :t3choice AS t3Choice, 
                  DB 
             FROM Current_DB

请注意SELECT操作如何替换VALUES()子句。

(小心,除非您在SELECT上放置了适当的WHERE子句,否则您可能会插入很多行,在Current_DB中每一行一个。)