dimanche 3 décembre 2017

MySql: Response does not return second query´s result when first query false

I made a search based on productName, so whenever the user search for e.g for product A, it shows product A, but if it searches for a product I don´t have in my database then it should still display all the products.

My first query works fine, but my second query doesn´t display any products, when I console the response on the client I get an empty array. Where is the issue?

Here is my search API:

<?php

try {

            // connect to the database
            require 'connect.php';
            // data from the BROWSER
            $sSearch = $_GET['search'];
            // TURN it into UPPERCASE
            strtoupper( $sSearch );
            // create a query: select products where search value equals productName
            $query1 = $conn->prepare("SELECT * FROM products WHERE productName=:productName");
            $query1->bindParam( ':productName' , $sSearch );
            $bResult1 = $query1->execute();
            $ajResult1 = $query1->fetchAll(PDO::FETCH_ASSOC);                                                                                                                                                                                                      
            $sajResult1 = json_encode( $ajResult1 );
            // create another query: select all products if search does not match any productName
            $query2 = $conn->prepare("SELECT * FROM products");
            $query2->execute();
            $ajResult2 = $query2->fetchAll(PDO::FETCH_ASSOC);                                                                                                                                                                                                      
            $sajResult2 = json_encode( $ajResult2 );
            $sjResponse = $bResult1 ? $sajResult1 : $sajResult2; 
            echo $sjResponse; 

    } catch (Exception $e) {

        echo "ERROR";

    }

?>

Aucun commentaire:

Enregistrer un commentaire