Let’s say I’m creating a basic page, said page’s text varies depending on what’s passed into it through a GET variable.
There’s a header at the top of the page like so:
<?php
mysql_connect("stuff", "stuff", "stuff");
mysql_select_db("dbname");
mysql_query("SELECT * FROM table WHERE ID = '{$_GET['url']}'");
//Now we have connected to the SQL database.
?>
Assuming I continued coding there, so that the header text varied depending on what was passed into the URL (however, this is irrelevant, it’s the next part in which I want to question).
Now let’s say that, further down the page, there is some more PHP code, but there is also more HTML code in between. If I wanted to access the database again in this second PHP snippet, do I have to reconnect to the database? Or is there a way I can make sure that the connection session stays open, even when it’s a completely different <?php ?> area? How do i make it so that my SQL connection isn’t dropped when I end the <?php tag?
Let’s address several issues at once 🙂
The connection will not be dropped unless you explicitly do it yourself. It will be dropped when the script ends, of course. Even then, there are techniques of persistent connection and connection pooling that may help you avoid the overhead.
The
mysql_*family of functions is deprecated and may soon cease working altogether. You’d be much better off by moving to e.g. PDO functions, which are more powerful and safer too.When you put a
_GETparameter directly inside a SQL query (or other server code) without checking/validating, you expose yourself to the danger of that parameter containing some nasty surprise. The classic example, apart from XKCD, is if you check that$_GET['password']corresponds to fieldpassword. If you just code it asand someone places in that field the value
the SQL server will see
and since ” is indeed equal to ”, that query will return true — and the user will be logged in without knowing the password. Such "SQL injection", if possible at all, can often be tuned to the point of allowing an attacker to be recognized as the site’s administrator, with all that entails. And that’s why you don’t want to use client-side parameters "as is". PDO’s prepared statements can help there, too.