简体   繁体   中英

Query not returning results in PHP for blank variable

A SELECT statement does not return values when run from PHP when the parameter is left blank. The same statement if run from the MYSQL query window works just fine for the above condition.

This is the SELECT statement in MYSQL

SELECT * FROM table1 WHERE field1=IFNULL(:var1,field1);

This is the code in PHP.

if(isset($_GET['var1'])){
$var1=mysqli_real_escape_string($conn,$_GET['var1']);
}
$sql = "SELECT * FROM table1 WHERE 
         field1= IFNULL('$var1',field1)";
$query = mysqli_query($conn, $sql);     

When the variable var1 is left blank the query should fetch all the records. If there is a value put in for var1 then only that record is to be displayed. This works fine. The problem is when the variable var1 is left blank. No records are displayed.

Please note running the SELECT statement in MYSQL query window for both the scenarios works perfectly.

Just an update: I tried putting a default value ('ALL') for the field(var1) in my HTML form which calls the PHP code. I then changed the SELECT statement in the PHP code as below:

$sql = "SELECT * FROM table1  WHERE 
         field1= COALESCE('$var1','ALL',field1)";

Even this does not work. Guys there has to be some way to do this.

You can use the WHERE clause only if the variable is not null :

$sql = "SELECT * FROM table1" ;
if(isset($_GET['var1'])){
    $var1=mysqli_real_escape_string($conn,$_GET['var1']);
    $sql .= " WHERE field1 = '$var1'" ;
}

$query = mysqli_query($conn, $sql); 

This is how it should be done. Use if statement and have 2 separate queries for the 2 scenarios.

if (isset($_GET['var1'])) {
    $stmt = $conn->prepare('SELECT * from table1 WHERE field1=?');
    $stmt->bind_param('s', $_GET['var1']);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query('SELECT * FROM table1');
}

Pay attention to how I used query() . You can only use that method if you do not have variables to be put inside of SQL. If you have some variable data you need to use placeholders and then bind it using bind_param() .

// New Connection
$db = new mysqli('localhost','user','pass','database');
// Check for errors
if(mysqli_connect_errno()){
  echo mysqli_connect_error();
}
$sql = "SELECT * FROM table1" ;
if(isset($_GET['var1'])){
  $var1=mysqli_real_escape_string($conn,$_GET['var1']);
  $sql .= " WHERE field1 = '$var1'" ;
}
$result = $db->query($sql);
if($result){
  while ($row = $result->fetch_object()){
    $rlt_arr[] = $row;
  }
  $result->close();
  $db->next_result();
}

try to add nullif

select
    *
from
    table1
where
    field1 = ifnull(nullif('$var1', ''), field1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM