Database report in PHP Just a small PHP exercise to write some simple reports, I thought I'd do it without a framework for fun and profit. I'm particularly concerned about the potential for SQL injection, since the user could pass their own values to $_GET['status'].

I also understand that mysql_connect() et. al are deprecated in PHP since 5.5, but I assume better equivalents work the same way.

&lt;?php

$server = "deleted";
$username = "deleted";
$password = "deleted";
$database = "deleted";

$conn = mysql_connect($server, $username, $password);

if (!$conn)
{
        die('Could not connect: ' . mysql_error());
}

mysql_select_db($database, $conn);

// Get the status from the last form submission, otherwise use default.
$choice = isset($_GET['status']) ? $_GET['status'] : '7';

// Get all the current statuses to populate the drop down list.
$options = mysql_query("SELECT name, id FROM issue_statuses", $conn);

// Get all the results for issues matching the chosen status id.
$result = mysql_query("SELECT id, subject FROM issues WHERE status_id = " . $choice, $conn);

// Get the name of the chosen status.
$chosen_status = mysql_query("SELECT name FROM issue_statuses WHERE id = " . $choice, $conn);
$status_name = mysql_fetch_array($chosen_status, MYSQL_ASSOC);

if (!$options || !$result || !$chosen_status)
{
        echo("&lt;p&gt;Error performing query: " . mysql_error() . "&lt;/p&gt;");
        exit();
}

mysql_close($conn);

?&gt;

&lt;!DOCTYPE html&gt;

&lt;html&gt;
&lt;head&gt;
        &lt;title&gt;RM Rep&lt;/title&gt;
        &lt;style&gt;
                body { font-family: Arial, sans-serif; }
                td { padding: 0px 5px; }
        &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
        &lt;form name="status_choice" action="index.php" method="get"&gt;
                &lt;select name="status"&gt;
                &lt;?php
                        // Load all the statuses into a select list.
                        while ($row = mysql_fetch_array($options, MYSQL_ASSOC))
                        {
                                echo('&lt;option value="' . $row['id'] . '"&gt;' . $row['name'] . '&lt;/option&gt;');
                        }
                ?&gt;
                &lt;/select&gt;
                &lt;input type="submit" value="Submit"&gt;
        &lt;/form&gt;

        &lt;h1&gt;&lt;?php echo($status_name['name']); ?&gt;&lt;/h1&gt;
        &lt;span&gt;&lt;?php echo(mysql_num_rows($result) . " results"); ?&gt;&lt;/span&gt;
        &lt;hr&gt;

        &lt;table&gt;

        &lt;?php
                // Print results.
                while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
                {
                        echo("&lt;tr&gt;");
                        echo("&lt;td&gt;" . $row['id'] . "&lt;/td&gt;");
                        echo("&lt;td&gt;" . $row['subject'] . "&lt;/td&gt;");
                        echo("&lt;/tr&gt;");
                }
        ?&gt;
        &lt;/table&gt;

&lt;/body&gt;
&lt;/html&gt;
I also understand that mysql_connect() et. al are deprecated in PHP since 5.5, but I assume better equivalents work the same way.


Sort of. MySQLi can work a lot like the the mysql extension, but personally I prefer PDO. Whereas MySQLi has both an OO and a procedural API, PDO has only an OO one.  PDO can interact with more than just MySQL though.

Due to differences in SQL dialects, it's rare for it to be possible to just change out the driver and have everything work. It is a lot closer to cross compatibility than a specific RDBMS's API.  Also, you can use your knowledge of the PDO API across multiple database systems.  Whether it's MySQL, sqlite, SQL Server, etc, the general API is the same.

Anyway, whether you choose MySQLi or PDO, you should definitely stop using ext/mysql.



As for SQL injection: your code is basically a poster child for it.

$choice = isset($_GET['status']) ? $_GET['status'] : '7';
$result = mysql_query("SELECT id, subject FROM issues WHERE status_id = " . $choice, $conn);


What if I go to page.php?status=0 OR 1=1?  The query becomes:

SELECT id, subject FROM issues WHERE status_id = 0 OR 1=1


This is a fairly benevolent example since all this will do is ignore the status filter. I've seen some very clever exploits though. Given enough time and determination, this small exploit could be ripped open into horrible, horrible things.

The easiest solution to SQL injection is to always stay aware that SQL is a language like any other (well, not on a technical level, but on a superficial level).

In particular, just remember to either escape content if it's being put into the query as a string, or cast it if it's being put in as something else.

For example:

$choice = isset($_GET['status']) ? (int) $_GET['status'] : 7;


$choice is now safe to put into an SQL statement.

This StackOverflow thread gives tons of options for properly handling SQL queries. 



if (!$options || !$result || !$chosen_status)
{
    echo("&lt;p&gt;Error performing query: " . mysql_error() . "&lt;/p&gt;");
    exit();
}


If more than one query fails, this will only output the error for the last one. Additionally, using exit for rendering errors is bad practice. In a file this simple, there's really not much of a better option without going way out of your way. What I tend to do in larger applications though is let uncaught exceptions (in other words, either the ones that I expect to never happen or the ones that are fatal) bubble up to the top at which point the request is transparently piped to an error controller (basically, I've copied the approach of most PHP MVC frameworks). If you wanted to use a similar approach, you could basically wrap exceptions over the MySQL API. That get's ugly fast though.

Oh, also, the mysql_error should be passed through htmlspecialchars.  I'll add more to this note in a minute.



I'm not sure if it's technically valid to close a MySQL connection and then read the result sets.  I suspect that this is not valid, and that if it works, it's just by luck.



Even when not going full-blown MVC, it can be very beneficial to separate logic or manipulation from the view.  In particular, all of the mysql calls in the HTML parts, I would put in the PHP parts.  If your view is only looping over an array, the source of the array can be changed without the view having to know about it.  (Side note: depending on how strictly we're using terminology, the HTML part is probably better not called a view.)



while ($row = mysql_fetch_array($options, MYSQL_ASSOC))


You might as well us mysql_fetch_assoc.



echo('&lt;option value="' . $row['id'] . '"&gt;' . $row['name'] . '&lt;/option&gt;');


Anything being put into HTML needs to be run through htmlspecialchars. This comes back to being aware of context. It's just the rules of HTML.  Certain things must be escaped in the same way that things in SQL or PHP must be escaped.

(I'm also not a fan of the echo() form of echo, but that's mostly opinion.)

echo '&lt;option value="' . htmlspecialchars($row['id']) . '"&gt;' . htmlspecialchars($row['name']) . '&lt;/option&gt;';


A lot of people will say that the htmlspecialchars on the id is pointless since it's going to be an int.  While that's true, that's only for now.  With a primary key column it's not likely to happen (in fact it probably shouldn't happen), but I've been in situations before where an int column has been changed to a varchar and we've had problems with the HTML escaping after that. Considering the overhead of htmlspecialchars is tiny, might as well call it on everything being put into HTML.



There's a few more comments and suggestions I have. I was originally going to add them as comments to the code, but I got a bit carried away and decided to rewrite it with PDO.

&lt;?php

$db = new PDO('mysql:host=localhost;dbname=somedatabase', 'username', 'password', array(
    PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION
));

//The error mode being exception means that exceptions will be thrown if a query fails 
//(or some other kind of error happens).  This tends to be more convenient since you don't
//have to explicitly check for unexpected errors -- either everything executes fine, or the script
//crashes and burns (which might not be desired behavior in a lot of cases).
//Anyway, there is one little catch.  PDOException instances will sometimes include with them
//the DSN (the 'mysql:host=...' string), the username, and the password. This means that you must be
//very careful about never letting an end user see a PDOException.  In particular, you can either have
//a just-in-case top level try {} catch {} that can catch any unexpected errors, log them, and render 
//them in a pretty page (what I like to do in any kind of sizable application), or at the very least,
//you can ensure that display_errors of Off on production servers (which it should be anyway). That way
//the exception will still be logged, but it won't be displayed.

//$options is a bad name. What kind of options?
$issueStatusesStmt = $db-&gt;query("SELECT name, id FROM issue_statuses");

//This is done in a weird way, but it has a reason.
//In particular, you can now check if a provided status id exists (isset($issueStatuses[$idToCheck])).
//And, you no longer need your name query since you can pull the name with $issueStatuses[$id]['name'].
$issueStatuses = array();
while ($is = $issueStatusesStmt-&gt;fetch(PDO::FETCH_ASSOC)) {
    $issueStatuses[$is['id']] = $is;
}

//This handles the isset check and validates that the provided value is an integer.
//If the value fails the integer check, $statusId will be false.  If no status param is
//provided in the URL, $statusId will be null. There is of course a lot more
//information about this at http://php.net/filter_input
$statusId = filter_input(INPUT_GET, 'status', FILTER_VALIDATE_INT);

 if (!isset($issueStatuses[$statusId]) {
    //This is what's called a magic constant. They tend to lead to problems.
    //In particular, what is this magical status 7? Someone not intimately familiar
    //with your DB data will have no idea.
    $statusId = 7;
}

//This prepares a statement with a placeholder for status_id.
$issuesStmt = $db-&gt;prepare("SELECT id, subject FROM issues WHERE status_id = :statusId");
$issuesStmt-&gt;execute(array('statusId' =&gt; $statusId));
/*
 * You could also do it like:
    $issuesStmt = $db-&gt;prepare("SELECT id, subject FROM issues WHERE status_id = ?");
    $issuesStmt-&gt;execute(array($statusId));
 * I prefer to stick with named fillers though.  It's significantly less confusing if you have 
 * to revisit a complicated query a month later.
*/

//You could make this an associative array like earlier, but really there's no reason to at this point.
$issues = $issuesStmt-&gt;fetchAll(PDO::FETCH_ASSOC);

//Note: if $statusId default to 7 and 7 somehow doesn't exist in the database,
//this will issue a notice and $statusName will be null.
$statusName = $issueStatuses[$statusId]['name'];

//PHP will only eat one new line.  The doctype is supposed to be the very top line (unless I've imagined that requirement).
//This means it need to be on the line directly after the closing tag.
?&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;RM Rep&lt;/title&gt;
        &lt;style&gt;
                body { font-family: Arial, sans-serif; }
                td { padding: 0px 5px; }
        &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;form name="status_choice" action="index.php" method="get"&gt;
            &lt;select name="status"&gt;
                &lt;?php foreach ($issueStatuses as $is) { ?&gt;
                &lt;option value="&lt;?php echo htmlspecialchars($is['id']); ?&gt;"&gt;&lt;?php echo htmlspecialchars($is['name']); ?&gt;&lt;/option&gt;
                &lt;?php } ?&gt;
            &lt;/select&gt;
            &lt;input type="submit" value="Submit"&gt;
        &lt;/form&gt;

        &lt;h1&gt;&lt;?php echo htmlspecialchars($statusName); ?&gt;&lt;/h1&gt;
        &lt;span&gt;&lt;?php echo count($issues) . ' results'; ?&gt;&lt;/span&gt;
        &lt;hr&gt;

        &lt;?php 
        /*
         If no entries are found, you will emit broken HTML in your current code.
         (At least I think an empty table is invalid HTML -- can't remember.)
         (Oh and also, I'm abusing PHP comments right now...)
        */
        ?&gt;

        &lt;?php if (!empty($issues)) { ?&gt;

        &lt;table&gt;
            &lt;?php foreach ($issues as $issue) { ?&gt;
            &lt;tr&gt;
                &lt;td&gt;&lt;?php echo htmlspecialchars($row['id']); ?&gt;&lt;/td&gt;
                &lt;td&gt;&lt;?php echo htmlspecialchars($row['subject']); ?&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;?php } ?&gt;
        &lt;/table&gt;

        &lt;?php } else { ?&gt;
        &lt;div&gt;
            No entries matched the given status.
        &lt;/div&gt;
        &lt;?php } ?&gt;

    &lt;/body&gt;
&lt;/html&gt;