سؤال

I am having some trouble getting my search query to work. I get this error.

SQLSTATE[HY093]: Invalid parameter number

Here's my code.

<?php
try{
    $sql = "SELECT * FROM `character` WHERE `name` LIKE :search  OR `play` LIKE :search";
    $query = $db->prepare($sql); 
    $query->execute(array(':search' => strip_tags($_POST['search'])));
    $result = $query->fetchAll(PDO::FETCH_ASSOC);
    foreach($result as $row){
            $name = $row['name'];
            $gender = $row['gender'];
            $id = $row['id'];
            echo "<tr>
            <td>". $name ."</td>
            <td>". $gender ."</td>
                <td><a href='characterbio.php?id=". $id ."'>". $name ."'s Bio Page</a></td>
                </tr>";
    }
}catch(PDOException $e){
     die($e->getMessage());
}
?>

Please help me out. Thanks!

هل كانت مفيدة؟

المحلول

According to PDO::Prepare

You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute(). You cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.

So either turn emulation mode on

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);

or change to -

$sql = "SELECT * FROM `character` WHERE `name` LIKE :search1  OR `play` LIKE :search2";
$query = $db->prepare($sql); 
$query->execute(array(':search1' => strip_tags($_POST['search']),':search2' => strip_tags($_POST['search'])));

Also, since you are using LIKE in your query, you will want to add wildcards % to your values

$query->execute(array(':search1' => "%".strip_tags($_POST['search'])."%",':search2' => "%".strip_tags($_POST['search'])."%"));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top