parsing results from mysql query

i have a function that query the mysql db for something and im getting an empty array. i know that the search query is correct, what i dont understand is why my code is returning an empty array. Furtherermore i have no errors when running this code.

my code is as follows:

public $results;

public function __construct () {
    require_once'app/model/DB_Con.php';
$this->db = new connection();
$this->db = $this->db->dbConnection();
}

public function _search ($data) {
    $this->query = $this->db->prepare("SELECT * FROM students WHERE name LIKE '%?%'");
    $this->query->bindParam(1, $data);
    $this->query->execute();
    $this->results = $this->query->fetchAll();
    print_r($this->results);
    echo $data;
}

Is there a way to troubleshoot PHP PDO since i dont see the mysql errors (if any).

Thanks.

Answers


PDO has several ways to handle errors, as well query results.

For errors, you may use the options, into the PDO::__construct, such as

new PDO($dsn, $user, $pwd, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

replacing $dsn, $user, $pwd by yours, obviously.

With such a construct, each PDO error will throw an exception, which is probably the best way to handle errors.

In your case, error is probably you fail the query. If you use bind to... bind paramters, you have to ensure parameters is not already escaped. Here, by using like '%?%' into your query, PDO will inject variable AND protect it, and your query will fail. You'll have to change it for like ? then bind you param adding the %, for example, $this->query->bindParam(1, '%'.$data.'%');.

EDIT : more about configuration options : http://php.net/manual/fr/pdo.setattribute.php


Need Your Help

Store attributes in deleted couchbase documents

swift couchbase-lite

I want to be able to save the data inside deleted records in a Couchbase Lite application. According the couchbase lite documentation I should be able to save a deleted_at attribute along with all ...

angular es6, this, scope and el all undefined in jqlite click event

javascript angularjs ecmascript-6

I can't get the link function to work in ES6. There is no context passed upon a click event at all - am I missing something obvious?