質問

i'm working on adding filters to my database but i have no knowledge and google didnt really help so i appreciate all the advice =)

I would like to add filters like name and price and arrange by asc and desc order.

my db has 4 columns, id(int15) , brand/model(varchar50), picture(longblob), price (varchar50).

Any advice on how to approach this(best if have some examples as i'm a beginner)? Currently below i created the form asc and desc below but i have no idea on how to integrating to my php code. I've set the form name as "results"

What i currently have is index.php

<form action="search.php" type="text"  method="POST">
Name: <input type ="text" name="search_name" size='30' /> 
<input type="submit" value="Search">
<br><br>
<b>Arrange Price by :</b>

<select name="results">
<option value="">Select...</option>
<option value="asc">Ascending</option>
<option value="desc">Descending</option>
</select>

<?php

if (isset($_POST['search_name'])) {
        $search_name = $_POST['search_name'];

        if (!empty($search_name)){

            if (strlen($search_name)>=3) {

            $query = "SELECT * FROM `shoes` WHERE `brand/model` LIKE '".mysql_real_escape_string($search_name)."%' ORDER BY `price` ASC";
            $query_run = mysql_query($query);
            $query_num_rows = mysql_num_rows($query_run);

            if ($query_num_rows>=1) {
                echo $query_num_rows.' Results found:<br>';

                while ($query_row = mysql_fetch_array($query_run)) {


                        $picture = $query_row['picture'];
                        echo "</br>";
                        echo $query_row ['brand/model']; 
                        echo str_repeat('&nbsp;', 15); // adds 5 spaces
                        echo $query_row ['price'];
                        echo "</br>";
                        echo "</br>";
                        //header("content-type: image/jpeg");
                        echo "<img src='image.php?id=".$query_row['id']."' width='300' height='200' />";
                        echo "</br>";



                }
            } else {
                echo 'No Results Found.';
            }
        } else {
            echo 'Text field must be more than 3 characters.';
        }

    } else {
        echo 'Text Field Cannot be Empty!';
    }
}

?>

役に立ちましたか?

解決

Try using this code,

  • Changes what I have done are, created anchor's of your field name as table header
  • by default the headers are in ASC order, if we click it, it changes to DESC order
  • the sql query then uses the field name in GET to order the records
  • the search term is also then saved in the GET request so that we can persist it ahead
  • as search term is sometimes received in GET and sometimes in POST, have used REQUEST here, to get data

    if (!empty($search_name)){

        if (strlen($search_name)>=3) {

            if(empty($_REQUEST['searchTrm']))
                $_REQUEST['searchTrm'] = 'price';

            if(empty($_REQUEST['order']))
                $_REQUEST['order'] = 'ASC';

            $query = "SELECT * FROM `shoes` WHERE `brand/model` LIKE '".mysql_real_escape_string($search_name)."%' ORDER BY ".$_REQUEST['searchTrm']." ".$_REQUEST['order'];

            $query_run = mysql_query($query);
            $query_num_rows = mysql_num_rows($query_run);

        if ($query_num_rows>=1) {
            echo $query_num_rows.' Results found:<br>';
?>
        <table border=1>
            <tr>
                <td>
                    <?php
//use your sql field name as searchTrm value
if($_REQUEST['searchTrm'] == 'brand/model' && $_REQUEST['order'] == 'DESC') { ?>
                        <a href='?searchTrm=brand/model&order=ASC&search_name=<?php echo $_REQUEST['search_name']?>' title = 'ASC'>Brand Name</a>
                    <?php } else { ?>
                        <a href='?searchTrm=brand/model&order=DESC&search_name=<?php echo $_REQUEST['search_name']?>' title = 'DESC'>Brand Name</a>
                    <?php } ?>
                </td>
                <td>
                    <?php if($_REQUEST['searchTrm'] == 'price' && $_REQUEST['order'] == 'DESC') { ?>
                        <a href='?searchTrm=price&order=ASC&search_name=<?php echo $_REQUEST['search_name']?>' title = 'ASC'>Price</a>
                    <?php } else { ?>
                        <a href='?searchTrm=price&order=DESC&search_name=<?php echo $_REQUEST['search_name']?>' title = 'DESC'>Price</a>
                    <?php } ?>
                </td>
                <td>Image</td>
            </tr>
            <?php
            while ($query_row = mysql_fetch_array($query_run)) {
                 $picture = $query_row['picture'];
                ?>
                <tr>
                    <td><?php echo $query_row['brand/model'];?></td>
                    <td><?php echo $query_row['price'];?></td>
                    <td><img src='image.php?id=<?php echo $query_row['id'];?>' width='300' height='200' /></td>
                </tr>
                <?php
            }
        ?> </table> <?php
        } else {
            echo 'No Results Found.';
        }
    } else {
        echo 'Text field must be more than 3 characters.';
    }

} else {
    echo 'Text Field Cannot be Empty!';
}
}

他のヒント

Use of POST is fine, so long as you are sanitizing your input to prevent against SQL injections. To further protect yourself, you can use prepared statements. Also, I see you are using the mysql_* API. I highly recommend you switch to MySQLi or PDO instead. I'll place emphasis on MySQLi in this case since it looks as if you are using MySQL (although PDO will work for MySQL as well).

For the searching component:

Fields are best searched if they have been indexed. The database will use this behind the scenes to get at your data quicker. However, using the LIKE % <your search string> % with the wildcards (%) like you are will negate any index you have placed on a column. This is because using a wildcard on the left hand side of a search doesn't allow the MySQL to make use of the index. (Long story short, it simply can't figure out if text matches unless it scans the entire table.) What it sounds like you need is a FULLTEXT index which you can run queries using the MATCH...AGAINST syntax. You can use LIKE on an indexed column if you want, but drop the left hand wildcard, e.g.: SELECT * FROM ...... LIKE 'your search value'% .....

So from here I would suggest you look into the following concepts/topics:

  • Prepared statements in PHP using MySQLi (or PDO)
  • Column indexes (specifically FULLTEXT indexes for searching purposes)
  • Fulltext searching for MyISAM tables (MySQL < 5.6) or Fulltext searching for InnoDB (MySQL 5.6+)
  • Internal "scoring" for FULLTEXT and how to use it
  • Boolean and natural language searching.
  • Adding a search filter like you want is a nice feature, but it takes a little more than what you are trying to do. (And trust me, Google will provide you plenty of information and these subjects. It is a matter of practicing and getting use to using the newer features of MySQL.)

    • Use PDO or Mysqli prepared statement . • I'll use regex to filter the inputs (remove all non-words,numbers and some chars) .

    example: $string = preg_replace('~[^\w\s-_\.,]~','',$string);
    

    • I'll use full text search .

    ライセンス: CC-BY-SA帰属
    所属していません StackOverflow
    scroll top