demosthenes.info

A blog by Dudley Storey on , , , , , , and anything else that strikes his fancy.

featured articles

popular favourites

Write a Customisable MySQL Query

The easiest way to alter a query based on user choices is to place that choice in the form a URL variable, otherwise known as a $_GET variable. For example, let’s say we wanted to give our site visitor the choice of seeing the details for products we have listed in a database table called bikes:

Example simple MySQL database table
idnonameframe_colorframe_comppic
1Snow Bikeredaluminumred_snow.jpg
2Road Bike blacktitaniumblack_ti.jpg
3Mountain Bikebluealuminummountain.jpg

If we wanted just the snow bike row as a result, our MySQL query would be:

  1. SELECT * FROM bike WHERE idno = 1;

But we want to make it such that the id value that we use is a variable. Keeping things simple, we’ll hard-code the links for the user into the PHP page:

  1. <ul id=productlist">
  2. <li><a href="?id=1">Snow Bike</a></li>
  3. <li><a href="?id=2">Road Bike</a></li>
  4. <li><a href="?id=3">Mountain Bike</a></li>
  5. </ul>

We don’t need a page name before the question mark delimiting our GET variable as we’ll be looping back on the same page. At the top of our page, we want to connect to our database. We’ll use the same lines of PHP code we did previously:

  1. <? $myDatabase = mysql_connect("mysql_server", "user", "password")
  2. or trigger_error(mysql_error(),E_USER_ERROR);
  3. mysql_select_db("database", $myDatabase); ?>

The change happens in the very next few lines:

  1. <? if (isset($_GET['id’]))
  2. { $id = mysql_real_escape_string($_GET['id’]); }
  3. else { $id = 1; } ?>

We’re using mysql_real_escape_string to ensure that what we get from the URL is just a number, and not anything that will corrupt our database when we use it in a query. Anytime you are building a query based on user input, it is vital to check and double-check the variables you are using for security. (If we were using a later version of PHP we might use FILTER_SANITIZE_NUMBER_INT instead.) If $_GET['id'] isn’t set – i.e. the user has come to the page for the very first time – $id is set to 1.

Now that we have a number, we can create our query:

  1. <? $query = "SELECT * FROM bikes WHERE idno = $id LIMIT 1";
  2. $mydata = mysql_query($query, $myDatabase) or die(mysql_error());
  3. $myrows = mysql_fetch_assoc($mydata); ?>

Assured that we are getting only one row returned from the database, we can echo it on our page. First, we’ll check that we have any response, then provide output:

  1. <? if ($myrows) { ?>
  2. <h1><?=$myrows['name’]?></h1>
  3. <img src="assets/images/<?=$myrows['pic’]?>" alt="<?=$myrows['name’]?>"
  4. title="<?=$myrows['alt’]?>" />
  5. <p>Material: <?=$myrows['frame_comp’]?></p>
  6. <p>Color: <?=$myrows['frame_color’]?></p>
  7. <? } else { ?>
  8. <h1>No product found</h1>
  9. <? } ?>

With the amount of in that i would almost have just echoed out the entire HTML statement. =P

posted by Ian Carson

oh no... it formatted my text again! (had opening and closing PHP tags)

posted by Ian Carson

Dudley StoreyYep, I'm afraid so, Ian... automatically escaping code in comments will have to wait for the next version of the blog, I'm afraid (coming Jan 2012, with luck). But I believe I understand what you are saying: use PHP to echo out all the HTML in the IF statement, rather than using a fragmentary approach.

posted by Dudley Storey

Yep that was my thought, and yea I keep forgetting about escaping what I type.

posted by Ian Carson

web developer guide

featured comment

by JoelB in Goodbye, JQuery Validation: HTML5 Form Errors With CSS3

what i'm reading

A Storm of Swords: A Song of Ice and Fire: Book Three
A Storm of Swords: A Song of Ice and Fire: Book Three

what i'm watching

Californication: The Third Season
Californication: The Third Season

what i'm playing

Mass Effect 3 Collector's Edition
Mass Effect 3 Collector's Edition

what i'm hearing

Dub FX
Dub FX

blogs

podcasts

no ads ever

This blog is free of advertising, and always will be.

creative commons licensed

The content of this blog is free to use in whatever way you wish under the Creative Commons license.