Php help needed for newbie

cyberock

Member
Apr 19, 2002
95
0
0
I was wondering if it is possible to put an if statement inside a mysql statement. I'd like to do a check for some defined variables inside my query. I was hoping to do something like this but this of course doesn't work...

query = "SELECT * ".
"FROM table ".
"where id = 1 "
if(isset($_GET[variable1])){
."and variable1 = $_GET[variable1] "}
if(isset($_GET[variable2])){
."and variable2 = $_GET[variable2] "};


Any suggestions how I could get something like this to work? Thanks!
 

igowerf

Diamond Member
Jun 27, 2000
7,697
1
76
How about:

$query = "SELECT * FROM table where id = 1";

if(isset($_GET[variable1])){
$query = $query." and variable1 =". $_GET[variable1];
}

if(isset($_GET[variable2])){
$query = $query." and variable2 =". $_GET[variable2];
}
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
$query = "SELECT * FROM table WHERE id=1";

if(isset($_GET["variable1"])) $query .= " AND variable1='{$_GET['variable1']}' ";
if(isset($_GET["variable2"])) $query .= " AND variable2='{$_GET['variable2']}' ";

A couple things:

if's are statements. You can't stick them inside of other statements or expressions like a string assignment. You can use the ternary operator like that, but it doesn't make much sense in this case.

You quote string array keys, because you quote strings everywhere. $foo["bar"]. The only time you wouldn't quote bar is when it's a constant that you defined with define(). Which is not the case in your example.

Generally when you put variables from an array inside of a string, you surround them with {}, to help the parser.

If these variables are text, then you need to quote them in the sql statements (like I did in my example).

You need to make sure that these variables have been checked properly, so people can't inject the code of their choice into your web app.

I think that's all..