0

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

1
  • I thought we might develop an example script that includes the variable cleaning etc... Commented May 6, 2009 at 2:13

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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: br2.php.net/manual/en/function.urlencode.php
i believe that the variables will already be decoded when they're in $_GET
0

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.

2 Comments

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)
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.