我一直试图让我的HTML表单提交到指定的数据库。我已经尝试了所有我知道但仍然没有结果我似乎无法得到错误。
HTML表格
<form action = "connect.php" method = "post">
<br>
<br>
<br>
<h5 style ="color:White;" style="font-family:verdana" align = "center"><font size = "2">
<fieldset >
<legend>Personal information:</legend>
First name: <br>
<input type = "text" name ="firstname">
<br>
Last name: <br>
<input type = "text" name ="lastname"><br>
Username: <br>
<input type = "text" name = "username"><br>
Password <br>
<input type = "password" name ="password"><br>
School <br>
<input type = "text" name ="school"><br>
Department <br>
<input type = "text" name ="department"><br>
Year Of Study <br>
<input type = "text" name ="studyYear"><br>
Email <br>
<input type = "text" name ="email"><br>
Phone number <br>
<input type = "text" name ="phoneNumber"><br><br>
Gender <br>
<input type = "radio" name = "gender" value ="male">Male<br>
<input type = "radio" name = "gender" value ="female">Female<br>
<input type = "radio" name = "gender" value ="male">Other<br>
<br><br>
<input type ="submit" value ="Insert">
</h5>
</fieldset>
</h5>
</form>
PHP CODE
<?php
// Connect to localhost
$connect = mysqli_connect('localhost', 'root', '', 'sigma');
if(!$connect) {
echo("Didn\'t work ". mysqli_error());
}
// Get values from the form
$ID = $_POST['UserID'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$password = $_POST['password'];
$school = $_POST['school'];
$dept = $_POST['department'];
$studyYear = $_POST['studyYear'];
$email = $_POST['email'];
$phone = $_POST['phoneNumber'];
// SQL query to insert the data collected from the form into the database.
$sql = mysqli_query ($connect, 'INSERT INTO users (firstname, lastname, username, password,
school, department, studyYear, email, phoneNumber)
VALUES ("'.$firstname.'", "'.$lastname.'", "'.$username.'","'.$password.'",
"'.$school.'", "'.$dept.'", "'.$studyYear.'", "'.$email.'", '.$phone.')');
if ($sql)
{
echo 'Inserted';
}
else
{
echo 'Not Inserted';
}
mysqli_close($connect);
?>
答案 0 :(得分:1)
这个查询应该对你有用,它几乎就像Shudhansh一样,但我用双引号包装INSERT查询并删除了每个变量之间的连接,并用自己的单引号将它们包装起来:
$sql = mysqli_query ($connect,
"INSERT INTO users (firstname, lastname, username, password,
school, department, studyYear, email, phoneNumber)
VALUES ('$firstname', '$lastname', '$username', '$password', '$school', '$dept', '$studyYear', '$email', '$phone')");
我在我的本地机器上运行它并且有效。
另外你的connect.php试图从请求中获取$ _POST ['userID']',但是你没有从表单中传递它以便将它们全部停在一起,你应该创建一个auto-将ID递增为处理用户ID的主键。
如果以某种方式投入生产,我建议验证并清理数据并在密码上使用phps password_hashing功能,这是出于明显的安全原因。
答案 1 :(得分:0)
首先检查你的连接
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
如果没问题,请检查结果
if ($result = mysqli_query($connect, $sql)) {
echo "I got the result yeah\n", mysqli_num_rows($result);
}else{
echo "No results buddy."
}