PHP如何把数据提交到MYSQL数据库,其实很简单,多的不说,直接看代码,看完你就明白了。
<!DOCTYPE html>
<?php
header("content-type:text/html; charset=utf-8");
?>
<head>
<meta charset="utf-8" />
</head>
<html>
<body>
<?php
if(isset($_POST['add']))// isset() 只能用于变量,因为传递任何其它参数都将造成解析错误。若想检测常量是否已设置,可使用 defined() 函数。
{
$dbhost = 'localhost:3306'; //mysql服务器主机地址
$dbuser = 'root'; //mysql用户名
$dbpass = '';//mysql用户名密码
$conn = mysql_connect($dbhost, $dbuser, $dbpass);//连接数据库
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
$student_id = addslashes ($_POST['student_id']);//获取name和id一致的值,赋值给$student_id
$student_name = addslashes ($_POST['student_name']);
$student_sex = addslashes ($_POST['student_sex']);
}
else
{
$student_id = $_POST['student_id'];
$student_name = $_POST['student_name'];
$student_sex = $_POST['student_sex'];
}
mysql_query("set names utf8"); //定义编码格式 这个很重要,不加这个可能会引起数据乱码
$sql = "INSERT INTO student ". //插入数据到数据库中
"(student_id,student_name, student_sex) ".
"VALUES ".
"('$student_id','$student_name','$student_sex')";
mysql_select_db('students');
$retval = mysql_query( $sql, $conn);
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);//关闭数据库
}
?>
<form name="form1" method="post" action="<?php $_PHP_SELF ?>">
<div><label>学号:</label><input name="student_id" type="text" id="student_id" /></div>
<div><label>姓名:</label><input name="student_name" type="text" id="student_name" /></div>
<div><label>性别:</label><input name="student_sex" type="text" id="student_sex" /></div>
<input name="add" type="submit" id="add" value="提 交" />
</form>
</body>
</html>
在我们接收用户提交的数据时,为了数据的安全性我们需要使用 get_magic_quotes_gpc() 函数来判断特殊字符的转义是否已经开启。如果这个选项为off(未开启),返回0,那么我们就必须调用addslashes 这个函数来为字符串增加转义。
这里再补充一下magic_quotes_gpc函数和addslashes()函数
magic_quotes_gpc函数在php中的作用是判断解析用户提示的数据,如包括有:post、get、cookie过来的数据增加转义字符“\”,以确保这些数据不会引起程序,特别是数据库语句因为特殊字符引起的污染而出现致命的错误。
默认情况下,PHP 指令 magic_quotes_gpc 为 on,对所有的 GET、POST 和 COOKIE 数据自动运行 addslashes()。不要对已经被 magic_quotes_gpc 转义过的字符串使用 addslashes(),因为这样会导致双层转义。遇到这种情况时可以使用函数 get_magic_quotes_gpc() 进行检测。
具体的你可以百度下哈。