sql >> Databasteknik >  >> RDS >> Mysql

Mysql, PDO - Liknande uttalande fungerar inte med bindParam

Du måste binda varje parameter separat, du kan göra det med en andra loop.

function retrieve_search_posts(PDO $pdo, $search_field) {
    /*
     * Get the PDO object as an argument, this function shouldn't care
     * how the PDO object is created, that's the factory's job.
     */

    /*
     * Use $underscored_names or $camelCase for variable names, easier on the eye
     */

    ## Variable initializations ##
    $where = array();

    ##Function start
    $words = preg_split("/\s+/", $search_field);

    for ($i = 0; $i < count($words); $i++) {
        /*
         * We don't need to have the word in here,
         * so we aren't even using the foreach loop, just a normal for
         */
        $where[] .= "`post_title` LIKE ?";
    }
    /*
     * For cleaner code, use an array and implode the pieces with OR,
     * this way, you don't get an OR at the beginning, nor the end.
     */
    $where_string = implode(" OR ", $where);

    $query = <<<MySQL
SELECT  p.post_id, post_year, post_desc, post_title, post_date, img_file_name, p.cat_id
    FROM mjbox_posts p
    JOIN    mjbox_images i
    ON      i.post_id = p.post_id
        AND i.cat_id = p.cat_id
        AND i.img_is_thumb = 1
        AND post_active = 1
    WHERE ?
    ORDER BY post_date DESC
    LIMIT 9
MySQL;

    $sth = $pdo->prepare($query);

    /*
    * Iterate over the array again,
    * this time, we're binding the values based on the index
    */
    foreach ($words as $index => $word) {
        $sth->bindValue($index+1, $word, PDO::PARAM_STR);
    }

    $sth->execute();

    $result = $sth->fetchAll(PDO::FETCH_ASSOC); //Fetch all the results in associative array form

    return $result;

}

Se kommentarerna till koden för att förklara de ändringar som gjorts.



  1. Hämta radprodukt (multiplikation)

  2. uppdatera en mySQL-tabell med C#

  3. Om två samma fält finns infoga annan uppdatering

  4. Välj sökfråga med förskjutningsgräns är för långsam