从多个表调用并插入一个表

时间:2015-02-09 16:51:47

标签: php sql mysqli insert multiple-columns

我创建了一个带有一些功能的小测验,我遇到了打嗝。我正在尝试使用从2个不同表格收集的信息写入答案表。

我的问题是有没有办法从我下面的代码中插入UserId,QuestionId和答案,或者任何人都可以帮助我完成我的代码。

很抱歉,如果我是一个菜鸟。代码低于!

到目前为止从会话中检索用户名

<?php
session_start();
//check if the user is already logged in.
if (!isset($_SESSION['username'])) {
    header('Location: index.php');
}
?>

然后检索QuestionId和userId并提交答案

  <section id="content" class="content">

<form action="testingq.php" method="post">
<p>

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "mydb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT QuestionId, QuestionText, InputTypeId FROM question";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "<br> QuestionId: ". $row["QuestionId"]. " - : ". $row["QuestionText"]."<br>";
     }
} else {
     echo "0 results";
}

$conn->close();
?>  
<?php 

        $host="localhost"; // Host name 
        $user="root"; // Mysql username 
        $pass="root"; // Mysql password 
        $db_name="mydb"; // Database name  

        // Connect to server and select databse. 
        $con = mysqli_connect($host, $user, $pass, $db_name);


        $sql = "SELECT UserId FROM user WHERE username='$username'"; 

        $result = mysqli_query($con, $sql);

        ?>
<input type="Radio" name="Answer" value="1" checked/>Yes</p>
<input type="Radio" name="Answer" value="0"/>No</p>
<p><input type="submit" value="Send it!"></p>
</form>

</section>

testingq.php

<!DOCTYPE html>
<html>
<body>



    <?php 

            $host="localhost"; // Host name 
            $user="root"; // Mysql username 
            $pass="root"; // Mysql password 
            $db_name="mydb"; // Database name  

            // Connect to server and select databse. 
            $con = mysqli_connect($host, $user, $pass, $db_name);


            $sql = "INSERT into answers (QuestionId, UserId, Answer) VALUES(
            '$_POST[QuestionId]',
            '$_POST[UserId]',
            '$_POST[Answer]')"; 

            $result = mysqli_query($con, $sql);

            ?>


    </body>
    </html>     

0 个答案:

没有答案