HTML / PHP表单不会将数据插入MySQL数据库

时间:2022-09-25 20:11:11

I am new to PHP, and I have been trying to make a small Homework Organiser Application.

我是PHP的新手,我一直在尝试制作一个小型的家庭作业组织应用程序。

The idea is that you can input a Subject and Description and it will be added to a MySQL Database (that's it for now).

这个想法是你可以输入一个主题和描述,它将被添加到MySQL数据库(现在就是它)。

I have created a html form:

我创建了一个html表单:

<form action="insert.php">
        <label for="subj">Subject:</label>
        <br>
        <input type="text" name="subj">
        <br>
        <label for="desc">Description:</label>
        <br>
        <input type="text" name="desc">
        <br>
        <input type="submit" value="Submit" name="submit">
    </form>

and some php code:

和一些PHP代码:

<?php
$subject = $_POST['subj'];
$description = $_POST['desc'];
$subject = mysql_real_escape_string($subject);
$description = mysql_real_escape_string($description);

$dbhost = ''; //These are filled in actually
$dbuser = ''; //These are filled in actually
$dbpass = ''; //These are filled in actually
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
    die('Could not connect: ' . mysql_error());
}

$sql = 'INSERT INTO organiser '.
    '(subject,description) '.
    'VALUES ('$subject', '$description')';

mysql_select_db(''); //These are filled in actually
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
    die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>

The problem is that the input from the Subject and Description boxes on the HTML form don't go into the MySQL Database.

问题是来自HTML表单上的主题和描述框的输入不会进入MySQL数据库。

However, If I set

但是,如果我设置

'VALUES ('$subject', '$description')';

to

'VALUES ("test", "test")';

it works.

Any help is appreciated! Thanks!

任何帮助表示赞赏!谢谢!

3 个解决方案

#1


0  

Your problem is because you are using single quotes in your $sql declaration,

您的问题是因为您在$ sql声明中使用单引号,

$sql = 'INSERT INTO organiser '.'(subject,description) '.'VALUES ('$subject', '$description')';

When you use single quotes you are telling PHP that you would like everything within the quotes to be taken literally.

当你使用单引号时,你告诉PHP你希望字面上引用引号中的所有内容。

$age = 20; 
$myAge = 'I am $age years';
echo $myAge; 

This would echo I am $age years since you used single quotes.

这可以回应我使用单引号后的年龄。

However, if you used double quotes instead,

但是,如果您使用双引号,

$age = 20; 
$myAge = "I am $age years";
echo $myAge;

The output would be,

输出将是,

I am 20 years

Thus, your $sql statement should be (I write it on one line instead),

因此,你的$ sql语句应该是(我把它写在一行代替),

$sql = "INSERT INTO organiser (subject,description) VALUES ('$subject', '$description')";
       ^                                                                               ^

If you echo your $sql it would become something along the lines of,

如果你回应你的$ sql它将成为一些东西,

INSERT INTO organiser (subject,description) VALUES ('Your subject', 'Your description') 

Your use of single quotes within your SQL-statement is correct, you can read more about the subject here: When to use single quotes, double quotes and backticks

您在SQL语句中使用单引号是正确的,您可以在此处阅读有关该主题的更多信息:何时使用单引号,双引号和反引号

#2


1  

In addition to the answer already given in regards to missing dots for the concatenate:

除了已经给出关于连接的缺失点的答案:

Form method defaults to a GET method, if the method is omitted from the form tag.

如果从表单标记中省略该方法,则表单方法默认为GET方法。

You are using <form action="insert.php"> which is equivalent to doing
<form action="insert.php" method = "get"> which is not what you want nor required.

您正在使用

,这相当于执行,这不是您想要或不需要的。

Change it to

将其更改为

<form action="insert.php" method="post">

since you are using POST variables.

因为你正在使用POST变量。

That is the contributing reason why 'VALUES ("test", "test")'; works and not the other way, since both of these variables $subject - $description, are based on your POST variables:

这就是'VALUES(“测试”,“测试”)'的原因;工作而不是其他方式,因为这两个变量$ subject - $ description,都是基于你的POST变量:

$subject = $_POST['subj'];
$description = $_POST['desc'];

You can either do

你可以做到

$sql = "INSERT INTO organiser (subject,description) VALUES ('$subject', '$description')";

as stated in a comment.

正如评论中所述。

or

$sql = "INSERT INTO organiser (subject,description) VALUES ('".$subject."', '".$description."')";

Add error reporting to the top of your file(s)

将错误报告添加到文件的顶部

error_reporting(E_ALL);
ini_set('display_errors', 1);

which would have signaled errors found in your code.

这将在您的代码中发现错误信号。


Yet, your method is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.

但是,您的方法对SQL注入是开放的。将mysqli_ *与预准备语句一起使用,或将PDO与预准备语句一起使用。


Use a mysqli prepared statements method; it's safer.

使用mysqli预处理语句方法;它更安全。

<?php 

$DB_HOST = "xxx"; // replace with your own
$DB_NAME = "xxx";
$DB_USER = "xxx";
$DB_PASS = "xxx";

$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
  die('Connection failed [' . $conn->connect_error . ']');
}

// optional to check for empty fields
// if(isset($_POST['submit']) && !empty($_POST['subj'])  && !empty($_POST['desc'])) {
if(isset($_POST['submit'])) {

$subject = stripslashes($_POST['subj']);
$description = stripslashes($_POST['desc']);

$stmt = $conn->prepare("INSERT INTO organiser (`subject`, `description`) VALUES (?, ?)");

$stmt->bind_param('ss', $subject, $description);

    if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }

        else{
          echo "<h2>Success!</h2>";
        }

$stmt->close(); // Statement
$conn->close(); // MySQLi

}

?>

Form: (new)

<form action = "insert.php" method = "post">
        <label for="subj">Subject:</label>
        <br>
        <input type="text" name="subj">
        <br>
        <label for="desc">Description:</label>
        <br>
        <input type="text" name="desc">
        <br>
        <input type="submit" value="Submit" name="submit">
</form>

#3


0  

You forgot the dots around the variables and you can add some double quotes around that depending on the content of your variables :)

你忘记了变量周围的点,你可以根据变量的内容添加一些双引号:)

'VALUES ("'.$subject.'", "'.$description.'")';

#1


0  

Your problem is because you are using single quotes in your $sql declaration,

您的问题是因为您在$ sql声明中使用单引号,

$sql = 'INSERT INTO organiser '.'(subject,description) '.'VALUES ('$subject', '$description')';

When you use single quotes you are telling PHP that you would like everything within the quotes to be taken literally.

当你使用单引号时,你告诉PHP你希望字面上引用引号中的所有内容。

$age = 20; 
$myAge = 'I am $age years';
echo $myAge; 

This would echo I am $age years since you used single quotes.

这可以回应我使用单引号后的年龄。

However, if you used double quotes instead,

但是,如果您使用双引号,

$age = 20; 
$myAge = "I am $age years";
echo $myAge;

The output would be,

输出将是,

I am 20 years

Thus, your $sql statement should be (I write it on one line instead),

因此,你的$ sql语句应该是(我把它写在一行代替),

$sql = "INSERT INTO organiser (subject,description) VALUES ('$subject', '$description')";
       ^                                                                               ^

If you echo your $sql it would become something along the lines of,

如果你回应你的$ sql它将成为一些东西,

INSERT INTO organiser (subject,description) VALUES ('Your subject', 'Your description') 

Your use of single quotes within your SQL-statement is correct, you can read more about the subject here: When to use single quotes, double quotes and backticks

您在SQL语句中使用单引号是正确的,您可以在此处阅读有关该主题的更多信息:何时使用单引号,双引号和反引号

#2


1  

In addition to the answer already given in regards to missing dots for the concatenate:

除了已经给出关于连接的缺失点的答案:

Form method defaults to a GET method, if the method is omitted from the form tag.

如果从表单标记中省略该方法,则表单方法默认为GET方法。

You are using <form action="insert.php"> which is equivalent to doing
<form action="insert.php" method = "get"> which is not what you want nor required.

您正在使用

,这相当于执行,这不是您想要或不需要的。

Change it to

将其更改为

<form action="insert.php" method="post">

since you are using POST variables.

因为你正在使用POST变量。

That is the contributing reason why 'VALUES ("test", "test")'; works and not the other way, since both of these variables $subject - $description, are based on your POST variables:

这就是'VALUES(“测试”,“测试”)'的原因;工作而不是其他方式,因为这两个变量$ subject - $ description,都是基于你的POST变量:

$subject = $_POST['subj'];
$description = $_POST['desc'];

You can either do

你可以做到

$sql = "INSERT INTO organiser (subject,description) VALUES ('$subject', '$description')";

as stated in a comment.

正如评论中所述。

or

$sql = "INSERT INTO organiser (subject,description) VALUES ('".$subject."', '".$description."')";

Add error reporting to the top of your file(s)

将错误报告添加到文件的顶部

error_reporting(E_ALL);
ini_set('display_errors', 1);

which would have signaled errors found in your code.

这将在您的代码中发现错误信号。


Yet, your method is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.

但是,您的方法对SQL注入是开放的。将mysqli_ *与预准备语句一起使用,或将PDO与预准备语句一起使用。


Use a mysqli prepared statements method; it's safer.

使用mysqli预处理语句方法;它更安全。

<?php 

$DB_HOST = "xxx"; // replace with your own
$DB_NAME = "xxx";
$DB_USER = "xxx";
$DB_PASS = "xxx";

$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
  die('Connection failed [' . $conn->connect_error . ']');
}

// optional to check for empty fields
// if(isset($_POST['submit']) && !empty($_POST['subj'])  && !empty($_POST['desc'])) {
if(isset($_POST['submit'])) {

$subject = stripslashes($_POST['subj']);
$description = stripslashes($_POST['desc']);

$stmt = $conn->prepare("INSERT INTO organiser (`subject`, `description`) VALUES (?, ?)");

$stmt->bind_param('ss', $subject, $description);

    if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }

        else{
          echo "<h2>Success!</h2>";
        }

$stmt->close(); // Statement
$conn->close(); // MySQLi

}

?>

Form: (new)

<form action = "insert.php" method = "post">
        <label for="subj">Subject:</label>
        <br>
        <input type="text" name="subj">
        <br>
        <label for="desc">Description:</label>
        <br>
        <input type="text" name="desc">
        <br>
        <input type="submit" value="Submit" name="submit">
</form>

#3


0  

You forgot the dots around the variables and you can add some double quotes around that depending on the content of your variables :)

你忘记了变量周围的点,你可以根据变量的内容添加一些双引号:)

'VALUES ("'.$subject.'", "'.$description.'")';