表单数据未正确插入MySQL数据库

时间:2016-10-10 21:55:39

标签: php

我正在尝试使用表单向我的数据库发送名字和姓氏,但是当我尝试它时实际上并没有向FirstName和LastName发送任何值,但是它会在创建ID时添加新记录。

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Student Form</title>
</head>
<body>
<form action="insert.php" method="post">
    <p>
        <label for="FirstName">First Name:</label>
        <input type="text" name="FirstName" id="FirstName">
    </p>
    <p>
        <label for="lastName">Last Name:</label>
        <input type="text" name="LastName" id="LastName">
    </p>
    <input type="submit" value="Submit">
</form>
</body>
</html>

PHP(作为一个名为&#39; insert.php&#39;的单独文件):

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

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

$sql = "INSERT INTO Students (FirstName, LastName) 
VALUES ('$FirstName', '$LastName')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

你必须在这里发布值e-g $姓= $ _ POST [ '姓']; $ LastName = $ _ POST ['LastName'];然后运行插入查询

答案 1 :(得分:0)

将PHP脚本更改为: -

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

$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];

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

$sql = "INSERT INTO Students (FirstName, LastName) 
VALUES ('$FirstName', '$LastName')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>