简体   繁体   中英

HTML/PHP form doesn't insert data to MySQL Database

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

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).

I have created a html form:

<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
$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.

However, If I set

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

to

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

it works.

Any help is appreciated! Thanks!

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.

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.

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:

$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 .


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

<?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>

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

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

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

$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.

$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 = "INSERT INTO organiser (subject,description) VALUES ('$subject', '$description')";
       ^                                                                               ^

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM