【发布时间】:2018-04-14 12:18:21
【问题描述】:
所以我有一个表格和一些 php 代码来在数据库中输入信息。但是,当我运行 php 文件时,会出现以下错误:
注意:未定义索引:第 24 行 C:\xampp\htdocs\temp\insert.php 中的第一个
注意:未定义的索引:最后在 C:\xampp\htdocs\temp\insert.php 第 25 行
注意:未定义索引:第 26 行 C:\xampp\htdocs\temp\insert.php 中的电子邮件
注意:未定义索引:第 27 行 C:\xampp\htdocs\temp\insert.php 中的消息
致命错误:未捕获的 PDOException:SQLSTATE[23000]:完整性 违反约束:1048 列“第一”不能为空 C:\xampp\htdocs\temp\insert.php:29 堆栈跟踪:#0 C:\xampp\htdocs\temp\insert.php(29): PDOStatement->execute() #1 {main} 在第 29 行的 C:\xampp\htdocs\temp\insert.php 中抛出
这是我的 html 表单:
<form action="insert.php" method="post">
<label for="first" >Firstname:</label>
<input type="text" name="first" id="first" />
<label for="last" >Surname:</label>
<input type="text" name="last" id="last" />
<label for="email" > Email: </label>
<input type="text" name="email" id="email" />
<label for="message">Message:</label>
<textarea name="message" id="message"> Enter your question here and we will get back
to you as soon as possible </textarea>
<input type="Submit">
</form>
这是我的 php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully <br />";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$query=$conn->prepare("INSERT INTO contacts (first, last, email, message) VALUES(?,?,?,?)");
$query->bindParam(1, $first);
$query->bindParam(2, $last);
$query->bindParam(3, $email);
$query->bindParam(4, $message);
$first=$_POST['first'];
$last=$_POST['last'];
$email=$_POST['email'];
$message=$_POST['message'];
$query->execute();
$conn = null;
echo 'Hi '.$_POST['first'].' ' .$_POST['last'] .' thanks for your interest.</br>';
echo 'We will contact you at '. $_POST['email'].' soon.</br>';
?>
【问题讨论】:
-
您从哪里获取 POST 参数以传递给您的查询?
-
大概您没有通过 POST 请求您的
insert.php页面。您必须提交表单才能填充$_POST数组 -
@BRjava 第 24 到 27 行
-
首先你必须定义变量。否则这些变量是未定义的。定义 $first=$_POST['first']; $last=$_POST['last']; $email=$_POST['email']; $message=$_POST['message'];在绑定到查询之前
-
@Stavros Kasapi ,我认为您正在直接运行 insert.php。
标签: php forms undefined-index