PHP 向MySQL数据库插入数据
可以通过执行PHP函数的SQL INSERT语句将数据插入到MySQL表中 mysql_query 。下面是一个简单的示例,将一条记录插入到 employee 表中。
示例
尝试以下示例,将记录插入employee表中。
<?php
dbhost = 'localhost:3036';dbuser = 'root';
dbpass = 'rootpassword';conn = mysql_connect(dbhost,dbuser, dbpass);
if(!conn ) {
die('Could not connect: ' . mysql_error());
}
sql = 'INSERT INTO employee '.
'(emp_name,emp_address, emp_salary, join_date) '.
'VALUES ( "guest", "XYZ", 2000, NOW() )';
mysql_select_db('test_db');retval = mysql_query( sql,conn );
if(! retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close(conn);
?>
在真实的应用中,所有的值将使用HTML表单获取,然后使用PHP脚本捕获这些值,最后将它们插入到MySQL表中。
在进行数据插入时,最佳实践是使用函数 get_magic_quotes_gpc() 来检查魔术引号的当前配置是否已设置。如果这个函数返回false,则使用函数 addslashes() 在引号前添加反斜杠。
示例
将此代码放入add_employee.php中,通过使用HTML表单输入数据,然后将其创建到数据库中。
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<?php
if(isset(_POST['add'])) {dbhost = 'localhost:3036';
dbuser = 'root';dbpass = 'rootpassword';
conn = mysql_connect(dbhost, dbuser,dbpass);
if(! conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {emp_name = addslashes (_POST['emp_name']);emp_address = addslashes (_POST['emp_address']);
}else {emp_name = _POST['emp_name'];emp_address = _POST['emp_address'];
}emp_salary = _POST['emp_salary'];sql = "INSERT INTO employee ". "(emp_name,emp_address, emp_salary,
join_date) ". "VALUES('emp_name','emp_address',emp_salary, NOW())";
mysql_select_db('test_db');retval = mysql_query( sql,conn );
if(! retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close(conn);
}else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<table width = "400" border = "0" cellspacing = "1"
cellpadding = "2">
<tr>
<td width = "100">Employee Name</td>
<td><input name = "emp_name" type = "text"
id = "emp_name"></td>
</tr>
<tr>
<td width = "100">Employee Address</td>
<td><input name = "emp_address" type = "text"
id = "emp_address"></td>
</tr>
<tr>
<td width = "100">Employee Salary</td>
<td><input name = "emp_salary" type = "text"
id = "emp_salary"></td>
</tr>
<tr>
<td width = "100"> </td>
<td> </td>
</tr>
<tr>
<td width = "100"> </td>
<td>
<input name = "add" type = "submit" id = "add"
value = "Add Employee">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>