PDOStatement对象和MySQL用户定义的变量

时间:2015-01-29 08:42:11

标签: php mysql pdo

我无法使用这个使用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中运行该查询,则会返回多条记录。但是,运行它与PDO对象我得到:

  

致命错误:在非对象

上调用成员函数rowCount()

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

2 个答案:

答案 0 :(得分:0)

  • 你可以做伙伴


    $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 ...";

答案 1 :(得分:0)

我弄清楚我的代码出了什么问题。这是PDO对象。设置时,dsn不能有任何空格。删除$dsn变量中的空格后,一切都按预期工作。 原始$dsn变量(不起作用):

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

正确的方式(分号后没有空格):

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