Can't upload text value to mysql by php [duplicate]

て烟熏妆下的殇ゞ 提交于 2020-01-07 08:06:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!