且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用php将数据插入表

更新时间:2023-12-01 13:07:46

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

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
);