0

I have the following code and I need to know if this is an unsafe code and if so, how can I make it safe.

I know that I can convert it to Prepared statements but I need to know (for my own knowledge) if it is possible to make this code safe without using prepared statements?

This is the code:

$sql="SELECT `id`, `title`, `slug`, `comment`, `date_added` FROM `blogs` WHERE slug='$title'";
$query = mysqli_query($db_conx, $sql);
$existCount = mysqli_num_rows($query);
if ($existCount!=0) {
    while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){

$id = $row["id"];   


}
}

Any advice would be appreciated.

Thanks in advance.

David Hope
  • 1,426
  • 4
  • 21
  • 50
  • 3
    It's possible, just very difficult to do in a general fashion. Just go with prepared statements. – Barmar Nov 13 '17 at 16:29
  • You can sanitize the `$title` variable. But you really want use parameter instead. – Juan Carlos Oropeza Nov 13 '17 at 16:29
  • 2
    No, the only way to be __sure__ that it's safe is to separate query building from parameter values. Which is precisely what prepared statements are for. – Sergio Tulentsev Nov 13 '17 at 16:29
  • 1
    Since slugs only contain alphanumeric and hyphen characters, you could use `preg_replace()` to remove any other characters from `$title`. – Barmar Nov 13 '17 at 16:32
  • Note: The object-oriented interface to `mysqli` is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface. Before you get too invested in the procedural style it’s worth switching over. Example: `$db = new mysqli(…)` and `$db->prepare("…")` The procedural interface is an artifact from the PHP 4 era when `mysqli` API was introduced and should not be used in new code. – tadman Nov 13 '17 at 18:04
  • 1
    @JuanCarlosOropeza "Sanitizing" is not to be confused with proper escaping. Normally "sanitizing" refers to cleaning up *unwanted* characters, not those that would cause SQL injection problems. Same goes in an HTML or JavaScript context where sometimes it requires some tricky handling to ensure that nothing can break through and be interpreted the wrong way. You usually "sanitize" things like email addresses to remove unwanted leading and trailing spaces, or to lower-case the domain if applicable. You escape it when it goes in SQL, HTML or JavaScript. – tadman Nov 13 '17 at 18:07
  • The problem with escaping is that escaping is designed to make **strings safe for SQL execution**. They cannot **prevent your SQL engine from confusing them for instructions**. That's why prepared statements are considered safe – Machavity Nov 13 '17 at 18:10

0 Answers0