按照教程,MySQL的连接方式可以用下面两种连接方式的其中一种连接数据库:
- 面向过程的方式
- 面向对象的方式
线面的代码分别是这两种方式的实现。对比一下。一般在使用过程中,最好统一使用其中的一种,要不代码会看起来比较混乱。
面向过程的例子:
<?php
$db = mysqli_connect('localhost','root','admin','test');
if (mysqli_connect_errno()) {
die('error no conncet to db');
}
mysqli_select_db($db,'test');
$sql = 'select * from buybook';
$result = mysqli_query($db,$sql);
$num_rows = mysqli_num_rows($result);
for ($i=0; $i < $num_rows ; $i++) {
$row = mysqli_fetch_assoc($result);
echo '<p>'.$row['bookname'].'</p>';
}
mysqli_free_result($result);
mysqli_close($db);
<?php
//面向对象的方式连接数据库
$db = new mysqli('localhost', 'root','admin','test');
if (mysqli_connect_errno()) {
echo 'Error to Connect to MySQL';
exit;
}
$key=trim($_GET['key']);
if(!get_magic_quotes_gpc()){
$key=addslashes($key);
}
$sql = "select * from buybook where bookname like '%".$key."%'";
$result = $db->query($sql);
$result_rows = $result->num_rows;
echo 'number :'.$result_rows.'<br/>';
for ($i=0; $i < $result_rows ; $i++) {
$row = $result->fetch_assoc();
echo '<p>'.var_export($row).'</p>';
}
$result->free();
$db->close();