与DB的连接成功,但在MySQL中不可见

时间:2016-11-30 17:00:28

标签: php mysql database-connection

我已经查看过与此相关的几个问题,而且大多数问题似乎都是通过简单的语法错误来解决的。我不认为我的问题是语法。

我正在成功连接到我的数据库,但我似乎无法在phpmyadmin(我正在查看MySQL)中看到我的条目。我可以将我在另一个页面上的条目作为变量回显,但我相信我的输入不会进入数据库。

这是我的HTML代码:

 <!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>student info</title>
    </head>
    <body>
        <br>
        Enter your first name and last name in the corresponding boxes.
        <br>
        <form  action="submit.php" method="POST">
            First: <input type="text" name="firstname"/>
        <br>
            Last: <input type="text" name="lastname"/>
        <br>
        <input type="submit">
        </form>


    </body>
</html>

我的php用于数据库连接:

<?php
echo 'here';
    $dsn = 'mysql:host=localhost;dbname=practice_students';


    try {
        $db = new PDO($dsn);
        echo 'db connection success';
    } catch (PDOException $e) {
        $error_message = $e->getMessage();
        include('database_error.php');
        exit();
    }

?>

我的php提交页面:

<?php
echo 'here ';
    $dsn = 'mysql:host=localhost;dbname=practice_students';


    try {
        $db = new PDO($dsn);
        echo 'db connection success';
        $firstname = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING, 
                FILTER_SANITIZE_SPECIAL_CHARS);
        $lastname = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING,
                FILTER_SANITIZE_SPECIAL_CHARS);
        echo "Now we know your name! Hi," . " " . $firstname . " " . $lastname;
    } catch (PDOException $e) {
        $error_message = $e->getMessage();
        include('database_error.php');
        exit();
    }
?>

所有这些都会在我的本地主机中成功提示响应

here db connection successNow we know your name! Hi, Maggie Bowen

但是,当我尝试CHECK或SELECT *时,MySQL没有显示任何条目。

enter image description here

enter image description here

如何查看我的参赛作品?我知道我的一些消毒等可以改进,但我真的只想知道如何查看我的条目并确保它们进入表格。谢谢!

1 个答案:

答案 0 :(得分:3)

您有数据$ firstname和$ lastname。现在,您必须insert将它们放入使用PDO::query()提交查询的数据库中。

这样的事情:

$q = "INSERT INTO people (column1, column2) VALUES ('$firstname', '$lastname')";

$db->query($q);

编辑使用预准备语句来避免SQL注入攻击

Wikipedia

  

预准备语句对SQL注入具有弹性,因为稍后使用不同协议传输的参数值无需正确转义。如果原始语句模板不是从外部输入派生的,则不能进行SQL注入。

所以经过审核的代码

$stmt = $db->prepare("INSERT INTO people (column1, column2) VALUES (:firstname, :lastname)";

$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);

$stmt->execute();

感谢评论中的人员!