简体   繁体   中英

Prepared statement with PHP and MSSQL

I have an odd scenario about pdos. With prepared statements I get 0 results from database. But hardcoded I get normal results. This is a sql query for mssql (< 2012) to get limited results.

Prepared Statement (just do not wonder about the top and offset variable. I'm setting those in the function just for testing purpose. Also $conn is edited for stackoverflow. The prepare function is reachable from the function, so there is no problem):

public function myFunction($top, $offset) {
    try {
        $top = 20;
        $offset = 1;

        $sql = "SELECT TOP :top * FROM (
            SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS t1
            FROM myTable) AS nU WHERE t1 >= :offset";

        $statement = $conn->prepare($sql);
        $statement->execute(array(':top' => $top, ':offset' => $offset));

        return $statement->fetchAll();

    } catch (Exception $e) {
        echo $e->getMessage();
    }
}

Result is an array with 0 elements.

But with this it works perfectly:

public function myFunction($top, $offset) {
    try {
        $top = 20;
        $offset = 1;

        $sql = "SELECT TOP 20 * FROM (
            SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS t1
            FROM myTable) AS nU WHERE t1 >= 1";

        $statement = $conn->prepare($sql);
        $statement->execute();

        return $statement->fetchAll();

    } catch (Exception $e) {
        echo $e->getMessage();
    }
}

With this I get results correctly.

How this is possible? What's wrong with the prepared statement? I have a lot of prepared statements and it worked fine before.

Thanks for answers.

@EDIT - updated code - still not working:

public function myFunction($top, $offset) {
    try {
        $top = 20;
        $offset = 1;

        $sql = "SELECT TOP :top * FROM (
            SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS t1
            FROM myTable) AS nU WHERE t1 >= :offset";

        $statement = $conn->prepare($sql);

        $statement->bindParam(':top', $top, PDO::PARAM_INT);
        $statement->bindParam(':offset', $offset, PDO::PARAM_INT);

        $statement->execute();
        return $statement->fetchAll();
    } catch (Exception $e) {
        echo $e->getMessage();
    }
}

It's not allowed to use parameter bindings in PDO for SELECT and FROM part of a sql query.

I replaced the whole query with another one where I don't have to set TOP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM