I have a query form where I need to fetch details from a custom table in MYSQL. If the parameter is left blank all records should be fetched. If there is a value entered in the parameter then records for that value should be fetched.
This is my code so far:
<?php
$host = 'localhost';
$dbname = 'test';
$username = 'test';
$password = 'xxx';
session_start();
global $wpdb, $current_user;
$conn = mysqli_connect($host, $username, $password, $dbname);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$param_1=mysqli_real_escape_string($conn,$_GET['param_1']);
if (!empty($param_1)){
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx
WHERE column1='$param_1'";
} else {
$sql = 'SELECT column1 ,column2,column3,column4,column5
FROM xxx';
}
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
This works fine with one parameter. I will need to add more parameters and those could also be null.
For e.g.
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx
WHERE column1='$param_1' AND column2='$param_2";
Either of these could be null. How do I take care of this in MYSQL?
My question is what would be the best way to take care of this situation?
Thanks in advance.