无法在php mysql中设置绑定参数

时间:2016-08-10 11:29:47

标签: php mysql prepared-statement

这是我的php-mysql选择查询

$servername = "localhost";
$username = "root";
$password = "mukund";
$dbname = "dbdata";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
else
{

        $uname="admin";
        $pass = "admin";
        $pass = md5($pass);

$sql = "SELECT ID,NAME,ROLE FROM USERDETAIL WHERE USERNAME = ? AND PASSWORD = ? AND STATUS = 'VERIFIED'";  

     if(!$stmt = $conn->prepare($sql))
     {
         echo 'stmt failed'.$mysqli->errno."<br>" ;
     }

if(!$stmt->bind_param('s', $uname))
{
        echo "failed bind  : ".$stmt->errno.": > ".$stmt->error."<br>";
}
if(!$stmt->bind_param("s", $pass))
{
        echo "failed bind2 : ".$stmt->errno.": > ".$stmt->error."<br>";
}




if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

$uid="";
 $result = $stmt->get_result();
 echo $count = mysqli_num_rows($result);

    if($count>0)
    {

          echo 'result obtained';  
        }
        }

这是获得的输出

failed bind : 0: >

failed bind2 : 0: >

Execute failed: (2031) No data supplied for parameters in prepared statement 

但是同样的代码我用不同的格式重写了!!!以下是工作代码

$servername = "localhost";
$username = "root";
$password = "mukund";
$dbname = "dbdata";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$uname ="admin";
$pass = "admin";
$pass = md5($pass);
$sql = "SELECT ID, NAME FROM USERDETAIL WHERE USERNAME = '$uname' AND PASSWORD = '$pass' AND STATUS = 'VERIFIED'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["ID"]. " - Name: " . $row["NAME"]. " ". "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();

输出

id: 1 - Name: Administrator 

我不知道我在第一个做错了。我听说php中的mysql查询更安全。请帮帮我

1 个答案:

答案 0 :(得分:2)

使用单个函数调用绑定所有参数:

$stmt->bind_param('ss', $uname, $pass)

另外,永远不要使用第二种方法。绑定参数是避免SQL注入漏洞的唯一方法,如here所述。