0

dbaccess.php file have below code.

<?php
   Class Connection {
   private  $server = "mysql:host=localhost;dbname=cloudways";
   private  $user = "root";
   private  $pass = "";
   private $options  = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE 
   => PDO::FETCH_ASSOC,);
   protected $con; 
        public function openConnection()
         {
           try
             {
              $this->con = new PDO($this->server, $this->user,$this->pass,$this->options);
              return $this->con;
              }
           catch (PDOException $e)
             {
                 echo "There is some problem in connection: " . $e->getMessage();
             }
         }
    public function closeConnection() {
    $this->con = null;
   }
 }
?>

I have been trying to select records from my table with LIKE operator using below code.

<?php  

include_once 'dbaccess.php';

$vaddr   = $_POST['addr'];

$database = new Connection();
$db = $database->openConnection();

$statement = $db->prepare("SELECT  address,
                                   studentno, 
                                   deptno 
                        FROM       student
                        WHERE      address  like :vaddr");

$statement->execute(array(':vaddr' => $vaddr));          


while ($row = $statement->fetch(PDO::FETCH_ASSOC)) 
    {
        $vaddr = $row['address'];
        $type = $row['type'];
        echo "$vaddr has the type $type<br>";
    }
 ?>;

If anyone can let me know how this works with PDO prepare statement. Connection is proper and it gets connected successfully. The issue is with the way I wrote this code.

  • 1
    Depends on if you want the wildcard before/after or both, but the quickest (IMHO) is `array(':vaddr' => "%".$vaddr."%")` – Nigel Ren Jun 08 '20 at 07:03
  • 1
    or just `array(':vaddr' => "%$vaddr%")` which takes less finger twisting – Your Common Sense Jun 08 '20 at 07:06
  • Nigen i am new to this php so did not know how i should write..that is why typed whole code..i did not get it with one line...or where should i change...link you shared also made me confused. Why to disable this question? any new beginner with find one liner code for this question...let someone use this.. – Master Blaster Jun 08 '20 at 07:51

0 Answers0