tags:

views:

50

answers:

1

I have a very simple search form, that takes in a term from GET_, and then incorporates this into an SQL query. I am trying to use this string from GET in a paramterized query, like so:

$searchString = '%' . $searchString . '%';
$recordsQuery = "SELECT username, firstname, lastname FROM $table WHERE lastname = $searchString" . $max;

  if ($getRecords = $con->prepare($recordsQuery)) {
        $getRecords->bind_param("s", $searchString);
        $getRecords->execute();
        $getRecords->bind_result($username, $firstname, $lastname);
        $rows = array();

        while ($getRecords->fetch()) {
            $row = array(
                'username' => $username,
                'firstname' => $firstname,
                'lastname' => $lastname,
            );
             $rows[] = $row;
        }
        return $rows;
    }

However, this results in the error

Unkown column 'term' in 'where clause'.

I assume this is becase my term is not quoted, however adding escaped quotes to the variable did nothing.

Any syntax errors or such are a product of modification to ask this question, and do not exist in my actaul code.


OK, I fixed this by changing the following lines:

 $searchstring = "'" . $searchstring . "'";
$recordsQuery = "SELECT username, firstname, lastname FROM $table WHERE lastname = $searchString" . $max;

I am sure this approach is probably bad because it is not paramterized..., but I was unable to get it working any other way.

+1  A: 

You forgot some quotes : $searchString = '"%' . $searchString . '%"';

But why do you build the request like that when you could use bound parameters : http://www.php.net/manual/fr/pdostatement.bindparam.php


$searchString = '%' . $searchString . '%';
$recordsQuery = "SELECT username, firstname, lastname FROM $table WHERE lastname = :lastname" . $max;
if ($getRecords = $con->prepare($recordsQuery)) {
        $getRecords->bind_param(":lastname", "%".$searchString."%");
        $getRecords->execute();
        $getRecords->bind_result($username, $firstname, $lastname);
        $rows = array();
        while ($getRecords->fetch()) {
            $row = array(
                'username' => $username,
                'firstname' => $firstname,
                'lastname' => $lastname,
            );
             $rows[] = $row;
        }
        return $rows;
    }

Arkh
Adding the quotes changed nothing.
Roger Sinks
What is in the $max var exactly ?
Arkh
Just an int, a caluulation done to see how many records to display.
Roger Sinks
So, you have a request like "SELECT username, firstname, lastname FROM $table WHERE lastname = %term%42" ?
Arkh
No, it should be like SELECT username, firstname, lastname FROM USERS WHERE lastname = 'term' LIMIT 0 , 10
Roger Sinks
I updated my question slightly, and will be back in a few hours, thanks for your help!
Roger Sinks