我正在使用php创建一个数据库,并在html中查看表。在我的编码中,我编写了一个"添加/插入"函数,用提交按钮插入到表中。选择提交按钮后,我会看到上面列出的错误消息。我不确定我改变了什么,我昨晚(在另一台电脑上)运行了这个代码,一切都很好!?!有人有什么想法吗??
以下是TABLE、insert info、add.html和insert.php 的插入脚本的代码
<?php
$con=mysqli_connect("localhost","root","","Franchise_Call_Log");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create table
$sql="CREATE TABLE caller_info(caller_id int(11) unsigned auto_increment primary key not null,
Firstname varchar(35) not null, Lastname varchar(35) not null,
Franchise varchar(25) not null)";
// Execute query
if (mysqli_query($con,$sql))
{
echo "Table caller_info created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
?>
<?php
$con=mysqli_connect("localhost","root","","Franchise_Call_Log");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO caller_info (Firstname, Lastname, franchise)
VALUES ('Peter', 'Griffin',Minneapolis)");
mysqli_query($con,"INSERT INTO caller_info (Firstname, Lastname, Franchise)
VALUES ('Maggie', 'DeJesus',Virginia)");
mysqli_close($con);
?>
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Franchise: <input type="text" name="franchise">
<input type="submit">
</form>
</body>
</html>
<?php
$con=mysqli_connect("localhost","root","","Franchise_Call_Log");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO caller_info (Firstname, Lastname, Franchise)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[franchise]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
*更新我能够通过更改我的文件名来解决上面的问题,但现在再次运行所有内容,我遇到了以下消息:
注意:未定义的索引:第11行C:''examplep''htdocs''Final Tests''insert.php中的Firstname
注意:未定义的索引:第11行C:''examplep''htdocs''Final Tests''insert.php中的姓氏
注意:未定义的索引:第11行C:''examplep''htdocs''Final Tests''insert.php中的特许经营增加了1条记录
尽管这只是一个通知,但在选择表时,新记录并不存在。有一个断开的地方,我没有赶上。有什么想法吗?
您使用
$sql="INSERT INTO caller_info (Firstname, Lastname, Franchise)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[franchise]')";
但是,在引用$_POST值(例如:$_POST[xyz])时,并没有引用xyz名称。应该是:
$sql="INSERT INTO caller_info (Firstname, Lastname, Franchise)
VALUES
('{$_POST['firstname']}','{$_POST['lastname']}','{$_POST['franchise']}')";
我在$_POST['xyz']周围添加了{}-括号,这样php就可以正确地识别变量。当然,您现在要接受SQL注入(请参阅How can I prevent SQL injection in PHP?)
如果您将表单提交到同一页面,则将操作字段留空:
<form action="" method="post">
指定提交按钮的名称:
<input type="submit" name="submit">
如果设置了提交(按下提交),则将值插入数据库:
if(isset($_POST['submit'])){
$sql="INSERT INTO caller_info (Firstname, Lastname, Franchise)
VALUES('".$_POST['firstname']."','".$_POST['lastname']."',
'".$_POST['franchise']."')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}