-4

Possible Duplicate:
How do I create a PDO parameterized query with a LIKE statement in PHP?

My sql statement initially was like this:

"SELECT companyname, axiscategory 
FROM axispl WHERE companyname 
LIKE '$searchterm%' LIMIT 11"

Now I want to change this to PDO format. Doubt I have is regarding the wild cards I have used in the searchterm (anything starting with...). How do I achieve this in PDO form?

I wrote the code till WHERE. Then when it came to writing companyname = : ... I was stuck.

$query = $db->prepare("SELECT companyname, axiscategory 
FROM axispl WHERE companyname 
LIKE '$searchterm%' LIMIT 11");
0

2 Answers 2

3

Prepared statement are useful because they separate the query and the parameters. Concatenation is now something to forget.

$query = $db->prepare("SELECT companyname, axiscategory 
    FROM axispl WHERE companyname 
    LIKE :searchterm LIMIT 11");

$query->bindValue('searchterm',$searchterm.'%');
$query->execute();
//then to fetch the results
$query->fetch(PDO::FETCH_ASSOC);

Here I used named parameters as they are more readable, but you can also use indexed parameters like that :

$query = $db->prepare("SELECT companyname, axiscategory 
    FROM axispl WHERE companyname 
    LIKE ? LIMIT 11");

$query->bindValue(1,$searchterm.'%');
$query->execute();
1
$query = $db->prepare("SELECT companyname, axiscategory
                       FROM axispl
                       WHERE companyname LIKE ?
                       LIMIT 11");

Then you execute it using $query->execute(array($searchterm.'%'));

Not the answer you're looking for? Browse other questions tagged or ask your own question.