准备好的语句始终是sql查询的方法。 php有一个名为mysqli的库。事实上,mysqli中的“i”代表“改进”说很多:)
这是一个例子!首先,我这样做到我的数据库:
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');然后我使用这个PHP脚本(名为news.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
\n$sql
\nerror reports:
\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();
?>我这样调用脚本:
http://localhost/news.php?min=1&max=2