Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP + PDO Pagination while Searching in multiple columns

I'm getting a syntax error while trying to do php pagination in a database search. What am I doing wrong?

Function:

public function searchItem1($search, $page) {
        $limit = '5';
        $start = ($page * $limit)-5;
        echo $start;
        $where = array();

        $words = preg_split('/[\s]+/', $search);

        array_unshift($words, '');
        unset($words[0]);

        $sqlstring = implode(" OR ", array_fill(0, count($words), "itemname LIKE ?"));

        $sql = "SELECT * FROM item WHERE $sqlstring LIMIT ? OFFSET ?";
        echo $sql;
        $stmt = $this->db->prepare($sql);
        foreach ($words AS $index => $word) {
            $stmt->bindValue($index, "%" . $word . "%", PDO::PARAM_STR);
        }
        $stmt->bindValue($index + 1, $limit, PDO::PARAM_INT);
        $stmt->bindValue($index + 2, $start, PDO::PARAM_INT);
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''5' OFFSET 0' at line 1' in C:\xampp\htdocs\aDatabase2\class.user.php:312 Stack trace: #0 C:\xampp\htdocs\aDatabase2\class.user.php(312): PDOStatement->execute() #1 C:\xampp\htdocs\aDatabase2\test.php(59): USER->searchItem1('dois', '1') #2 {main} thrown in C:\xampp\htdocs\aDatabase2\class.user.php on line 312

like image 460
Helder Ferreira Avatar asked Nov 26 '25 13:11

Helder Ferreira


1 Answers

Actually, I never could pass "limit" statements by binding them through PDO. You may pass them by concatening on query like:

$sql1 = "SELECT * FROM item WHERE itemname LIKE ? OR description LIKE ? LIMIT $limit OFFSET $start";

[EDIT] After doing that, i forgot to say that you have to delete the lines with the "bindings"

    $stmt->bindValue($index + 1, $limit, PDO::PARAM_INT);
    $stmt->bindValue($index + 2, $start, PDO::PARAM_INT);
like image 127
Arthur Oliveira Avatar answered Nov 29 '25 01:11

Arthur Oliveira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!