问题
Every time I submit the form of my website for comment, It only creates a new ID.But all other value is empty, what should I do? Do I need create some attribute for the name, email and content?
<?php
error_reporting(E_ALL);ini_set('display_errors',1);
$servername = "localhost";
$username = "seamaszhou";
$password = "123456";
$dbname = "guest";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO guest
(guestName,guestEmail,guestContent)
VALUES (:guestName, :guestEmail, :guestContent)");
$stmt->bindParam(':guestName', $guestName);
$stmt->bindParam(':guestEmail', $guestEmail);
$stmt->bindParam(':guestContent', $guestContent);
// insert a row
$guestName = "$guestName";
$guestContent = "$guestContent";
$guestEmail = "$guestEmail";
$stmt->execute();
?>
HTML CODE :
回答1:
This is wrong:
// insert a row
$guestName = "$guestName";
$guestContent = "$guestContent";
$guestEmail = "$guestEmail";
$stmt->execute();
The variables you're trying to use don't exist. You need to retrieve the values posted by the form from the $_POST
array:
$guestName = $_POST['guestName'];
$guestContent = $_POST['guestContent'];
$guestEmail = $_POST['guestEmail'];
$stmt->execute();
Edit: Note that you are running this code on every request, even if the form is not posted. You will want to add a check for that:
if (isset($_POST['guestName']) && isset($_POST['guestContent']) && isset($_POST['guestEmail'])) {
$guestName = $_POST['guestName'];
$guestContent = $_POST['guestContent'];
$guestEmail = $_POST['guestEmail'];
$stmt->execute();
}
Actually, you might want to put everything that has to do with saving the data in the database inside that if
-statement, so that you're not opening a database connection or preparing a statement when you're not going to use it.
来源:https://stackoverflow.com/questions/46744901/cant-upload-text-value-to-mysql-by-php