PHP登录脚本SQL错误 [英] PHP login script SQL error

查看:91
本文介绍了PHP登录脚本SQL错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对SQL和PHP还是很陌生.

我正在尝试编写一个简单的登录脚本.我在HTML文档中有一个表单,已证明可以将正确的数据发布到所需的2个变量中,但是我的脚本在执行SQL时失败...

我也已经在mysqlWorkbench中测试了SQL,并且得到了想要的结果?

请帮助.

这是我的剧本:

<?PHP

$odbc = mysql_connect('localhost', 'root', '') or die ("could not connect to database");
mysql_select_db('examresults', $odbc)  or die("Could not find database");

// username and password sent from form 
$username=$_POST['username']; 
$password=$_POST['password']; 

$sql='SELECT * FROM tuser where username = '.$username.' and password = '.$password.'';

$result = mysql_query($sql, $odbc) or die ("Error in SQL");

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

 //If result matched username and password, table row must only equal 1 row
if($count==1)
{   
    header("location:exammenu.php");
}
else 
{
    echo 'username and password do not match';
}
?>

解决方案

注意:不推荐使用mysql_*函数,您不应再使用它们.您的代码也容易受到SQL注入的攻击.<​​/p>

使用mysql_error而不是仅打印出"SQL中的错误"将为我们(和您)提供更详细的sql错误消息.但是很可能失败了,因为您忘记在查询中的字符串周围加上" "了.

$sql='SELECT * FROM tuser where username = "'.$username.'" and password = "'.$password.'"';

I'm fairly new to SQL and PHP.

I'm trying to write a simple login script. I have a form in a HTML document that I have proved posts the correct data into the 2 variables required but my script fails when it executes the SQL...

I've also tested the SQL in mysqlWorkbench and I get the result I want ???

Please help.

Here is my script:

<?PHP

$odbc = mysql_connect('localhost', 'root', '') or die ("could not connect to database");
mysql_select_db('examresults', $odbc)  or die("Could not find database");

// username and password sent from form 
$username=$_POST['username']; 
$password=$_POST['password']; 

$sql='SELECT * FROM tuser where username = '.$username.' and password = '.$password.'';

$result = mysql_query($sql, $odbc) or die ("Error in SQL");

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

 //If result matched username and password, table row must only equal 1 row
if($count==1)
{   
    header("location:exammenu.php");
}
else 
{
    echo 'username and password do not match';
}
?>

解决方案

Note: mysql_* functions are deprecated, you should not use them anymore. Your code is also vulnerable to SQL Injections.

Using mysql_error instead of just printing out "Error in SQL" would give us (and you) a more detailed sql error message. But most likely it is failing because you forgot to put " " around your strings in the query.

$sql='SELECT * FROM tuser where username = "'.$username.'" and password = "'.$password.'"';

这篇关于PHP登录脚本SQL错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆