0

I have a page, project.php. I am attempting to implement slugs. So lets say I have a database entry called A Project, and the slug is a-project. Here's the PHP code

$slug = $_GET['name'];
try {
    $sql = "SELECT id FROM projects WHERE slug = '" . $slug . "' AND display = 1";
    $s = $pdo->prepare($sql);
    $s->execute();
} catch(PDOException $e) {
    die("Failed to run query: " . $e->getMessage());
}

This works. But when I decide to add in a rewrite rule in .htaccess like so:

RewriteRule ^projects/([0-9a-zA-Z]+) project.php?name=$1 [NC,L]

This is the result:

Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

Echoing out the query returns SELECT id FROM projects WHERE slug = 'a' AND display = 1 which when run in phpMyAdmin works fine, as you'd expect as it runs fine without the rewrite rule.

Using var_dump($_GET); returns array(1) { ["name"]=> string(1) "a" }

This only happens on multi word slugs, if the project's slug is simply project it works

Why is my rewrite rule breaking off the slug after the first word and corrupting my query, and how can I fix it?

cameronjonesweb
  • 2,435
  • 3
  • 25
  • 37
  • Please use prepared statments as you already use pdo. You are at risk of [**`mysql injection`**](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Fabio Aug 31 '14 at 12:45

1 Answers1

0

([0-9a-zA-Z]+) matches all characters that are between 0 and 9, a and z and A and Z. You will notice that the - character is not between them. Since the path segment that is being used for the slug is most likely not going to be used for anything else, consider matching it with ([^/]+) instead. This will match it up until the next /.

RewriteRule ^projects/([^/]+) project.php?name=$1 [NC,L]

As mentioned by Fabio: Please use prepared statements. Your current code is open to sql injection. If you learn how to properly use prepared statements, you never ever have to worry again about external input causing sql injections.

Sumurai8
  • 20,333
  • 11
  • 66
  • 100