使用PHP

时间:2017-09-05 13:35:00

标签: html mysql database

我只想弄清楚将表单数据插入数据库的逻辑。下面的代码(load.php)工作正常。 Howewer我在process.php中以某种方式收到语法错误,除了我不确定我的插入代码是否正确。我也怀疑这段代码是安全的,在使用数据库时我应该考虑的关键安全因素是什么?我知道我问了很多问题,但我只想尝试全局。我很感激任何建议和想法。

谢谢!

**//process.php**

<?php
require ("load.php");
$fname= $_POST['fname'];
$lname= $_POST['lname'];

$sql = "INSERT INTO registration (firstname, lastname) VALUES ('$_POST[fname]','$_POST[lname]')";
if (mysqli_query($conn, $sql)) {
      echo "New record created successfully";
} else {
      echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>



**//load.php**


    <?php
    $servername = "localhost";
    $database = "registration";
    $username = "root";
    $password = "";

    $conn = mysqli_connect($servername, $username, $password, $database);
    if (!$conn) {
          die("Connection failed: " . mysqli_connect_error());
    }

    echo "Connected successfully";

    ?>




**//index.php**

<?php require ("load.php"); ?>

<html>
   <head>
      <title>Registration Form</title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   </head>
   <body>
      <h3>Registration Form</h3>
      <form name="registration" method="post" action="process.php">
      <table border="0" cellspacing="2" cellpadding="2">
         <tr><td>First Name:</td><td><input type="text" name="fname"></td></tr>
         <tr><td>Last Name:</td><td><input type="text" name="lname"></td></tr>
         <tr><td>&nbsp;</td><td><input type="submit" name="submit" value="Register"></td></tr>
      </table>
      </form>
   </body>
</html>

2 个答案:

答案 0 :(得分:-1)

很可能语法错误是由缺少的反斜杠引起的

<强>前

$sql = "INSERT INTO registration (firstname, lastname) VALUES ('$_POST[fname]','$_POST[lname]')";

<强>后

$sql = "INSERT INTO registration (`firstname`, lastname`) VALUES ('$fname','$lname')";

进一步说明

在查询中不需要使用post数组,因为它被分配给变量$ fname和$ lname

正如您在评论中注意到的那样,它很容易被SQL注入。应该对名字和姓氏的值进行转义,但我认为它仍然容易受到攻击。

 $firstname = mysqli_real_escape_string($con, $_POST['firstname']);

更安全的方法是使用PDO而不是mysqli和查询绑定。您可以在此处阅读有关此内容的更多信息http://php.net/manual/en/pdostatement.bindparam.php

答案 1 :(得分:-2)

请尝试以下process.php代码 这将有效

require ("load.php");

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname)    VALUES (?, ?)");
$stmt->bind_param("ss", $firstname, $lastname);

$fname= $_POST['fname'];
$lname= $_POST['lname'];


if ($stmt->execute()) {
      echo "New record created successfully";
} 

$stmt->close();