我试图在db中插入简单的两个值,但它们既不插入也不给出错误。我不知道发生了什么。 我也尝试在if语句之外进行sql查询,但是它没有用。
请帮助
编码文件
<?php
include 'includes/db_connection.php';
if (isset($_POST['submit']))
{
$name = test_input($_POST["name"]);
$fathername = test_input($_POST["fathername"]);
$sql = "INSERT INTO student (name,fathername)
VALUES ('$name','$fathername')";
mysqli_query($conn, $sql);
if(mysqli_query($conn, $sql))
{
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script>
</head>
<body>
<form action="valid_test.php" method="post" id="registration-form">
<div>
Name
<input name="name" data-validation="length alphanumeric"
data-validation-length="6-15"
data-validation-error-msg="User name has to be an alphanumeric value (6-15 chars)">
</div>
<div>
Father Name
<input name="fathername" data-validation="length alphanumeric"
data-validation-length="6-20"
data-validation-error-msg="User name has to be an alphanumeric value (6-20 chars)">
</div>
<div>
<input type="submit" value="Validate">
<input type="reset" value="Reset form">
</div>
</form>
答案 0 :(得分:5)
当我们发布HTML表单时,元素会以name
属性发布。
您缺少提交按钮的name
属性。
变化:
<input type="submit" value="Validate">
要:
<input type="submit" value="Validate" name="submit">
由于您的提交按钮没有name
属性,因此条件
if (isset($_POST['submit']))
未得到满足,因此代码无效。
此外,您正在重复mysqli_query($conn, $sql);
。删除它的第一个实例。
答案 1 :(得分:-1)
首先,在你的PHP中,$ conn:你试图插入一些不存在的东西。第二,你的SQL不太正确,而不是你应该有这样的东西:
$sql = "INSERT INTO student (name, fathername) VALUES (" . $name . ", " . $fathername . ");";
你在问题中做了什么,你把'$ name'和'$ fathername'作为单个字符,你想要的是变量的值,这就是你如何做到的。
此致