If you like DNray Forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...

 

Website Search

Started by fordhenries, Oct 18, 2022, 02:51 AM

Previous topic - Next topic

fordhenriesTopic starter

Greetings everyone! Sorry for not being active on here lately.

Our website now has a simple search form. I started by learning how to write queries and am now focusing on making sure my work is safe.

Here's the code I'm currently using:

<?php
require_once '.config.php';
mysqli_set_charset($db"utf8");
$query=$_POST['query'];
$sql "SELECT * FROM product WHERE content = ?";
if (!empty(
$query) && trim($query) !=''){
    
$stmt mysqli_prepare($db$sql);
    
mysqli_stmt_bind_param($stmt's'$query);
 
    
$result mysqli_stmt_get_result($stmt);

    
// read data
    
while ($row mysqli_fetch_assoc($result)) {
        
// associative array with the next entry from the result
        
var_dump($row);
    }
    
    if (
mb_strlen($query) < 12) {
        echo 
'<p>The search term is too short.</p>';
    } else if (
mb_strlen($query) > 12) {
        echo 
'<p>The search term is too long.</p>';
    }

    if(
mysqli_num_rows($result) > 0){
        foreach(
$result as $row){
            
$str=$row['info'];/*create a variable to display results*/
            
$stra=$row['content'];/*create a variable to display results*/
            
$strm=$row['date_created'];/*create a variable to display results*/
                
            
echo "<p>Your ID: " htmlentities($straENT_QUOTES'UTF-8') . "</p>";
            echo 
"<p>Product: " htmlentities($strENT_QUOTES'UTF-8') . "</p>";
            echo 
"<p>Production date: " htmlentities($strmENT_QUOTES'UTF-8') . "</p>";
        }
    } else{
        echo 
"<p>No results were found for your search.</p> <p><b>Please try again by clicking the button below.</b></p>";
    }
    
    
mysqli_free_result($result);
} else{
    echo 
"<p>An empty search term has been set.</p> <p><b>Try again by clicking the button below.</b></p>";
}
mysqli_close($db);
?>

One of our users reported that when they make a request, they see the message "Nothing was found for your request" even though there are results that should be displayed. Can anyone advise me on what I might be doing wrong? Thank you in advance for any help!
  •  


expointer

It seems like you haven't fully mastered the Post-Redirect-Get method, despite my detailed explanation of it in relation to error handling. The same approach can be used for outputting search results, which involves a POST request to /search and a query parameter of "search-code", followed by a redirect to the GET request at /search/search-code.

Although this method requires an extra database query and HTTP request, it provides a generic solution that works well for different types of search queries that may involve various encoding or substitution of keys.

Alternatively, if you don't want to use a generic approach, you can simply make a GET request to /search?query=search-code.

Regarding security, it's important to handle errors properly when using mysqli functions, including prepare, bind_param, execute, and get_result. Even the set_charset function can return errors.

It's also worth noting that many developers create separate functions for SELECT and INSERT/UPDATE requests and use exceptions to handle errors rather than relying on return values.
  •  

matrice

It seems like the problem might be with the condition for displaying the "No results were found" message.

In your code, you have the condition `if(mysqli_num_rows($result) > 0)`. This condition checks if there are more than 0 rows in the result set. However, earlier in your code, you have already fetched and displayed the rows using a while loop.

To fix the issue, you can remove the `if(mysqli_num_rows($result) > 0)` condition and directly check if any rows were fetched in the while loop. Here's an updated version of your code:

```php
// ...

$result = mysqli_stmt_get_result($stmt);

// read data
if(mysqli_num_rows($result) > 0){
    while ($row = mysqli_fetch_assoc($result)) {
        $str = $row['info'];
        $stra = $row['content'];
        $strm = $row['date_created'];
           
        echo "<p>Your ID: " . htmlentities($stra, ENT_QUOTES, 'UTF-8') . "</p>";
        echo "<p>Product: " . htmlentities($str, ENT_QUOTES, 'UTF-8') . "</p>";
        echo "<p>Production date: " . htmlentities($strm, ENT_QUOTES, 'UTF-8') . "</p>";
    }
} else {
    echo "<p>No results were found for your search.</p> <p><b>Please try again by clicking the button below.</b></p>";
}

// ...
```

By making this change, the "No results were found" message will only be displayed if no rows were fetched during the while loop.

suggestions to improve the safety and functionality of your code:

1. Use prepared statements: Prepared statements help prevent SQL injection attacks by separating data from the query. Instead of directly including the value of `$query` in the SQL statement, you can bind it as a parameter using a prepared statement. You've already done this correctly in your code with `mysqli_stmt_bind_param()`.

2. Sanitize user input: While using prepared statements helps protect against SQL injection, it's also a good practice to sanitize user input before using it in any context. You can use functions like `mysqli_real_escape_string` or `htmlspecialchars` to sanitize user input.

3. Limit the length of the search term: You're already checking the length of the search term, but the condition seems incorrect. Currently, you're checking if the length of the query is less than 12, and then if it's greater than 12. You could instead check if the length is less than or equal to 12, and display a message accordingly.

4. Properly handle database errors: It's a good idea to include error handling in your code to catch and display any database errors that may occur. You can use `mysqli_error()` to retrieve the error message and handle it appropriately.

5. Implement pagination: If you expect a large number of results from the search query, consider implementing pagination to display the results in smaller chunks. This can improve performance and provide a better user experience.
  •  


If you like DNray forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...