Home > Back-end >  How to add query parameters in PHP code database output
How to add query parameters in PHP code database output

Time:07-24

I have tasks.php file which shows all results of database.

I'm now looking to add query parameters in the URL that would result in "tasks.php/query=books" that would only show raw data showing data that contains "books" in columns Task_title or task_description from my SQL database.

Say if query="" then return all tasks and if query=somevalue then filter based on it.

I have tried creating a separate file for search query with success, but I need to include in this tasks.php for app dev and I'm not sure how to integrate.

Here is my tasks.php

<?php

 // Create connection
$con=mysqli_connect("test","test","test","test");
 
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
 
// Select all of our stocks from table 'stock_tracker'
$sql = "
SELECT * FROM `tasks` ORDER BY `tasks`.`date_added` DESC

";

$cValue=str_replace(array("'",",","."), array("&amp;#039;","&amp;#44;","&amp;#46;"), $_POST['contractValue']);
 
// Confirm there are results
if ($result = mysqli_query($con, $sql))
{
    // We have results, create an array to hold the results
    // and an array to hold the data
    $resultArray = array();
    $tempArray = array();
 
    // Loop through each result
    while($row = $result->fetch_object())
    {
        // Add each result into the results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }
 
    // Encode the array to JSON and output the results

echo json_encode($resultArray, DEFINED('JSON_INVALID_UTF8_IGNORE') ? JSON_INVALID_UTF8_IGNORE : 0);
    

}
 
// Close connections
mysqli_close($con);
?>

CodePudding user response:

Step 1.

In Url it should be - tasks.php?query=books instead of tasks.php/query=books

Step 2.

Get your query value form url

$search_key = $_GET['query'];

Step 3.

Change your select query.

SELECT * FROM `tasks` WHERE `Task_title` LIKE '%$search_key%' OR `task_description`  LIKE '%$search_key%' ORDER BY `tasks`.`date_added` DESC
  • Related