本文介绍了使用php将数据插入表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HTML表单如下:

My html form is like below:

<html>
<body>
<form action="createconnection.php" method="post">

Firstname : <input type="text", name="fname"> </br>
Lastname : <input type="test" name="lname"> </br>
Age : <input type="text" name="age"></br>

<input type="submit">

</form>
</body>
</html>

和php文件:
表名和数据库名都很好。

and php file:Table name and db name all are fine.

<?php
// Create connection

$con=mysqli_connect('127.0.0.1:3306' ,'root','root','my_db');
echo "hi";
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="INSERT INTO table1 (Fname, LName, Age)
VALUES
('$_POST[fname]','$_POST[lname]','$_POST[age]')";

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "1 record added";

mysqli_close($con);
?>

我尝试了很多,但是当我执行它没有给出任何东西,没有在表中更新。

I tried very much but when I execute it gives nothing and no update in table.

推荐答案

这是一个非常简单的工作示例,您的代码与准备语句。

Here is a very simple working example of your code with prepared statements.

请注意查询上的询问符号, bind_param s 表示字符串, i 表示整数,

Note the interrogation signs on the query and the bind_param, s means string and i means integer, you can read more here.

因此 ssi 表示我们将收到2个字符串和1个整数条目。

So ssi means we will receive 2 strings and 1 integer entry.

<?php
// Your database info
$db_host = '';
$db_user = '';
$db_pass = '';
$db_name = '';

if (!empty($_POST))
{
        $con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
        if ($con->connect_error)
            die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

        $sql = "INSERT INTO table1 (Fname, LName, Age) VALUES (?,?,?)";
        if (!$stmt = $con->prepare($sql))
            die('Query failed: (' . $con->errno . ') ' . $con->error);

        if (!$stmt->bind_param('ssi',$_POST['fname'],$_POST['lname'],$_POST['age']))
            die('Bind Param failed: (' . $con->errno . ') ' . $con->error);

        if (!$stmt->execute())
                die('Insert Error ' . $con->error);

        echo "Record added";
        $stmt->close();
        $con->close();
}
?>
<html>
<body>
<form action="createconnection.php" method="post">

Firstname : <input type="text", name="fname"> </br>
Lastname : <input type="test" name="lname"> </br>
Age : <input type="text" name="age"></br>

<input type="submit">

</form>
</body>
</html>

这里是使用的SQL表:

Just in case here is the SQL table used:

CREATE TABLE IF NOT EXISTS `table1` (
  `Fname` varchar(50) NOT NULL,
  `LName` varchar(50) NOT NULL,
  `Age` int(3) NOT NULL
);

这篇关于使用php将数据插入表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

查看更多