使用PHP

时间:2018-11-15 05:30:26

标签: php html mysql mysqli

我正在尝试使用HTML表单中的PHP将新记录插入SQL数据库。

我使用Post方法制作了表单

<form name="CreatNewMCQ" action="create.php" method="POST">

带有一个提交按钮

<button type="submit" form="CreateNewMCQ">CREATE</button>

我想做的就是当我按下按钮时,它将调用create.php,这是

<?php
$servername = "localhost";
$user = "admin";
$pass = "admin";
$dbname = "examples";

// Create connection
$conn = new mysqli($servername, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$id = $_POST['id'];
$name = $_POST['name'];
$year = $_POST['year'];

$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, $name, $year)";

if ($conn->query($sql) === TRUE) {
    echo "Tạo mới thành công";
} else {
    echo "Lỗi: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

然后将数据从表单插入到SQL数据库(表单的ID,名称,年份)。 我在SQL语法中遇到一些错误。我犯了什么错误?

3 个答案:

答案 0 :(得分:2)

确保所有发布值都正确获取。您应该在插入数据之前进行条件检查,例如:

$id = isset($_POST['id']) ? $_POST['id'] : '';
$name = isset($_POST['name']) ? $_POST['name'] : '';
$year = isset($_POST['year']) ? $_POST['year'] : '';

if($id && $name && $year){
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, '$name', '$year')";
}else{
  return "required fields are missing";
}

注意:如果可能,请发布您的html。

答案 1 :(得分:1)

尝试一下:

<?php
/* Attempt MySQL server connection.*/

$servername = "localhost";
$user = "admin";
$pass = "admin";
$dbname = "examples";

$link = mysqli_connect($servername, $user, $pass, $dbname);

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Attempt insert query execution
$id = $_POST['id'];
$name = $_POST['name'];
$year = $_POST['year'];

$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, '$name', '$year')";

if(mysqli_query($link, $sql)){
    echo "Records inserted successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// Close connection
mysqli_close($link);
?>

答案 2 :(得分:-1)

HTML Form :
<html>
<form name="test" method="post">
Enter name:<input type="text" name="name"/> <br>
Enter year :<input type="text" name="year"/><br>
<input type="submit" name="save" value="save" />
</form>
</html>
php code  :

<?php
$conn=mysql_connect("localhost","root","passward");
$select_db=mysql_select_db("Atul",$conn);
if($conn)
{
    echo "connected";
}
else
{
    echo "Please try again";
}

if(isset($_POST['save']))
{
    $name=$_POST['name'];
    $year=$_POST['year'];
    $insert_record="insert into test (name,year) values("$name","$year");
    $result=mysql_query($insert_record);
    if($result)
    {
        echo "Record inserted successfully";
    }
    else
    {
    echo "please try again";
    }
}
?>