1

As you can see I'm trying to fetch rows from table while using prepared statements.

$stmt = $conn->prepare("SELECT * FROM table ORDER BY date DESC LIMIT ?, 10");
$stmt->bindParam(1, $row_start, PDO::PARAM_INT);
$stmt->execute();

while($row = $stmt->fetch()) {
echo $row['title'];
echo $row['name'];
}

It doesn't echo anything.

Edit: var_dump is showing this log :

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''0', 10' at line 1" }

Edit 2: Here is how I declare my $row_start

$row_start = "0";
if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] != "0" )
{
$row_start = $_GET['page'];
if ($row_start == "1") {
$row_start = "0";
}else{
$row_start = ($row_start-1) * 10;
}                       
}
14
  • Does your SQL work when you run it straight in the database? Commented Aug 8, 2012 at 16:42
  • @andrewsi Yes! if I replace ? with a number and run it, it does work. Commented Aug 8, 2012 at 16:44
  • Try binding your parameter explicitly as an integer $stmt->bindParam(1, $row_start, PDO::PARAM_INT); Commented Aug 8, 2012 at 16:46
  • 1
    Is there anything returned by the database? Does var_dump($stmt->errorInfo()) print anything? Commented Aug 8, 2012 at 16:57
  • 1
    @xperator - oh, and I made a mistake with the casting code, too - it should be (int) $row_start with a space. Commented Aug 8, 2012 at 17:16

2 Answers 2

3

By default, the value type will be string.

You can set it to an integer like this:

$stmt->bindParam(1, $row_start, PDO::PARAM_INT);

Update:

Even though you are forcing it to INT, it's still passing it as a string.

Look at your error message:

near ''0', 10' at line 1" }

And specifically the ending ' after 0, indicating it is a string.

0'

Update

Manually typecasting the variable is needed, even if you pass the expected PDO type:

$limit = (int) 1;
$limit2 = (int) 1;


$stmt = $pdo->prepare("SELECT * FROM Table LIMIT :limit, :offset");
$stmt->bindParam(":limit", $limit, PDO::PARAM_INT);
$stmt->bindParam(":offset", $limit2, PDO::PARAM_INT);
$stmt->execute();
Sign up to request clarification or add additional context in comments.

1 Comment

Yes I think it's because I am giving that variable string value.
0
$conn->prepare("SELECT * FROM table ORDER BY date DESC LIMIT ?");
$stmt->execute(array(10));

1 Comment

@wanovak is passing the value directly to the statement via execute, not through binding. See php.net/manual/en/pdostatement.execute.php

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.