Jump to content

Code not entering if statement


Recommended Posts

$name value is coming through from form submission.



If statement is not working properly. Whether $name is empty or not, it adds the where clause.


    $sql = "SELECT * FROM dirCsv_500" ?>
 <?php if (!empty($name)) {
    " where name like '%".$name."%'";
} ?>;

Link to comment
Share on other sites

I'm not surprised you can't see what's going on wrong, with all the chopping and changing back and forth between HTML and PHP. 

Keep it Simple: 

. . . 
  $sql = 'SELECT * FROM dirCsv_500';  	/* Added a missing ";" here */ 
  if (!empty($name)) {
    $sql .= " where name like '%".$name."%'"; 	/* Added string concatenation */ 
?> 	/* Removed an extraneous ";" here that's actually in the HTML, not the PHP */ 

I think I can see what you're trying to do,  but that's just not how you write PHP.  
You can "duck in and out" to embed bits of HTML in between the PHP code,  but you can't embed bits of PHP code in between the PHP code! 

There's other things to worry about here as well. 

From a database perspective, your code will perform poorly on a large table, given the leading wildcard in your search criteria, e.g. '%fred%'. 
The database is unable to use an index for this and will scan the table serially (i.e. slowly). 

Even before that, though, you have an even bigger problem - you are wide open to a SQL Injection Attack. 
Obligatory XKCD Reference - Little Bobby Tables

Look at using Prepared Statements for your SQL to [partly] protect yourself against this. 

   Phill  W.


Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.