0

This is my code

$PageNumber = $_GET["p"];
if (!isset($PageNumber) || $PageNumber < 1 || !is_int($PageNumber))
    $PageNumber = 1;
$PageSize = 3;
$strSQL = $dbCon->prepare("SELECT * FROM News WHERE isActive = 1 ORDER BY NewsID DESC LIMIT (:PageNumber - 1)*:PageSize, :PageSize;");
$strSQL->bindParam(":PageNumber", $PageNumber, PDO::PARAM_INT);
$strSQL->bindParam(":PageSize", $PageSize, PDO::PARAM_INT);
$strSQL->execute();
$Result = $strSQL->fetchAll();
if (count($Result) != 0) {
    print_r($Result);
} else {
    echo "no record";
}

im sure rows exist but output is no record, When i replace parameters with default value like LIMIT 0,3 it works well.

3 Answers 3

2

Since you are not catching exceptions but i guess that what you are doing wrong .In PDO your bindValue or bindParam variable should be equal to used in query. I mean

$strSQL = $dbCon->prepare("SELECT * FROM News WHERE isActive = 1 ORDER BY NewsID DESC LIMIT :Start, :PageSize;");
$strSQL->bindParam(":Start",($PageNumber - 1)*$PageSize, PDO::PARAM_INT);
$strSQL->bindParam(":PageSize", $PageSize, PDO::PARAM_INT);
Sign up to request clarification or add additional context in comments.

Comments

1

Try this, since you tried using mathematical operators inside prepared statement i just replaced them and did it at the place of assigning.

$PageNumber = $_GET["p"];
if (!isset($PageNumber) || $PageNumber < 1 || !is_int($PageNumber))
    $PageNumber = 1;
$PageSize = 3;
$strSQL = $dbCon->prepare("SELECT * FROM News WHERE isActive = 1 ORDER BY NewsID DESC LIMIT :PageNumber, :PageSize;");
$strSQL->bindParam(":PageNumber", ($PageNumber - 1) * $PageSize, PDO::PARAM_INT);
$strSQL->bindParam(":PageSize", $PageSize, PDO::PARAM_INT);
$strSQL->execute();
$Result = $strSQL->fetchAll();
if (count($Result) != 0) {
    print_r($Result);
} else {
    echo "no record";
}

Comments

0

I think that the problem is that you have used the same token two times (":PageSize").

As said in php documentation of PDO::prepare():

You cannot use a named parameter marker of the same name twice in a prepared statement.

So you can only use once each token, so you must use two different tokens, for example ":PageSizeA" and ":PageSizeB".

$strSQL = $dbCon->prepare("SELECT * FROM News WHERE isActive = 1 ORDER BY NewsID DESC LIMIT (:PageNumber - 1)*:PageSizeA, :PageSizeB;");
$strSQL->bindParam(":PageNumber", $PageNumber, PDO::PARAM_INT);
$strSQL->bindParam(":PageSizeA", $PageSize, PDO::PARAM_INT);
$strSQL->bindParam(":PageSizeB", $PageSize, PDO::PARAM_INT);

Anyway, @user1432124 or @Ramesh's solution is better because it process data in php and not in mysql, witch is where it must be done.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.