tags:

views:

184

answers:

2

Hi All

I'm looking for a simple and secure script to insert rows into a mysql table from a php script.

by calling http://www.myserver.com/addtosometable.php?1=asdf&2=asdf....

I'm not asking how specifically, rather I thought this might be a good platform to build a example script and keep it up to date with best practices...

Cheers

+2  A: 

all the URL variables (GET variables) are put into the PHP variable $_GET as an array.

Using your example above myfile.php?1=asdf&2=asdf your script would have access to an array that looks like this:

array(
    1 => "asdf"
    2 => "asdf"
)

If you want to see this for yourself, just put this in your file:

print_r($_GET);

From there it should be a simple task of cleaning the variables to avoid injection attacks and then creating an INSERT statement. I'd need to know more about your table structure and whatnot to help you specifically with that. See the docs on mysql_real_escape_string.

nickf
It might also help to take a look at the urlencode/decode functions, if the content you want to pass contains special chars, like >,<, space, etc..See: http://br2.php.net/manual/en/function.urlencode.php
Macalendas
i believe that the variables will already be decoded when they're in $_GET
nickf
A: 

If you're using MySQL 5, you can use prepared statements to avoid most forms of SQL Injection.


$stmt = $db->prepare("INSERT INTO table ( col1, col2 ) values ( ?, ? );
// check for errors 
$result = $stmt->execute( $_GET['1'], $_GET['2'] );
// check for errors

I believe you still have to worry about XSS (Cross-Site-Scripting) attacks, but that's beyond my ken.

hapes
this is using a DB framework though, right?
nickf
The example provided is using MDB2, which is indeed a DB framework. You can use mysqli->prepare() just as well, but it involves more statements (prepare, bind_param, execute, bind_result, fetch), compared to 3 with MDB2 (prepare, execute, fetch)
hapes
MDB2 is pretty painless to implement, and you can install PEAR modules without being root or even having shell access, so there's no excuse to not use a DB framework.
hapes
Were you looking to not use DB frameworks?
hapes