开发者

Basic SQL Select Statement Formatting in PHP

I have a searchable database of the House and Senate and I just want to make a simple web page that can search this database. The only problem is, while I'm comfortable writing SQL select statements, how do I properly format them for use in PHP?

For example, here's my radio button to select Senators by state:

$sql = "";
if ($_POST['pkChamber'] == "Senate") {
    if ($_POST['pkParty'] == "Y") {
        $sql = SELECT * FROM senateinfo
               WHERE state =  (V开发者_运维知识库ariable = "stname")
               ORDER BY last_name, first_name');
    }
    else
    {
        $sql = SELECT * FROM senateinfo
               WHERE state =  (Variable = "stname")
               ORDER BY last_name, first_name
    }
}


I am not sure what you're asking for, But I have a good example of reliable and safe way for building WHERE statement dynamically:

$w     = array();
$where = '';

if (!empty($_GET['rooms']))     $w[]="rooms='".mysql_real_escape_string($_GET['rooms'])."'";
if (!empty($_GET['space']))     $w[]="space='".mysql_real_escape_string($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mysql_real_escape_string($_GET['max_price'])."'";

if (count($w)) $where = "WHERE ".implode(' AND ',$w);
$query = "select * from table $where";

Hope this helps.


Your query seems fine. I think you just need to understand some of the finer points of string parsing in PHP.

When you use double quotations (") to enclose a string, PHP actually will try to parse it looking for variables and/or other php code to process first. Something like this:

$sql = "SELECT * FROM table WHERE state = '{$state}' AND user = {$user->id}";

PHP will substitute out $state for whatever is defined in that variable and the same for the id of whatever user is instantiated in that class. (Also, you don't have to wrap your simple variables in {}. It does help with readability but is only required for class methods/variables.)

If you use single quotes (') to enclose a string, PHP simply treats it like normal. For your above query, I would suggest enclosing it in single quotes like this:

$sql = 'SELECT * FROM senateinfo WHERE state =  (Variable = "stname") ORDER BY last_name, first_name)';

If you want to use variables later on in this query, then you will need to escape the double quotations that are in there like this:

$sql = "SELECT * FROM senateinfo WHERE state =  (Variable = \"stname\") ORDER BY last_name, first_name)";

This way, PHP doesn't error out thinking you were trying to concatenate strings incorrectly when all you were doing was pasting a query.


You need to focus on one issue at a time.

Try to avoid writing SQL in PHP until you've a clear handle on strings in PHP, and how to inject variables into those strings. So:

Read up on string quoting in PHP (double quotes vs. Single quotes, and yes, HEREDOC)

Read up on variables in strings in PHP (note that if it doesn't have a $ dollar sign, it's a CONSTANT, not a string variable. Start off right with $strings and $variables where they're supposed to be used, not CONSTANTs, which only fall back to turn into strings if nothing else is available.)

Read up on binding SQL in PHP. Anything else will lead you down the path of SQL injection. If there are only naked strings used in your PHP SQL, then you are setting yourself up for failure when you finally deploy your web scripts to the harsh and unforgiving Internet. It's full of sharks ready to take advantage of SQL injection prone scripts.

Here is an example of code I use daily to bind SQL, centered around a custom function that makes it easy:

query("select * where someTable where someTable_id = :bound_id", array(':bound_id'=>13)); 

I can get you a function for creating bound SQL simply like that later (when I'm actually at a computer instead of mobile) if you're interested.


I use HEREDOCs for writing out non-trivial queries:

$sql = <<<EOL
SELECT blah, blah, blah
FROM table
WHERE (somefield = {$escaped_value}) ...
ORDER BY ...
HAVING ...
EOL;

Heredocs function as if you'd done a regular double-quoted string, but with the bonus of not having escape internal quotes. Variable interpolation works as expected, and you can do indentation on the text as well, so your query looks nicely formatted


I always do mine like this to keep it looking nice.

$sql = "SELECT * FROM senateinfo " .
       "WHERE state =  (Variable = "stname") " .
       "ORDER BY last_name, first_name')";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜