An easy to use MySQL access library for PHP featuring safe placeholders without the annoyance.

Works with mysql or mysqli libraries for PHP.

If you're developing a web application with PHP and MySQL, then you're probably going to need to read and write records with data supplied by your users.

You have to be aware of SQL-injection attacks where a person might type in that their name is "; DROP DATABASE mysql and trash your database when their input is used in a query like SELECT * FROM people WHERE name="$name".

You could search and replace quotes and other punctuation in people's inputs to prevent this, but you can also use SQL placeholders which are much safer.

Using placeholders, your query looksl ike this: SELECT * FROM people WHERE name=? and then you supply a value for the placeholder with a mysql function.

Using placeholders is safe but it's cumbersome because they are positional and if you have more than one in your query and you want to change the query you have to always count placeholder 1, 2, 3, etc and change the order of your function calls later to match.

I created the _mysql.php library to solve this problem and make placeholders as easy and convenient to use as the "old way".

Here's a sample query with my library:

$people = db_select_param("SELECT * FROM people where name=:name[s]",
foreach($people as &$person) {
	// do something with each $person

The result set always comes back as an array even if there's just one result.

Using this library, you can use placeholders like :name[s] instead of ?. The : indicates a placeholder. In this example, name is the name of the placeholder and is the key to the value in the data array that comes after the query. Finally, [s] indicates that name is a string. You can also use [i] for integer or [d] for double or float.

Here's a sample update:

$person = array();
$person['name'] = "Bob";
$person['years'] = 28;
$person['income'] = 8982.15;
db_update("UPDATE people SET name=:name[s], age=:years[i], salary=:income[d]", $person);


Get the source: mysql.php.txt or mysqli.php.txt