使用PHP中的url参数进行MySQL查询

时间:2014-03-24 03:45:33

标签: php mysql url-parameters

首先,这是我第一次尝试PHP ..

这是代码:

<?php
if (isset($_GET['name']) && isset($_GET['password']) 
$uname = $_GET['name'];
$pass = $_GET['password'];
$conn = mysql_connect("localhost","DBusername","DBpassword");
mysql_select_db("DBname",$conn);
$result = mysql_query("SELECT * FROM table WHERE username=$uname and password =$password");
$row  = mysql_fetch_array($result);
if(is_array($row)) {
$ip = $row[ip];
 echo $ip ;
}else {
echo = "Invalid Username or Password!";
}
?>

当我尝试此链接时:http://www.mywebsite.com/page.php?name=user&password=mypassword

这是一个隐藏页面,我用它来获取我的录制成员IP地址,当用户 尝试登录用C#

编写的Windows窗体应用程序

总是得到一个空白页..

提前致谢

2 个答案:

答案 0 :(得分:5)

使用单引号包围变量,并在结尾添加die(mysql_error());,如图所示。

$result = mysql_query("SELECT * FROM `dvtmembers` WHERE username='$uname' and password ='$pass'") or die(mysql_error());

警告:您的代码对SQL注入攻击持开放态度。

其他重大错误。

  • 应该是$uname而不是$uanme
  • 您在isset构建
  • 之后错过了一个括号
  • 您正在对echo声明进行分配。

修改后的代码

<?php
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);

if (isset($_GET['name']) && isset($_GET['password']))
{
$conn = mysql_connect("localhost","DBusername","DBpassword");
mysql_select_db("DBname",$conn);
$uname = mysql_real_escape_string($_GET['name']);
$pass = mysql_real_escape_string($_GET['password']);
$result = mysql_query("SELECT * FROM table WHERE username='$uname' and password ='$pass'") or die(mysql_error());
$row  = mysql_fetch_array($result);
if(is_array($row)) {
    $ip = $row['ip'];
    echo $ip ;
}else {
    echo "Invalid Username or Password!";
}
}
else { echo "Name and Password was not passed !";}
?>

mysql_*)扩展程序自PHP 5.5.0起已弃用,将来会被删除。相反,应使用MySQLiPDO_MySQL扩展名。切换到PreparedStatements甚至可以更好地抵御SQL注入攻击!

答案 1 :(得分:2)

在$ row [&#39; ip&#39;]和变量中也使用单引号。您的查询是有效的(SQl注入),因此最好使用mysql_real_escape_string()来获取名称,密码等参数。

   <?php
echo "<br/> Outside loop"; 

   if (isset($_GET['name']) && isset($_GET['password']) {
echo "<br/> Inside if loop"; 

    $uname =  mysql_real_escape_string($_GET['name']);
    $pass =  mysql_real_escape_string($_GET['password']);
    $conn = mysql_connect("localhost","DBusername","DBpassword");

if($conn == false ){ echo "Database not connected. DB error. " ; } 
echo "<br/> after connection "; 

    mysql_select_db("Tablename",$conn);
echo "<br/> after db selection"; 

    $result = mysql_query("SELECT * FROM dvtmembers WHERE username= '$uname' and password = '$pass' ") or die(mysql_error());
    $row  = mysql_fetch_array($result);
    if(mysql_num_rows($result) > 0) {
    $ip = $row['ip'];
     echo $ip ;
echo "<br/>final If loop"; 

    }else {
echo "<Br/> final else loop"; 

    echo = "Invalid Username or Password!";
    }
}
else { 

echo "Parameters are not passed" ; 
} 
    ?>