简体   繁体   English

如何修复php代码以将数据从html表单传输到数据库

[英]How to fix php code to transfer data from html form to a database

I am trying to get data from a form into a database, have searched all the answers and code on yours and other websites but none of them work.我正在尝试将表单中的数据导入数据库,在您和其他网站上搜索了所有答案和代码,但没有一个有效。

It is connecting to the database OK, but keep getting an error message when submitting the form.它连接到数据库正常,但在提交表单时不断收到错误消息。

Thanks谢谢

My form is我的表格是

<html><head>

<link rel="stylesheet" href="form.css" type="text/css">


<meta charset="utf-8">
</head>

<body>

<h1>A small example page to insert some data in to the MySQL database using 
PHP</h1>

<form action="insert.php" method="post">

Firstname: <input type="text" name="firstname" /><br><br>

Lastname: <input type="text" name="lastname" /><br><br>

<input type="submit" />

</form>

</body>
</html>

My PHP code is我的 PHP 代码是

<?php

$servername = "server";
$username = "username";
$password = "xxxx";
$database = "xxx_com";

$conn = mysqli_connect($servername, $username, $password, $database);
{
    $first_name = $_POST['firstname'];
    $last_name = $_POST['lastname'];

    $dbh->query = "INSERT INTO nametable (firstname, lastname)
    VALUES  ('$_POST[firstname]', '$_POST[lastname]')";
}

if (!mysqli_query($user_info, $connect)) {
    die('Error: ' . mysqli_error());
}
echo “Your information was added to the database.”; 
mysqli_close($connect); 
    ?>

Your html form using您的 html 表单使用

Firstname: <input type="text" name="fname" /><br><br>

Lastname: <input type="text" name="lname" /><br><br>

but your PHP get from但是你的 PHP 从

$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];

it should used the same name.它应该使用相同的名称。 Like喜欢

$first_name = $_POST['fname'];
$last_name = $_POST['lname'];

As mention by people comment, please learn how to avoid the SQL injection problem正如人们评论中提到的,请学习如何避免 SQL 注入问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM