SQL-Injection prevention

Hey, I have an example of a “posting an article by user input” script, which input then will be displayed on a certain website; though there are probably some security issues within that script that I’d like to know how to prevent, - for instance, SQL-Injection.

Here’s the code:



<?php

// Noetig fuer die Datenbank.
require('php/connect.php');

// Unsere Variablen.
$postnews	 = $_POST['postnews'];
$ip		   = $_SERVER['REMOTE_ADDR'];

// Unsere if-statements.
if (empty($postnews)) {
   echo"Bitte gebe deinen Newsbeitrag ein.";
}
else {
// Wenn alles uebereinstimmt, fuege es in die Datenbank hinein.
   mysql_query("INSERT INTO news (post, ip) VALUES ('$postnews', '$ip')");
   header('Location: index.php');
}

?>



The $postnews variable is a declaration for the <input> field, which lets someone post something; - how and why would someone be able to inject SQL queries? Why would it work, and how would I prevent it? I’d like to see code examples of how I can prevent it.

Regards

examples of sql injection

Validating all user inputs and sanitising them with mysql_real_escape_string() or using prepared statements are your best defences against sql injection or other attacks.

Examples: SQL Injection Attacks by Example

We have a thread stickied to the top of the forum, called PHP and MySQL Coding Tips
You may want to study a post there called Handling Input and Output

also it’s probably good to keep in mind that if you are building commercial database driven websites, or any website for that matter, you need to not leave yourself vulnerable to being sued for compensation and/or damages for being “negligent” in your coding.

Thanks, it’s been a great help to me.

You might also look into using prepare/bind instead of query to do the database updaters as that keeps the data completely separated and so makes SQL injection completely impossible.

Hello.

mysqli_query() already prevent SQL injection? It allow to run only one sql command.

The procedural style of mysqli_query has no more prevention than [url=“http://nz2.php.net/manual/en/function.mysql-query.php”]mysql_query

It’s the object oriented style of mysqli::prepare that provides much better injection protection.