Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Searching from type and name

Tags:

php

mysql

I'm sorry for the bad title, but I don't know a better alternative.

Currently I'm creating a search engine to get product detail. I have 2 search types, 1st I'm searching by using product type, and another one is by using product name.

Here is the search code:

<?php
$search_exploded = explode (" ", $search);

$x = "";
$construct = "";  

foreach ($search_exploded as $search_each) {
    $x++;
    if ($x==1)
        $construct .="product_type LIKE '%$search_each%'";
    else
        $construct .="AND product_type LIKE '%$search_each%'";
}
?>

and this is the data fetch code.

$results = $mysqli->query("SELECT * FROM produk2 WHERE $construct" );
if ($results) {

    //fetch results set as object and output HTML
    while ($obj = $results->fetch_object()) {
        echo '<div class="product">'; 
        echo '<form method="post" action="cart_update.php">';
        echo '<div class="product-thumb"><img src="images/'.$obj-  >product_img_name.'"></div>';
        echo '<div class="product-content"><h3>'.$obj->product_name.'</h3>';
        echo '<div class="product-desc">'.$obj->product_desc.'</div>';
        echo '<div class="product-info">';
        echo 'Price '.$currency.$obj->price.' | ';
        echo 'Qty <input type="text" name="product_qty" value="1" size="3" />';
        echo '<button class="add_to_cart">Add To Cart</button>';
        echo '</div></div>';
        echo '<input type="hidden" name="product_code" value="'.$obj->product_code.'" />';
        echo '<input type="hidden" name="type" value="add" />';
        echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
        echo '</form>';
        echo '</div>';
    }

How can I change the data search from product_type to product_name and vice versa, based on what I'm getting from user input?

I can't really explain it better, because of my poor English.

like image 738
Mohd Fadli Avatar asked Jul 12 '26 15:07

Mohd Fadli


1 Answers

You can make it a OR condition rather like below. That way, whatever uset types will be applied against both column and since it's a OR condition, it will return true if either matches.

where product_type LIKE '%$search_each%'
or product_name LIKE '%$search_each%';

Modify your below code segment

if ($x==1)
    $construct .="product_type LIKE '%$search_each%'";
else
    $construct .="AND product_type LIKE '%$search_each%'";

To be

$construct .="product_type LIKE '%$search_each%' OR product_name LIKE '%$search_each%'";
like image 146
Rahul Avatar answered Jul 15 '26 05:07

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!