1

I am newbee and want to learn about php, got below code from google.

Not understand this line of the code.

What is the meaning of this line of code $where = ($data_id) ? 'WHERE id = :data_id' : '';

is it mean, if $data_id is not empty than set variable $where to WHERE id = (param data_id)?

How about if i want to change it to WHERE id like (param data_id) ?

<?php
    include 'db.php';
    $id = (isset($_GET['uid'])) ? $_GET['uid'] : NULL;

    getById($id);

     function getById($data_id) {
         $where = ($data_id) ? 'WHERE id = :data_id' : '';
         $sql="SELECT * from tbl_user $where ORDER BY id desc";
         try {
             $db = getDB();
             $stmt = $db->prepare($sql);
             $stmt->bindParam("data_id", $data_id);
             $stmt->execute();
             $listed = $stmt->fetchAll(PDO::FETCH_OBJ);
             $db = null;
             echo '{"data": ' . json_encode($listed ) . '}';
         } catch(PDOException $e) {
             echo '{"error":{"text":'. $e->getMessage() .'}}';
         }
     }
?>
Joseph Goh
  • 689
  • 5
  • 16
  • 38
  • it just means, if the `$data_id` is supplied in the argument, it adds the `WHERE` clause in your query. and that `->bindParam` method is superfluous if you omit the argument, and yes you can change it to `LIKE` if want it, just don't forget the wildcards if you need it. and please, don't manually create JSON strings `echo '{"data": ' `, just use `echo json_encode(array('data' => $listed))` – Kevin Jan 26 '16 at 04:31
  • @Ghost how to change it to `LIKE`, is it `$where = ($data_id) ? 'WHERE id = :%data_id%' : '';`? – Joseph Goh Jan 26 '16 at 04:33
  • just put the placeholders intact, don't put the wildcards there. here's an example of what you're trying to achieve, lots of em already here on SO http://stackoverflow.com/questions/11117134/implement-like-query-in-pdo or this http://stackoverflow.com/questions/7252283/using-named-paramaters-with-pdo-for-like – Kevin Jan 26 '16 at 04:35
  • okay, i got it work. thank you – Joseph Goh Jan 26 '16 at 04:45
  • Possible duplicate of [Reference - What does this symbol mean in PHP?](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – miken32 Jan 26 '16 at 05:52

0 Answers0