PDO execute() statement with placeholder in LIMIT [duplicate] - php

This question already has answers here:
Setting PDO/MySQL LIMIT with Named Placeholders [duplicate]
(2 answers)
Closed 9 years ago.
$pageMin = (($page * 10)-10);
$reponse = $bdd->prepare('SELECT pseudo, message FROM minichat ORDER BY id DESC LIMIT ?, 10');
$reponse->execute(array($pageMin));
It seems like the placeholders don't work for LIMIT...
When I concatenate with pageMin it works, ex:
$reponse = $bdd->query('SELECT pseudo, message FROM minichat ORDER BY id DESC LIMIT' . $pageMin . ', 10');
or even
$reponse = $bdd->prepare('SELECT pseudo, message FROM minichat ORDER BY id DESC LIMIT' . $pageMin . ', 10');
$reponse->execute(array());
Using the placeholder, it does not return me any results, why?
Thank you for helping.

When you pass an array of params to execute they are treated as strings and limit is an int. Just use bindValue with type int.
$reponse->bindValue(1, $pageMin, PDO::PARAM_INT);

Related

num_rows with prepared statement returns 0 rows when equivalent normal query returns more [duplicate]

This question already has an answer here:
Why does mysqli num_rows always return 0?
(1 answer)
Closed 1 year ago.
I am having some problems with prepared statements in Mysqli and I’m not sure why.
I have a database which currently has 3 rows, which I want to select using a SELECT WHERE query. The query which works in PhpMyAdmin is:
SELECT `totalhits`, `totalmisses`, `date`
FROM `performance`
WHERE `domain` = 'test' AND `profileid` = 1
ORDER BY `date` DESC
This shows all three rows (all have domain = test and profileid=1.)
If I run this with a normal query in Mysqli and hard-coded variables, I get the same result:
$query = $conn->query(“SELECT `totalhits`, `totalmisses`, `date` FROM `performance` WHERE `domain` = 'test' AND `profileid` = 1 ORDER BY `date` DESC”);
echo $query->num_rows; //outputs 3
If I try and run it as a parameter query (as I will be using user entered data), I get 0 rows returned:
$stmt = $conn->prepare("SELECT `totalhits`, `totalmisses`, `date` FROM `performance` WHERE `domain` = ? AND `profileid` = ? ORDER BY `date` DESC");
$domain = 'test';
$profileid = 1;
$stmt->bind_param('si', $domain,$profileid);
$stmt->execute();
echo $stmt->num_rows; //outputs 0
No Mysqli errors are generated by any of these lines (using print_r on the object at each point to check). I also added a $stmt->store_result() line after the execute line but still had the same result (should I be doing this anyway?).
The documentation for mysqli_stmt::num_rows misses some detailed information about using num_rows with prepared statements. The description is rather ambiguous in that it refers only to the need to store the result when using the procedural style, but the object-oriented example makes it clear that you need to call the store_result() method before accessing the num_rows property. This means your code should be something like this:
$stmt = $conn->prepare("SELECT `totalhits`, `totalmisses`, `date` FROM `performance` WHERE `domain` = ? AND `profileid` = ? ORDER BY `date` DESC");
$domain = 'test';
$profileid = 1;
$stmt->bind_param('si', $domain,$profileid);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows; //should now output 3

How to bind column = value to a PDO statement [duplicate]

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 7 years ago.
I have a Query like this in my PDO statement:
SELECT * FROM table WHERE ? = ? ORDER BY id DESC
I wanted to bind column name to first ? and the value to second ? (column = value)
I tried many things such as below, but they all fail or return empty array (when there should be result)
This returns empty array
$query = "SELECT * FROM table WHERE ? = ? ORDER BY id DESC"
$db->prepare($query);
$stmt->bindValue(1, $column, PDO::PARAM_STR);
$stmt->bindValue(2, $value, PDO::PARAM_STR);
and this one displays an error
$query = "SELECT * FROM table WHERE column = :value ORDER BY id DESC"
$db->prepare($query);
$stmt->bindColumn('column', $column);
$stmt->bindValue(':value', $value, PDO::PARAM_STR);
Column is variable, so i had to bind it and can't put it in query directly.
What am I doing wrong here? I tried many things but no luck...
Please note that I know how to bind values if column is static, my issue is when column is also variable like above.
It should be bindParam, but you can execute it with an array inside too that's the way I do it:
$query = $db->prepare( 'SELECT * FROM table WHERE column=\':value\' ORDER BY id DESC' );
$query->execute(array(
':value' => $value
));

Whats wrong with my PDO mysql query [duplicate]

This question already has an answer here:
Invalid Parameter Number. Parameter not defined
(1 answer)
Closed 8 years ago.
Here is my code
$sql3= "select *
from comments
where status=:status
limit=:limit
offset=:offset
order by time desc";
$query3= $pdo->prepare($sql3);
$query3->bindValue(":status",'n');
$query3->bindValue(":limit",$per_page);
$query3->bindValue(":offest",$offset);
$query3->execute();
$comments=$query3->fetchall();
Here comments is my table name status and time is two column in my table . Whenever I run this code , It shows a warning
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in E:\XAMPP\htdocs\parlament\user\logged_in_area.php
What does this mean ?
The answer depends of what are limit and offset.
If they're columns names...
You can't use these reserved keywords for column names without backticks
You need to add a AND / OR operator between your lines
$sql3= "select *
from comments
where status=:status
and `limit`=:limit
and `offset`=:offset
order by time desc";
$query3= $pdo->prepare($sql3);
$query3->bindValue(":status", 'n');
$query3->bindValue(":limit", $per_page);
$query3->bindValue(":offest", $offset);
$query3->execute();
$comments=$query3->fetchall();
If they're keywords...
The syntax is LIMIT <n>, not LIMIT = <n> (same for OFFSET)
It better to specify their type with PDO::PARAM_INT (same for OFFSET)
ORDER BY must be added before LIMIT and OFFSET
$sql3= "select *
from comments
where status=:status
order by time desc
limit :limit
offset :offset";
$query3= $pdo->prepare($sql3);
$query3->bindValue(":status", 'n');
$query3->bindValue(":limit", (int)$per_page, PDO::PARAM_INT);
$query3->bindValue(":offset", (int)$offset, PDO::PARAM_INT);
$query3->execute();
$comments=$query3->fetchall();
Adding my answer because nobody has mentioned this specific part yet...
MySQL is very picky about the data type of LIMIT parameters. You pretty much need to use bindParam(':limit', $per_page, PDO::PARAM_INT). I assume the same for OFFSET.
So, in summary
// because E_WARNING level errors are insufficient
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM `comments` WHERE `status` = :status ORDER BY `time` DESC LIMIT :limit OFFSET :offset');
$stmt->bindValue(':status', 'n');
$stmt->bindParam(':limit', $per_page, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT); // spelt "offset"
$stmt->execute();
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
Try this->
$sql3= "select *
from comments
where status = ?
limit ?
offset ?
order by time desc";
$query3= $pdo->prepare($sql3);
$query3->execute(array('n',$per_page,$offset));
$comments=$query3->fetchall();
Not sure about that but I think that PDO::bindValue / bindParam works with variable references. You cannot set a static value as parameter.
Try to replace
$query3->bindValue(":status",'n');
by
$n_value = 'n';
$query3->bindValue(":status",$n_value);
You also forgot the "AND" Keyword between your conditions
You're missing the AND or OR keyword in statement. Also, LIMIT is a reserved keyword, you'll need to backtick it or rename it to something else if you don't want to do that.
$sql3= "select *
from comments
where status = ?
limit= ?
offset= ?
order by time desc";
$query3= $pdo->prepare($sql3);
$query3->bindValue(1,'n');
$query3->bindValue(2,$per_page);
$query3->bindValue(3,$offset);
$query3->execute();
$comments=$query3->fetchall();

Invalid parameter number error

Im having an invalid parameter error but I guess that I have the right number of parameter.
Does anyone see the opposite here?
Im getting this error:
PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in $readNews->execute();
if(isset($_POST['search']))
{
$search = $_POST['search'];
$readNews = $pdo->prepare("SELECT * FROM news WHERE title LIKE ? ORDER BY date DESC LIMIT ?, ?");
$readNews->bindValue(1, $search);
$readNews->bindValue(1, $begin,PDO::PARAM_INT);
$readNews->bindValue(2, $max,PDO::PARAM_INT);
}
else
{
$readNews = $pdo->prepare("SELECT * FROM news ORDER BY date DESC LIMIT ?, ?");
$readNews->bindValue(1, $begin,PDO::PARAM_INT);
$readNews->bindValue(2, $max,PDO::PARAM_INT);
}
$readNews->execute();
You have three parameters yet you assign a value to index 1 twice. Try this...
$readNews->bindValue(1, $search);
$readNews->bindValue(2, $begin,PDO::PARAM_INT);
$readNews->bindValue(3, $max,PDO::PARAM_INT);
I'm guessing you may want to wrap some wildcard characters around the $search value too. Try this...
$readNews->bindValue(1, "%$search%");
... or use CONCAT in your query...
WHERE title LIKE CONCAT('%', ?, '%')
Your query should also use WHERE instead of AND...
SELECT * FROM news WHERE title LIKE ? ORDER BY date DESC LIMIT ?, ?"
I would probably simplify this by using named placeholders to remove some of the duplication. In total, this...
if (isset($_POST['search'])) {
$stmt = $pdo->prepare("SELECT * FROM news WHERE title LIKE CONCAT('%', :search, '%') ORDER BY date DESC LIMIT :begin, :max");
$stmt->bindParam(':search', $_POST['search']);
} else {
$stmt = $pdo->prepare('SELECT * FROM news ORDER BY date DESC LIMIT :begin, :max');
}
$stmt->bindParam(':begin', $begin, PDO::PARAM_INT);
$stmt->bindParam(':max', $max, PDO::PARAM_INT);
$stmt->execute();

Using PDO insert values in the limit clause of an SQL statement? [duplicate]

This question already has answers here:
How to apply bindValue method in LIMIT clause?
(11 answers)
Closed 7 years ago.
In my PDO implementation, I am attempting to use an inserted value in the limit clause of the SQL statement:
$sql = "SELECT * FROM table ORDER BY datetime DESC LIMIT :limit";
$params = array(":limit" => 5);
$query = $dbh->prepare($sql);
$query->execute($params);
$result = $query->fetchall(PDO::FETCH_ASSOC);
$params and $query are correctly returned, but $result is empty.
Upon running print_r($query->errorInfo);, I get the following:
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 ''5'' at line 1
How can I use PDO's insert values in this query? Am I doing it right?
See PHP PDO bindValue in LIMIT
Basically, you need to cast the limit value to int using intval() when binding.
You cannot bind variables into LIMIT clause’s operand (exactly, it probably depends on your database system vendor). Instead, use just string interpolation. :-(
$limit = 5;
$sql = "SELECT * FROM table ORDER BY datetime DESC LIMIT $limit";
$stmt = $dbh->query($sql);
$result = $stmt->fetchall(PDO::FETCH_ASSOC);

Categories