php第三篇

使用php从web访问mysql数据库

1.粗略的第一部分

1
2
3
4
5
6
7
8
9
$searchterm=trim($_POST($searchterm));
if(!$searchterm)
{
echo "you have not enter anything.please try again.";
exit;
}
if(!get_magic_quotes_gpc()){
$searchterm=addslashes($searchterm);
}

2.粗略的第二部分

1
2
3
4
5
6
7
8
9
@$db=new mysqli('loalhost','用户名','密码','数据库');
if(mysqli_connect_errno())
{
echo 'could not connect to database.';
exit;
}
apache修改配置:httpd.conf中的MaxCients参数
mysql修改配置:my.conf中的max_connections参数

3.粗略的第三部分

$db->select_db(dbname);

4.粗略的第四部分

1
2
3
4
5
6
7
8
9
10
11
12
$query="select * from books where".$seartype."like %'".$searchterm."$'";
$result=$db->query($query);
$num_results=$result->num_rows;
for($i=0;$i<$num_results;$i++)
{
$row=$result->fetch_assoc;
echo stripslashes($row['关键字']);
$row=$result->fetch_row($result);
echo stripslashes($row[0]);
}

5.粗略的第五部分

1
2
$result->free();
$db->close();

prepared语句一定程度上可以免受sql注入攻击

1
2
3
4
5
6
$query="insert into books value(?,?,?,?)";
$stmt=$db->prepare($query);
$stmt->bind_param("sssd","isbn","author","title","price");
$stmt->excute();
echo $stmt->affected_rows.'book inserted into database';
$stmt->close();

用来查询结果

1
2
$stmt->bind_result();
¥stmt->excute();

每一行一个结果

1
$stmt->fetch();

就是这样,打游戏去耶耶耶!