zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

PHP MySQL向数据库表中插入新记录

mysqlPHP数据库 记录 插入 表中
2023-06-13 09:13:56 时间

PHP MySQL向数据库表中插入新记录

向数据库表插入数据

INSERT INTO 语句用于向数据库表添加新记录。

语法

INSERT INTO table_name

VALUES (value1, value2,....)

您还可以规定希望在其中插入数据的列:

INSERT INTO table_name (column1,column2,...)

VALUES (value1, value2,....)

注释:SQL 语句对大小写不敏感。INSERT INTO 与 insert into 相同。

为了让 PHP 执行该语句,我们必须使用 mysql_query() 函数。该函数用于向 MySQL 连接发送查询或命令。

=======直接用php语句======

<?php

$servername = "localhost";

$username = "root";

$password = "root";

$dbname = "db_user";

// 创建连接

conn = new mysqli(servername, username,password,

mysqli_query($conn,"set namesutf8");

// 检测连接

if ($conn->connect_error) {

die("连接失败: " . $conn->connect_error);

}

$sql = "INSERT INTO stu_info VALUES(NULL,'郭靖',100,100,100)";

if (conn->query(

echo "新记录插入成功";

} else {

echo "Error: " .

}

$conn->close();

?>

========来自web表单的数据插入数据库========

现在,我们创建一个 HTML 表单,这个表单可把新记录插入 "Persons" 表。

这是这个 HTML 表单:

====Add.html代码====

<html>

<head>

<title>添加学生数据表记录</title>

<metahttp-equiv="Content-Type" content="text/html;charset=utf-8" />

</head>

<body>

<h1>添加学生数据表记录</h1>

<hr>

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

<table>

<tr>

<td>姓名: <inputtype="text" name="name_stu"></td>

</tr>

<tr>

<td>语文: <inputtype="text" name="chinese_f"></td>

</tr>

<tr>

<td>数学: <inputtype="text" name="maths_f" ></td>

</tr>

<tr>

<td>英语: <inputtype="text" name="english_f" ></td>

</tr>

<tr>

<td><input type="submit"></td>

<table>

</form>

</body>

</html>

====Add.html代码end====

当用户点击上例中 HTML 表单中的提交按钮时,表单数据被发送到 "insert.php"。"insert.php"文件连接数据库,并通过 $_POST 变量从表单取回值。然后,mysql_query() 函数执行 INSERT INTO 语句,一条新的记录会添加到数据库表中。

下面是 "insert.php" 页面的代码:

====insert.php代码====

<?php

$conn=mysql_connect('127.0.0.1','root','root')or die("数据库连接错误:".mysql_error()); //连接数据库

mysql_select_db("db_user",$conn)or die("数据库访问错误:".mysql_error()); //选择数据库

mysql_query("setnames 'utf8'");//设置设置编码方式,必须要设置,不然中文会乱码

name_stu=_POST[name_stu];

chinese_f=_POST[chinese_f];

maths_f=_POST[maths_f];

english_f=_POST[english_f];

sqlstatement="insertinto stu_infovalues(null,'chinese_f','maths_f','

sql=mysql_query(sqlstatement);

if($sql){

echo"<script>alert('添加成功!');window.location.href='add.php';</script>";

mysql_free_result($sql);

mysql_close($conn);}

?>

====insert.php代码end====

成功

----------------------------

今天就学习到此吧