PDOStatement 对象和 MySQL 用户定义变量

PDOStatement object and MySQL user defined variables

我无法使使用 PDO 对象的脚本和 MySQL 与用户定义的变量一起工作。我了解到使用 PDO 无法在一次调用中执行两个查询,因此我将其拆分为两个 query() 调用。但它仍然无法正常工作。这是我的脚本的摘要(与 MySQL 的连接当然是在不同的文件中完成的,我将它复制到这里,所以它都在一个地方只是为了这个问题的目的):

 $db_hostname = 'localhost';
 $db_username = 'username';
 $db_password = 'pwd';
 $db_name = 'dbname';
 $dsn = "mysql:dbname=$db_name; host=$db_hostname";

 $pdo = new PDO($dsn, $db_username, $db_password);
 $strsql = "SET @num := 0, @tp := ''";

 $result=$pdo->query($strsql);

 $strsql = "SELECT " . $offer . "_tp AS tp, " . $offer . "_level AS best_offer, Price
           FROM (
                SELECT " . $offer . "_tp, " . $offer . "_level, Price, 
                    @num := if(@tp = `" . $offer . "_tp`, @num + 1, 1) as level,
                    @tp := `" . $offer . "_tp` as dummy
                FROM tbl_limit_offers
                WHERE Prod_Code = $procCode) as x               
           WHERE x.level = 1";
 $result = $pdo->query($strsql);
 echo $result->rowCount()

如果我运行那直接在PHPmyAdmin里面查询就returns几条记录。但是,运行将其与 PDO 对象结合我得到:

Fatal error: Call to a member function rowCount() on a non-object

$result 应该是一个 PDOStatement 对象,rowCount() 应该是它的方法之一。那么,为什么它不起作用?

  • 小伙伴们可以的


    $setNumSql = "set @num = ?";
    $stmt = $con->preparedStatement($setNumSql );
    $stmt->executeQuery($num);

    $setTpSql = "set @tp = ?";
    $stmt = $con->preparedStatement($setTpSql);
    $stmt->executeQuery($tp);

    $exampleSql = "select * from tbl where NUM >= @num and TP = @tp";
    $stmt = $con->preparedStatement($exampleSql);
    $stmt->executeQuery();
    return $stmt->fetchAll();

  • 顺便说一句


    $sql = 'SELECT CONCAT(:offer_1, "_tp") AS tp, CONCAT(:offer_2, "_level") AS best_offer ...';

    $binds = array();
    $binds['offer_1'] = $offer;
    $binds['offer_2'] = $offer;

    $stmt = $con->preparedStatement($sql);
    $stmt->executeQuery($binds);

优于



    $sql = "SELECT " . $offer . "_tp AS tp, " . $offer . "_level AS best_offer ...";

我发现我的代码出了什么问题。它是 PDO 对象。设置的时候,dsn不能有任何space。在我删除 $dsn 变量中的 space 之后,一切都按预期进行。 原始 $dsn 变量(无效):

 $dsn = "mysql:dbname=$db_name; host=$db_hostname";

正确方式(分号后没有space):

 $dsn = "mysql:dbname=$db_name;host=$db_hostname";