使用php连接和插入Mysql数据库

3

由于我正在使用PHP连接到MySQL数据库。我尝试连接到数据库,并且同样地,每当我单击表单上的登录按钮时,我想将数据插入到数据库中。但是,当我尝试此代码时,数据库中没有更改显示出来,因此请帮助我。谢谢。

<?php
        $servername = "localhost"; 
        $username = "root";
        $password = "password";
        $conn = new PDO("mysql:host=$servername;dbname=Akalpa", $username, $password); // connection to my sql database

        if(isset($_POST['Log In'])){
            $username=$_POST['username'];
            $query = "Insert into User(username) values('$username')"; //query to insert to db

            if (mysql_query($query)) //checking the query 
            {
                echo"<h3>Inserted Successfully</h3>";   //value inserted to db successfully           
            }       


        }
    ?>

只需将 mysql_query($query) 替换为 $conn->query( $query ),并查看 Jack M 的答案,因为您应该采取更多安全措施。 - Brian Gottier
1个回答

2

看起来你正在使用PDO连接,但是使用了mysql_函数。 你应该像这样编写代码。

<?php
        $servername = "localhost"; 
        $username = "root";
        $password = "password";
        $conn = new PDO("mysql:host=$servername;dbname=Akalpa", $username, $password); // connection to my sql database

    if(isset($_POST['Log In'])){
        $username=$_POST['username'];
        $query = "INSERT INTO User(username) VALUES(:username)"; //query to insert to db
        $stmt = $conn->prepare($query);
        $result = $stmt->execute(["username"=>$username]);
        if ($result) //checking the query 
        {
            echo"<h3>Inserted Successfully</h3>";   //value inserted to db successfully           
        } else {
            die("query failed");
        }       


    }
?>

您的原始代码容易受到SQL注入攻击,这是不好的。我也不建议使用$_POST ["Log In"],因为在数组键中包含空格是可怕的做法。尝试使用更简单的内容,如"submit"或"login"。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接