使用PHP将数据添加到MySQL表时遇到问题

时间:2015-02-26 10:22:21

标签: php mysql

我有一个简单的代码,应该通过PHP将数据添加到MySQL表中。我有代码检查机器是否设法连接到数据库,一切都成功通过,但它没有工作。任何人都可以帮我找到问题吗?



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<?php
$mysqlhost="host";
$mysqldatabase="database";
$mysqlusername="username";
$mysqlpassword="password";
$connect=new mysqli($mysqlhost,$mysqlusername,$mysqlpassword);
if (!$connect) {
    die("Connection failed: " . $connect->connect_error);
}
echo "Connected Successfully";
mysqli_select_db($connect,"b33_15887129_Accounts");
$username=$_POST['username'];
$password=$_POST['Password'];
$email=$_POST['Email'];
$gender=$_POST['Gender'];
$tutorgroup=$_POST['tutorgroup'];
	$newaccount="INSERT INTO Users (Username,Password,Gender,Email,Tutor Group)
	VALUES('$username','$password','$email','$gender','$tutorgroup')";
if(!$newaccount){
	die("Failed to create new account.");
	
	}else{
		echo "New Account Successfully Created!";
		
		}
?>
</body>
</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

问题似乎是您没有执行查询。在$newaccount中存储查询后,您应该将后面的if语句替换为该语句:

if(!$connect->query($newaccount))
    die("Failed to create new account. DB Error: [" . $connect->error . "]");
else
    echo "New Account Successfully Created!";

此外,如果您按照我所描述的方式执行此操作,则会显示因查询失败而导致的任何错误消息。

检查here以获取有关如何正确使用mysqli的简单教程。

答案 1 :(得分:1)

执行您的查询,如

mysqli_query($newaccount) or die(mysqli_error());