欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

关于PHP数据库的小问题

程序员文章站 2022-06-17 20:14:26
...
PHP 数据库 用户验证 $con=mysql_connect("localhost","root","123456");
if(!$con)
{
die('Could not connect:'.mysql_error());
}
mysql_query("SET NAMES 'utf8'"); //设置字符集
mysql_select_db("manage",$con); //选择数据库
$sql1="
select count(*)
from user
where username=="".$_POST['name']."" and password=="".$_POST['password'].""
LIMIT 1
";
$result=mysql_query($sql1,$con);
红色部分报错。前辈们,在下有两个问题:第一,目前这种格式,应该怎么改,使其正确。第二,你们在验证用户信息时,是这么做的呢?比较简单的那种。

回复讨论(解决方案)

$sql1="select count(*)from userwhere username='".$_POST['name']."' and password='".$_POST['password']."'LIMIT 1";


然后用mysql_num_rows 判断行是否等于1就行。

username='".mysql_real_escape_string($_POST['name'])."' and password='".mysql_real_escape_string($_POST['password'])."

最好做个简单的防注入措施。

http://php.net/manual/en/function.mysql-real-escape-string.php

php5.5以上版本,用mysqli_real_escape_string() 或者 PDO::quote()

$sql1 = "select count(*)from userwhere username='".$_POST['name']."' and password=='".$_POST['password']."'";


$sql1 = "select count(*)from userwhere username='$_POST[name]' and password='$_POST[password]'";

不需要 LIMIT 1
因为没有 group 子句,聚类函数只会取得一条记录

对传入的数据做一下转义处理是必须的,在程序入口处这样就可以了
$_POST = array_map('mysql_real_escape_string', $_POST);

$_POST = array_map('mysql_real_escape_string', $_POST);

如果某$_POST为空,会不会报错?

直接在sql 里使用'$_POST[name]' 之类的不会出错吗..
一般都要 先判断一下吧比如 ISSET之类的.