prepared statements is always the way to go about sql queries. php has a library called mysqli. the fact that the "i" in mysqli stands for "improved" says alot :)
here's an example! first, i did this to my database:
create database mydatabase default character set = UTF8;
use mydatabase;
create table news(id int auto_increment, title varchar(50), body text, primary key (id));
insert into news(title, body) values('good news','are good');
insert into news(title, body) values('old news','are old');
and then i used this php script (named news.php) to access my table:
<?php
//my root user doesn't have a password, so third argument is empty string
$db = new mysqli("localhost", "root", "", "mydatabase");
if(mysqli_connect_errno()) {
die("unable to connect to database: " . mysqli_connect_error());
}
//change character set to utf8
if(!$db->set_charset("utf8")) {
die("Error loading character set utf8:\n{$mysqli->error}");
}
//the question marks denote parameters to be bound
$sql = "SELECT * FROM news WHERE id BETWEEN ? AND ?;";
$statement = $db->stmt_init();
$statement->prepare($sql);
$sqlError = $db->error;
if($sqlError != "") {
die("there was a problem with your query<br />\n$sql<br />\nerror reports:<br />\n$sqlError");
}
//the "i":s denote both parameters to bind are int
$statement->bind_param("ii", $min, $max);
$min = $_GET['min'];
$max = $_GET['max'];
$statement->execute();
$statement->store_result();
$statement->bind_result($id, $title, $body);
//everytime fetch is called, a new line is attempted to be read.
//if a line was read, two things happen:
//1. true is returned
//2. the values of the columns in the fetched result row is stored in the
// variables bound as results on the line above
while($statement->fetch()) {
print "$id, $title, $body";
}
$statement->free_result();
$statement->close();
$db->close();
?>
i called the script like so:
http://localhost/news.php?min=1&max=2