1

I just want to check how safe (if at all) my PHP-MYSQL queries are, I'm using user data which is coming through $_POST and then validating - the validation process of all data includes using mysqli_real_escape_string() on the string and trim(). The nature of some of my inputs however means that I don't restrict any characters on user input. Is what I'm doing safe and if not how could it be improved.

An example of an insert query (where $name and $description are $_POST data values which have been through a validation function.)

    $sql = "INSERT INTO company(company_name, company_description) VALUES('".$name."', '".$description."')";
$result = mysqli_query($con, $sql);

An example of a select query (where $companyid is user input, real_escaped and stripped)

    $sql = "SELECT * FROM events WHERE event_company=".$companyid."";
$result = mysqli_query($con, $sql);

Thanks in advance.

Andrew
  • 47
  • 6
  • 3
    your queries are not safe at all, you need to use PDO or mysqli prepared statements – cmorrissey Aug 31 '17 at 15:35
  • 1
    get a feel for consequences of SQL injections **[here](https://xkcd.com/327/)** , and if you dont want to have to deal with it, read **[this fairly comprehensive question/answers on the topic.](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)** – YvesLeBorg Aug 31 '17 at 15:55
  • 1
    `mysqli_real_escape_string` won't protect your select query at all. You can try it with `$company="1 or event_company=2";`.If 1 and 2 are in your db you'll get both. – jh1711 Aug 31 '17 at 15:57

2 Answers2

2

Here are your queries updated to use mysqli prepared statements.

$sql    = "INSERT INTO `company` (`company_name`, `company_description`) VALUES(?, ?)";
$stmt   = $con->prepare($sql);
$stmt->bind_param('ss',$name,$description); // ss is for string string
$stmt->execute();
$result = $stmt->get_result();

and

$sql    = "SELECT * FROM `events` WHERE `event_company` = ?";
$stmt   = $con->prepare($sql);
$stmt->bind_param('i',$companyid); // i indicates integer 
$stmt->execute();
$result = $stmt->get_result();
cmorrissey
  • 8,493
  • 2
  • 23
  • 27
0

There a type of hack called "SQL INJECTION" which can deceive your control. Read there for more information https://www.veracode.com/security/sql-injection

Pelliz18
  • 51
  • 1
  • 7