0

我正在尝试将 mysqli 连接传递给一个类,以便它使用准备好的语句。但是,我遗漏了一些东西并且它不起作用。艾做错了什么?

以下代码输出“否”

索引.php

$db_host = 'localhost';
$db_name = 'my_database';
$db_user = 'my_user';
$db_password = 'my_password';

$con = new mysqli($db_host,$db_user,$db_password,$db_name);
if (mysqli_connect_errno())
{
    die(mysqli_connect_error()); 
}

$obj = new Obj( $con );

对象文件

Class Obj
{
    public function __construct( mysqli $con )
    {
        $sql = "SELECT * FOM myTable";
        if($con->prepare( $sql ))
        {
            echo "yes";
        }
        else
        {
            echo "no";
        }        
    }
}
4

2 回答 2

0
Class Obj {
  public function __construct( mysqli $con ) {
    $sql = "SELECT * FROM myTable";
    if($con->prepare( $sql ))       //here, u pass $slq before
    {
        echo "yes";
    }
    else {
        echo "no";
    }
  }
}
于 2013-02-04T09:57:44.540 回答
0

如果您未能将 mysqli 连接传递给您的班级,您将在此行收到致命错误:

public function __construct( mysqli $con )
                             ^^^^^^

但不仅构造函数开始运行良好,您甚至可以访问类方法:

if($con->prepare( $sql ))

总而言之,所有发生的事情都是因为准备 SQL 语句时出错而mysqli::prepare()返回。false我对 mysql 不熟悉,但您可以使用mysqli::$error_listmysqli::$error获得确切的错误消息:

    if($con->prepare( $slq ))
    {
        echo "yes";
    }
    else
    {
        echo "no: " . $con->error;
    } 

If SELECT * FOM myTable is the actual query, I suppose it's a simple syntax error since you've misspelt FROM.

于 2013-02-04T10:00:46.793 回答