我无法通过练习注册表单将数据提交到我的数据库......
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$name = $email = $password = "";
?>
<form method="post">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Password: <input type="text" name="password">
<br><br>
<input type="submit" value="Submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
function fix_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
答案 0 :(得分:1)
缺少表名
mysql_query("INSERT INTO ...... ('username','password') VALUES ('$name', md5('$password'))");
答案 1 :(得分:1)
除了Ugur的回答,你的mysqli命令和mysql命令不匹配。以下是如何以面向对象的方式执行此操作:
// create mysqli database object
$mysqli = new mysqli_connect("localhost","username","password","database");
// store your query in a variable. question marks are filled by variables
$sql = "INSERT INTO table_name ('username','password') VALUES (?,?)";
// prepare command uses $sql variable as query
$stmt = mysqli->prepare($sql);
// "ss" means your 2 variables are strings, then you pass your two variables.
$stmt->bind_param("ss",$name,md5($password));
// execute does as it seems, executes the query.
$stmt->execute();
// then print your success message here.
使用预准备语句无需清理用户输入,因为有害输入不会直接替换为查询。欲了解更多信息:
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
在许多不同的场景中使用预准备语句有一些很好的技巧,而且在底部,有一个关于准备语句如何阻止SQL注入的解释。
答案 2 :(得分:1)
您将mysql_*
与mysqli_*
个函数混合在一起,即:mysqli_connect
和mysql_query
并且您将列名包装在引号中,而且您错过了要插入的表名。
尝试以下固定代码:
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysqli_query("INSERT INTO `your_table` (`username`,`password`) VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
您还使用可追溯到1996年的密码存储技术。MD5
不再被认为是安全的。
我建议您查看PHP的password
函数:http://php.net/password
如果您的fix_input()
功能出现问题,则应考虑使用mysqli_real_escape_string()
功能。
然后在将变量传递给它时设置数据库连接。
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
而不是使用:
$name = fix_input($_POST["name"]);
使用以下内容:
$name= mysqli_real_escape_string($db, $_POST['name']);
并为其他人做同样的事。
答案 3 :(得分:0)
您的查询中没有表名!也不要在列名中使用引号:)
你混淆了mysqli和mysql 改变 mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
到
mysqli_query("INSERT INTO yoour_table(username',password) VALUES ('$name', md5('$password'))");