我开始学习PHP,并且需要您的帮助,因为我正在尝试在MySQL数据库上进行编写。该脚本似乎很好(对我来说:D),并且没有给我错误。但是,当我提交查询时,数据没有出现在我的MySQL数据库中。你能帮我吗?
这是我的HTML / PHP代码:
<?php
session_start();
$_SESSION['message'] = '';
//connection variables
$host = '127.0.0.1';
$user = 'root';
$password = 'MyPassword';
$database= 'test';
$port= '3306';
//create mysql connection
$mysqli = new mysqli($host, $user, $password,$database,$port);
if ($mysqli->connect_errno) {
printf("Connection failed: %s\n", $mysqli->connect_error);
die();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $mysqli->real_escape_string($_POST['name']);
$email = $mysqli->real_escape_string($_POST['email']);
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ('$name','$email')") == true) {
$_SESSION['message'] = "registration succesfull! Added $name to the database";
} else {
$_SESSION['message'] = "User can't be added to the database";
}
}
?>
<!DOCTYPE html>
<html>
<center>
<h1>Inputs</h1>
<form class="form" action="welcome.php" method="post" autocomplete="off">
<div class="alert alert-error"><?= $_SESSION['message'] ?></div>
<input type="text" name="name" placeholder="Insert your name" /> <br>
<input type="email" name="email" placeholder="Insert your email"/><br>
<input type="submit" name="submit" placeholder="Submit"/>
</form>
</center>
</html>
这是数据库: [表格结构] [] 1 [数据库信息]
答案 0 :(得分:0)
请使用预先声明的语句并绑定参数:http://php.net/manual/en/mysqli-stmt.bind-param.php
您还可以使用error_list
调试mysql服务器响应:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$stmt = $mysqli->prepare("INSERT INTO `contatti` (`name`, `email`) VALUES (?,?)");
$stmt->bind_param('ss', $name, $email);
if ($stmt->execute()) {
/* ... */
}
else {
$errors = $stmt->error_list;
/* ... */
}
}
答案 1 :(得分:0)
如果可能的话,您应该对MYSQL和PHP使用准备好的语句,至少是为了防止SQL注入(SO Ref)。
也就是说,当您阅读此行时:
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ($name,$email)") == true)
您正在将字符串连接到没有引号的SQL查询中,并且查询字符串看起来像($ name ='test',$ email ='test @ test':
INSERT INTO 'contatti' ('name', 'email') VALUES (test,test@test)
:语法错误
您必须在SQL上转义字符串:
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ('$name', '$email' )") == true)
结果查询应类似于:INSERT INTO 'contatti' ('name', 'email') VALUES ('test','test@test')
编辑:,请注意,表(contatti)和字段名称(名称,电子邮件)应以加上反引号而不是单引号包围(我不能用引号将反引号引起来),变量$ name和$ email用单引号引起来
答案 2 :(得分:-1)
查询中存在语法错误,请尝试在此处的if条件内更改INSERT
查询:
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ('$name','$email')") == true) {
$_SESSION['message'] = "registration succesfull! Added $name to the database";
} else {
$_SESSION['message'] = "User can't be added to the database";
}
要这样:
if ($mysqli->query("INSERT INTO contatti (name, email)
VALUES('$name', '$email')") == true) {
$_SESSION['message'] = "registration succesfull! Added $name to the database";
} else {
$_SESSION['message'] = "User can't be added to the database";
}