PHP准备语句错误

时间:2014-03-06 17:37:33

标签: php

  

致命错误:在非对象中调用成员函数prepare()   /home/melazabi/public_html/assigment/The/include/process.php上线   15

// check if the username exists in the database
// line 15 is the one below:
$statement = $conn->prepare("select * from users where username=? AND password=?");
//prepare statment is to try to stop sql injection
$statement->bindParam(1, $un);
$statement->bindParam (2, $pw);
$statement->execute();

2 个答案:

答案 0 :(得分:1)

由于各种原因,错误告诉您查询失败。

  1. 您的数据库连接失败,无论是身份验证问题还是完全无法连接。

  2. 您的参数未正确定义。

  3. 您可以通过

    进行调试
     print_r($statement->errorInfo());
    

    这将为您提供sql返回的错误。

    也会设置用户变量。如果我猜测没有看到你的其余代码。你可能想要$ _POST ['un']和$ _POST ['pw']

     echo $un;
     echo $pw;
    

    修改

    连接到db:

     $conn = new PDO('mysql:host='SERVERADDRESS';dbname=DBNAME;charset=utf8', 'USERNAME', 'PASSWORD');
    

    然后你的查询

    $statement = $conn->prepare("select * from users where username=? AND password=?");
    //prepare statment is to try to stop sql injection
    $statement->bindParam(1, $un);
    $statement->bindParam (2, $pw);
    $statement->execute();
    

答案 1 :(得分:1)

根据您在your comment中显示的内容:

您正在使用基于mysql_*的连接

$conn = mysql_connect('localhost','admin','admin') or die("error2"); mysql_select_db("admin") or die("error");

使用PDO查询。

您需要使用:(替换为实际的DB凭据)

$dbname = 'admin';
$username = 'admin';
$password = 'admin';

$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
相关问题