无法通过php将文本值上传到mysql [英] Can't upload text value to mysql by php

查看:81
本文介绍了无法通过php将文本值上传到mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我提交网站表单以进行评论时,它只会创建一个新ID.但是所有其他值均为空,我该怎么办?我需要为名称,电子邮件和内容创建一些属性吗?

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代码:

推荐答案

这是错误的:

// insert a row
$guestName = "$guestName";
$guestContent = "$guestContent";
$guestEmail = "$guestEmail";
$stmt->execute();

您要使用的变量不存在.您需要从$_POST数组中检索表单发布的值:

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();

编辑:请注意,即使没有发布表单,您也会在每个请求上运行此代码.您将需要为此添加支票:

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();
}

实际上,您可能希望将与将数据保存在数据库中有关的所有内容都放在该if语句中,以便在不使用数据库时不打开数据库连接或准备语句使用它.

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.

这篇关于无法通过php将文本值上传到mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆