添加的数据库行是空的mysql / php

时间:2014-04-12 12:10:32

标签: php sql forms

我想从我的表单写到我的数据库。我很困惑,因为它类似于教程中的脚本,并且有效。

表格(w3schools示例)摘录:

<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>

PHP:

<?php
$con=mysqli_connect("localhost","XXX","AAA","databasename");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($_POST['firstname']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
$age = mysqli_real_escape_string($_POST['age']);
$sql="INSERT INTO test (firstname, lastname, age)
VALUES ('$firstname', '$lastname', '$age')";

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>

每次提交都会在我的数据库中添加一个新行。问题:这个添加的行是空的,除了年龄列总是0,无论我提交什么。

我的错误在哪里?

1 个答案:

答案 0 :(得分:0)

请参阅php document您必须为mysqli_real_escape_string提供两个值。 试试这个:

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