我正在尝试使用名为PHP for Absolute Beginners的书来学习一些PHP。我正在尝试使用 WAMP 和 editplus 来实现书中给出的一些博客设计代码。当我尝试使用 PHP 表单插入数据时,我得到的只是数据库表中的 NULL 值。这是一段用于将值插入数据库的代码。
<?php
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Save Entry'
&& !empty($_POST['title'])
&& !empty($_POST['entry']))
{
// Include database credentials and connect to the database
include_once 'db.inc.php';
$db = new PDO(DB_INFO, DB_USER, DB_PASS);
// Save the entry into the database
$sql = "INSERT INTO entries (title, entry) VALUES (?, ?)";
$stmt = $db->prepare($sql);
$stmt->execute(array($title, $entry));
$stmt->closeCursor();
// Get the ID of the entry we just saved
$id_obj = $db->query("SELECT LAST_INSERT_ID()");
$id = $id_obj->fetch();
$id_obj->closeCursor();
// Send the user to the new entry
header('Location: ../admin.php?id='.$id[0]);
exit;
}
// If both conditions aren't met, sends the user back to the main page
else
{
header('Location: ../admin.php');
exit;
}
?>
当我检查 apache 错误日志时,我看到以下内容:
[Sun May 27 19:21:24 2012] [error] [client 127.0.0.1] PHP Notice: Undefined
variable: title in C:\\wamp\\www\\examples\\simple_blog\\inc\\update.inc.php
on line 14, referer: http://localhost/examples/simple_blog/admin.php?id=8
[Sun May 27 19:21:24 2012] [error] [client 127.0.0.1] PHP Stack trace:, referer:
http://localhost/examples/simple_blog/admin.php?id=8
[Sun May 27 19:21:24 2012] [error] [client 127.0.0.1] PHP 1. {main}()
C:\\wamp\\www\\examples\\simple_blog\\inc\\update.inc.php:0, referer:
http://localhost/examples/simple_blog/admin.php?id=8
[Sun May 27 19:21:24 2012] [error] [client 127.0.0.1] PHP Notice: Undefined
variable: entry in C:\\wamp\\www\\examples\\simple_blog\\inc\\update.inc.php
on line 14, referer: http://localhost/examples/simple_blog/admin.php?id=8
[Sun May 27 19:21:24 2012] [error] [client 127.0.0.1] PHP Stack trace:, referer:
http://localhost/examples/simple_blog/admin.php?id=8
[Sun May 27 19:21:24 2012] [error] [client 127.0.0.1] PHP 1. {main}()
C:\\wamp\\www\\examples\\simple_blog\\inc\\update.inc.php:0, referer:
http://localhost/examples/simple_blog/admin.php?id=8
我不知道这些错误是什么。请帮助我。
最佳答案
可能您的服务器配置为 $_POST['title']
不会自动别名为 $title
。手动初始化 $title = $_POST['title']
并对其他使用的 $_POST
项目进行同样的操作。
<?php
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Save Entry'
&& !empty($_POST['title'])
&& !empty($_POST['entry']))
{
$title = $_POST['title'];
$entry = $_POST['entry'];
...
}
关于php - 无法使用php表单将数据插入mysql数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10774605/