Micheal Micheal - 6 months ago 33
PHP Question

Serach database not working in php pdo

Please i have been trying to make search in php pdo but is not working when i search it will only show the current title i searched for.
I have been using MYSQL but is showing error at the top of my page but is searching very well like i wanted it to be please can someone convert this Mysql to PDO for me or MYSQLI but i prefer PDO because i understand it more

here is my PHP to get search using mysql

<?php require_once("_inc/dbcontroller.php"); $db_handle = new DBController();?>
<?php
if(isset($_GET['q'])){
$button = mysql_real_escape_string($_GET ['t']);
$search = mysql_real_escape_string($_GET ['q']);
$construct = "";
if(!$search)
echo 'The Query String field is required.';
else{
if(strlen($search)<=1)
echo 'The Query String is too short.';
else{
echo "You searched for <b>$search</b> <hr size='1'></br>";
mysql_select_db("your database name");
$search_exploded = explode (" ", $search);

foreach($search_exploded as $search_each){
$x =0; $x++;
if($x==1){$construct .="title LIKE '%$search_each%'";}
else {
$construct .="AND blog LIKE '%$search_each%' AND tags LIKE '%$search_each%'";
}
}
$construct ="SELECT * FROM blogtd WHERE $construct AND action = 'active'";
$run = mysql_query($construct);

$foundnum = mysql_num_rows($run);
if($foundnum==0)
echo "Sorry, there are no matching result for";
else{
echo "We've found match";
while($runrows = mysql_fetch_assoc($run)){
$title = $runrows ['title'];
$body = mysql_real_escape_string($runrows ['blog']);
?>
<div>
<?php
echo $title."<br/>";
echo $body;
?></div>
<?php
}
}
}
}
}
?>


Here is my db-controller and i saved it in a different folder _inc/dbcontroller.php

<?php
class DBController {
//include('Define.php');
private $host = "localhost";
private $user = "root";
private $password = "12345";
private $database = "ServerDBsclab";

function __construct() {
$db_conn = $this->connectDB();
if(!empty($db_conn)) {
$this->selectDB($db_conn);
}
}

function connectDB() {
$db_conn = mysql_connect($this->host,$this->user,$this->password);
return $db_conn;
}

function selectDB($db_conn) {
mysql_select_db($this->database,$db_conn);
}

function runQuery($query) {
$result = mysql_query($query);
while($row=mysql_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}

function numRows($query) {
$result = mysql_query($query);
$rowcount = mysql_num_rows($result);
return $rowcount;
}

function updateQuery($query) {
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
} else {
return $result;
}
}

function insertQuery($query) {
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
} else {
return $result;
}
}

function deleteQuery($query) {
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
} else {
return $result;
}
}

}
$db_conn = null;

?>


Here is my php pdo that i tried to use but is not working please help me with this so it will work like the above code

<?php
if(isset($_GET['postid'])){
echo '<h5 style="color: #2f2f2f;">Search</h5><br/>';
$matchpost = $blog_title;
$button = mysql_real_escape_string($_GET['postid']);
$q = $blog_title;
$search_output = "";
// Prepare statement
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$search = $db_conn->prepare("SELECT * FROM `blogtd` WHERE `blog` LIKE ?");
$search->execute(array("%$q%"));

foreach($search as $s){
$id = $s["BID"];
$title = $s["blog"];
$body = substr($s["body"], 0, 50);
$search_output .= '<article>
<header><a href="'.$id.'">
<h5>'.$title.'</h5>
</a></header>
<p>'.$body.'...</p></article>';
}
echo $search_output;

}
?>

Answer

Its wat everyone is saying. Keep everything by 1 extension. If u use PDO, do everything in PDO. If u use mysqli. Do everything in mysqli. Never use mysql. (we live in 2016 now).

I'm only looking at your PDO code. It seems your missing some code how do you want to get your mysql data. Your don't fetch anything. I created a similar script for you that works a little different. Including my PDO class. Test it in your own server and check it that is working.

<?php
class dbo{

    private $conn;
    public $error;

    private $stmt;

    public function __construct(){
        $driver = 'mysql';
        $host = 'localhost';
        $port = 3306;
        $user = 'user';
        $pass = 'pass';
        $db = 'mydb';
        $dsn = $driver.':host='.$host.';port='.$port.';dbname='.$db;
        // Set options
        $options = array(
            PDO::ATTR_PERSISTENT    => true,
            PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
        );
        try{
            $this->conn = new PDO($dsn, $user, $pass, $options);
        }
        catch(PDOException $e){
            $this->error = $e->getMessage();
        }
    }


    public function error(){
        return $this->stmt->errorInfo();
    }

    public function errorInfo(){
        return $this->stmt->errorInfo();
    }

    public function prepare($query){
        $this->stmt = $this->conn->prepare($query);
    }

    public function bind($param, $value, $type = null){
        if(is_null($type)){
            switch(true){
                case is_int($value): $type = PDO::PARAM_INT; break;
                case is_bool($value): $type = PDO::PARAM_BOOL; break;
                case is_null($value): $type = PDO::PARAM_NULL; break;
                default: $type = PDO::PARAM_STR;
            }
        }
        $this->stmt->bindValue($param, $value, $type);
    }

    public function execute(){
        return $this->stmt->execute();
    }

    public function rowCount(){
        return $this->stmt->rowCount();
    }

    public function getOne(){
        return $this->stmt->fetch(PDO::FETCH_OBJ);
    }

    public function getAll(){
        return $this->stmt->fetchAll(PDO::FETCH_OBJ);
    }

    public function getAllObject(){
        $result = new stdClass;
        $count = 0;
        while($row = $this->stmt->fetchObject()){
            $count++;
            $result->$count = $row;
        }
        return $result;
    }

    public function getLastInsertId(){
        return $this->conn->lastInsertId();
    }

    public function free(){
        $this->stmt = null;
    }
}

$search = filter_input(INPUT_GET, 'q');
$output;

if(!empty($search)){
    $db = new dbo();
    $db->prepare('SELECT * FROM blogtd WHERE blog LIKE :search');
    $db->bind(':search', '%'.$search.'%');
    $db->execute();
    $output = $db->getAll(); // This is the thing i'm missing in your script.
    $db->free();
}

if(!is_null($output)):
    $html = '';
    foreach($output as $i => $row){
        $id = $row->BID;
        $title = $row->blog;
        $body = substr($row->body, 0, 50);
        $html .= '
            <article>
                <header>
                    <a href="'.$id.'"><h5>'.$title.'</h5></a>
                </header>
                <p>'.$body.'</p>
            </article>';
    }
    echo $html;
else: ?>
<form id='searchform' method="GET" target="#">
    <input type='text' name='q' value=''/>
    <input type='submit' value='search'/>
</form><?php
endif;