连接
//下面使用了函数库mysqli,所以需要将php.ini文件中的extension=php.mysqli 打开
//这里采用了面向对象的语法,当然,mysqli也支持面向过程的语法
@ $db = new mysqli('localhost', 'root', 'tograce', 'books');
//以上代码实例化了mysqli类并且创建了到主机'localhost'的连接,该连接使用的用户名为和密码分别是:root,tograce,同时连接上books数据库
if (mysqli_connect_errno())
{
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
else{echo "gong xi,Connected successfully";}
$query = "select * from books";
$result = $db->query($query);
$num_results = $result->num_rows;
echo '
Number of books found: '.$num_results.'
';
$result->free();
$db->close();
?>
插入数据
摘自第11章
Book-O-Rama Book Entry ResultsBook-O-Rama Book Entry Results
// create short variable names
$isbn=$_POST['isbn'];
$author=$_POST['author'];
$title=$_POST['title'];
$price=$_POST['price'];
if (!$isbn || !$author || !$title || !$price)
{
echo 'You have not entered all the required details.
'
.'Please go back and try again.';
exit;
}
if (!get_magic_quotes_gpc())
{
$isbn = addslashes($isbn);
$author = addslashes($author);
$title = addslashes($title);
$price = doubleval($price);
}
@ $db = new mysqli('localhost', 'root', 'tograce', 'books');
if (mysqli_connect_errno())
{
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "insert into books values
('".$isbn."', '".$author."', '".$title."', '".$price."')";
$result = $db->query($query);
if ($result)
echo $db->affected_rows.' book inserted into database.';
$db->close();
?>