PHP5链接mysql有2个方法
一、使用和连接MYSQL数据库一样的方法,代码如下:<?php
//php连接MySQLI
$link = mysqli_connect('localhost','user','password','world');
if (!$link){
printf("不能连接到MySQL. 错误代码: %sn", mysqli_connect_error());
exit;
}
/*发送查询指令*/
if ($result = mysqli_query($link, 'SELECT Name, Population FROM City ORDER BY Population DESC LIMIT 5')){
print("Very large cities are:n");
//开始获取查询结果
while( $row = mysqli_fetch_assoc($result) ){
printf("%s (%s)n", $row['Name'], $row['Population']);
}
mysqli_free_result($result);//注销结果集。释放内存
}
mysqli_close($link); //关闭连接
?>
二、使用内置OO接口方式<?php
//php连接MySQLI
$mysqli=new mysqli('localhost','user','password','world');
if(mysqli_connect_errno()){
printf("找不到MySQL服务. 错误编号: %sn", mysqli_connect_error());
exit;
}
/* 发送查询请求 */
if ($result = $mysqli->query('SELECT Name, Population FROM City ORDER BY Population DESC LIMIT 5')){
print("Very large cities are:n");
/* 查询结果 */
while( $row = $result->fetch_assoc() ){
printf("%s (%s)n", $row['Name'], $row['Population']);
}
/* 注销查询释放内存*/
$result->close();
}
/*关闭连接*/
$mysqli->close();
?>