Home » Php » Search into MySQL PDO PHP

Search into MySQL PDO PHP

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have JSON ‘https://jsonplaceholder.typicode.com/todos/‘ from where I take data and populate MySQL. Then I connect to MySQL and display data. I made a search box and button to serch inside my table and it works perfectly. The result I display it in table in mt php page. But i have one problem. This is how I insert JSON data into MySQL and here is the table where I display data from DB in to my php page:

     function getDati()
        {
            $url = 'https://jsonplaceholder.typicode.com/todos/';
            $cURL = curl_init();
            curl_setopt($cURL, CURLOPT_URL, $url);
            curl_setopt($cURL, CURLOPT_HTTPGET, true);
            curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

            curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Accept: application/json'
            ));

            $result = curl_exec($cURL);
            curl_close($cURL);
            $all_items = json_decode($result);
            return $all_items;
        }
    //DB CONECTION
    class Database
    {
        private $db_host;
        private $db_name;
        private $db_username;
        private $db_password;

        public function dbConnection()
        {
            $this->db_host = 'localhost';
            $this->db_name = 'items';
            $this->db_username = '*****';
            $this->db_password = '****';
            try {
                $conn = new PDO('mysql:host=' . $this->db_host . ';dbname=' . $this->db_name, $this->db_username, $this->db_password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conn;
            } catch (PDOException $e) {
                echo "Connection error " . $e->getMessage();
                exit;
            }
        }
    }
//connecto to DB to displayit into my php page
<?php
            $database = new Database;
            $db = $database->dbConnection();
            $stmt = $db->query("SELECT * FROM posts ");
            $stmt->execute();
            ?>
 <table class="table table-hover">
                    <hr>
                    <div style="text-align: center"> <label class="badge badge-light" style="font-size:30px; background-color: #2196F3;">All Items</label></div>
                    <hr>
                    <thead>
                        <tr>
                            <th>User ID</th>
                            <th>ID</th>
                            <th>Title</th>
                            <th>Compiled</th> 
                        </tr>
                    </thead>
                    <?php foreach ($stmt as $item) : ?>
                        <tr>
                            <td><?php echo $item['userId'] ?> </td>
                            <td><?php echo $item['id'] ?> </td>
                            <td><?php echo $item['title'] ?></td>
                            <td><?php echo $item['completed'] ? 'Compiled' : 'Not Compiled' ?></td> //completed is boolean so I used "? 'Compiled' : 'Not Compiled'" to not be displayed 0 or 1 
</tr>
                    <?php endforeach ?>
                </table>

And here is HTML code for search box and button:

<form method="post" class="form-inline my-2 my-lg-0 navbar navbar-expand-lg navbar-light bg-dark">
            <input name="search" class="form-control mr-sm-2" placeholder="Search" aria-label="Search">
            <button name="submit-search" class="btn  my-2 my-sm-0 bg-white" type="submit">Search</button>
        </form>

And code for function Search():

function search()
{
    $keyword = '%' . $_POST['search'] . '%';
    $database = new Database;
    $db = $database->dbConnection();
    $stmt = $db->query("SELECT * FROM posts WHERE id LIKE '$keyword' OR userId LIKE '$keyword' OR title LIKE '$keyword'  OR completed LIKE  '$keyword'");
    $stmt->execute();
 <div class="container" style=" margin-top:5%;">
        <table class=" table table-hover" id="search-table" style="font-size: 18px;">
            <hr>
            <div style="text-align:center;"> <label style="text-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1), 10px 10px 10px rgba(0, 0, 0, 0.2); font-size:30px;border-radius: 45px; "> Results from search : </label></div> <br>
            <tr>
                <th>User ID:</th>
                <th> ID: </th>
                <th> Title: </th>
                <th> Compiled: </th>
            </tr>

            <?php while ($row = $stmt->fetch()) : ?>
                <tr>
                    <td> <?php echo $row['userId'] ?> </td>
                    <td> <?php echo $row['id'] ?> </td>
                    <td> <?php echo $row['title'] ?> </td>
                    <td> <?php echo $row['completed'] ? 'Compiled' : 'Not Compiled' ?> </td>
                </tr>
            <?php endwhile ?>
        </table>
    </div>
<?php } ?>

The problem is that JSON file have one array with 200 objects and those 200 objects have properties like userId, id, title, completed. Completed is boolean type and inside MySQL it is saved like 0 or 1 (false / true). So obviously when I type Completed or Not completed in my search box it results nothing.

How can I display all Completed or Not completed items that are in my MySQL table when I type Completed or Not completed in the search box.

UPDATE:
My HTML search from 2 inputs :

<div class="container bg-light " style=" margin-top:8%; width:30%;" id="searcform">
    <form method="post">
        <div class="text-center">
            <label class="h3 font-weight-bold">SEARCH BY:</label>
        </div>
        <hr>
        <div class="form-group">
            <label for="formGroupExampleInput">User ID: </label>
            <input type="text" name="userId" class="form-control" id="formGroupExampleInput" required>
        </div>
        <div class="form-group ">
            <label for="formGroupExampleInput2">Title</label>
            <input type="text" name="title" class="form-control" id="formGroupExampleInput2" required>
        </div>
        <button type="submit" name="search-btn2" class="btn btn-primary">Search</button>
        <hr>
    </form>
</div>

And PHP search from 2 inputs :

if (isset($_POST['search-btn2'])) {

    $values = [];
    $conditions = [];
    $conditions[] = "1";  /* trivial condition that is True */

    $userId = $_POST['userId'];
    if ($userId != '') {
        $values[] = $userId;
        $conditions[] = "userId = ?";
    }
    $title = $_POST['title'];
    if ($title  != '') {
        $values[] = $title;
        $conditions[] = "title like concat('%', ?, '%')";
    }

    $database = new Database;
    $db = $database->dbConnection();
    $cond = join(' AND ', $conditions);
    $sql = "SELECT * FROM posts WHERE $cond";
    $stmt = $db->prepare($sql);
    $stmt->execute($values);
}
?>
How to&Answers:

I would recommend that your search box contain a separate input widget for each parameter the user can supply.

You should use a <select> HTML tag for specifying the completed search parameter as follows:

<select name="completed">
    <option value=''>-- Select a Completion Value --</option>
    <option value="0">Not Completed</option>
    <option value="1">Completed</option>
</select>

You could have a <select> tag for the id parameter:

<select name="id">
    <option value=''>-- Select an id value --</option>
    <option value="id-value-1">id-value-1</option>
    <option value="id-value-2">id-value-2</option>
    . . .
    <option value="id-value-N">id-value-N</option>
</select>

The above would have to be initialized in a loop. Or else you could have a simple text box where the user has to type in the id of the row of interest.

You should have text input fields userId and title:

User Id: <input type="text" name="userId">
Title: <input type="text" name="title">

Your PHP code then should be:

$values = [];
$conditions = [];
$conditions[] = "1";
$completed = $_POST['completed'];
if ($completed != '') {
    $values[] = $completed;
    $conditions[] = "completed = ?";
}
$id = $_POST['id'];
if ($id != '') {
    $values[] = $id;
    $conditions[] = "id = ?";
}
$userId = $_POST['userId'];
if ($userId != '') {
    $values[] = $userId;
    $conditions[] = "userId = ?";
}
$title = $_POST['title'];
if ($title  != '') {
    $values[] = $title;
    $conditions[] = "title like concat('%', ?, '%')";
}
$cond = join(' AND ', $conditions);
$db = $database->dbConnection();
$stmt = $db->prepare("SELECT * FROM posts WHERE $cond");
$stmt->execute($values);

Note that the above code used a prepared statement to prevent SQL Injection attacks. If you can ensure that there is always at least one input criteria specified such that the $conditions array is not empty, then the 1 condition can be removed from the SELECT statement.