php - 如何将变量值存储到mysql数据库中

时间:2016-04-17 19:50:10

标签: php mysql

嘿伙计们我是php的新手,所以我需要你的帮助。正如标题所示我试图将变量值存储到数据库表中。

这是我写的PHP代码,但它似乎并没有起作用。它似乎没有在数据库中存储任何值。

<?php

    // starts a session and checks if the user is logged in
    error_reporting(E_ALL & ~E_NOTICE);
    session_start();

    if (isset($_SESSION['id'])) {
        $userId = $_SESSION['id'];
        $username = $_SESSION['username'];


    } else {
        header('Location: index.php');
        die();

    }   

?>



<!DOCTYPE html>

<html>
<body>



                        <!-- heading -->
        <div id="intro">Thankyou for booking a slot using the booking system.</div>


                        <!-- echo out information -->

        <div id="fonts">

        <h4>Below is the information of your booking:</h4>

            </br>
            </br>

        <b>Student Name:</b> <?php echo $username; // echo's name ?>
            </br>
            </br>



        <b>Room No:</b> <?php $room = $_SESSION['g'];

                echo $room; // echo's room ?>
            </br>
            </br>



        <b>Computer No:</b> <?php 

                $select3 = $_POST['bike'];
                echo  $select3;
                ?>
            </br>
            </br>



        <b>Date:</b> <?php $date = $_POST['datepicker']; 
                echo $date; // echo's date 
                ?>
        </br>
        </br>



        <b>Start Session and End Session:</b> <?php 
                if(isset($_POST['select1']) && isset($_POST['select2'])) {
                $select1 = $_POST['select1'];
                $select2 = $_POST['select2'];
                echo $select1;
                echo "";
                echo $select2;
                }
                else{
                echo "not set";
                }
                ?>

        </div>





        <?php

            // to connect to database 
            require("user_connection.php");

            $query = "INSERT INTO booked (date, computer_id, name, start_time, end_time) VALUES ('$date', '$select3', '$username', '$select1', '$select2')";

            mysqli_query($query);


        ?>






    </body>


    <footer>
        <p>Copyright © 2016 MyComputer &nbsp; | &nbsp; Contact information: <a href="mailto:gurungmadan@hotmail.com">gurungmadan@hotmail.com</a></p>
    </footer>

</html>
你可以帮我检查我的代码是否有问题。数据库表被调用&#34;预订&#34;列是&#34; date,computer_id,name,start_time,end_time&#34;。下面是页面的完整代码

ReaderT :: * -> (* -> *) -> * -> *

1 个答案:

答案 0 :(得分:1)

首先,我建议你使用mysqli的PDO insteand。您可以查看有关herehere

的更多信息

使用pdo方式,您的代码将产生如下结果:

    $sql = "INSERT INTO booked (date, computer_id, name, start_time, end_time) VALUES (?,?,?,?,?)";
    $data = array($date, $select3, $username, $select1 ,$select2);
    $sth = $this->_db->prepare($sql);
    $sth->execute($data);

通过使用prepare语句,您可以免受sql注入。