要将数据插入到MySQL的表中,需要使用SQL INSERT INTO
命令。可以使用mysql>
提示或使用任何脚本(如PHP)将数据插入到MySQL表中。
下面是插入数据到MySQL表的INSERT INTO
命令的通用SQL语法:
INSERT INTO table_name
( field1, field2,...fieldN )
VALUES
( value1, value2,...valueN );
使用PHP脚本插入数据
可以使用相同的SQL INSERT INTO
命令在PHP函数mysqli_query()
中以将数据插入到MySQL表中。
示例
这个例子将从用户接收三个参数,并将它们插入到MySQL表中 -
<html>
<head>
<title>PHP插入数据到MySQL表中</title>
<link rel = "stylesheet" type = "text/css" href = "style.css">
</head>
<body>
<div id = "main">
<form action = "" method = "post">
<label>用户名 :</label>
<input type = "text" name = "username" id = "username" />
<label>密码 :</label>
<input type = "password" name = "password" id = "password" />
<input type = "submit" value ="提交" name = "submit"/>
<br />
</form>
</div>
<?php
if(isset($_POST["submit"])){
$servername = "localhost:3306";
$username = "root";
$password = "123456";
$dbname = "testdb";
/** 表结构
CREATE TABLE `test_userinfo` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL,
`passwd` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
*/
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
$sql = "INSERT INTO test_userinfo(username, passwd)VALUES ('$username', '$password')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($conn);
}
$conn->close();
}
?>
</body>
</html>
执行上面示例代码,得到类似以下结果 -