Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this work to stop sql injections

I have been using the block of code below to supposedly stop sql injections. It is something someone showed me when I first started php(which was not that long ago)

I place it in every page just as shown on the open. I am wondering if it is effective? I do not know how to test for sql injections

<?php

//Start the session

session_start();


//=======================open connection

include ('lib/dbconfig.php');

//===============This stops SQL Injection in POST vars

  foreach ($_POST as $key => $value) {
    $_POST[$key] = mysql_real_escape_string($value);
  }

  foreach ($_GET as $key => $value) {
    $_GET[$key] = mysql_real_escape_string($value);
  }

My typical insert and update queries look like this

$insert = ("'$email','$pw','$company', '$co_description', '$categroy', '$url', '$street', '$suite', '$city', '$state', '$zip', '$phone', '$date', '$actkey'");

mysql_query("INSERT INTO provider (email, pw, company, co_description, category, url, street, suite, city, state, zip, phone, regdate, actkey) VALUES ($insert)") or die ('error ' . mysql_error());

mysql_query("UPDATE coupon SET head='$_POST[head]', fineprint='$_POST[fineprint]', exdate='$exdate', creationdate=NOW() WHERE id='$cid'") or die ('error ' . mysql_error());
like image 281
Daniel Hunter Avatar asked Apr 22 '26 03:04

Daniel Hunter


1 Answers

That's somewhat effective, but it's suboptimal -- not all of the data you receive in _GET and _POST will go into the database. Sometimes you might want to display it on the page instead, in which case mysql_real_escape_string can only hurt (instead, you'd want htmlentities).

My rule of thumb is to only escape something immediately before putting it into the context in which it needs to be escaped.

In this context, you'd be better of just using parameterized queries -- then escaping is done for you automatically.

like image 61
Frank Farmer Avatar answered Apr 24 '26 17:04

Frank Farmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!