Home > php教程 > php手册 > body text

php如何连接mysql数据库

WBOY
Release: 2016-05-25 16:45:57
Original
1085 people have browsed it

很多的朋友在问php连接mysql数据库,今天我们就来讲一下最基本的最简单的利用php连接mysql数据库的实例代码吧.

$localhost ='localhost';//连接服务器,大多情况下用localhost就可以了, 
$user ='root';//mysql登录帐号 
$upwd ='123456';//mysql服务器的登陆密码 
$db = 'db';//你的mysql数据库 
$conn = mysql_connect($localhost,$user,$upwd) or die(mysql_error().'mysql数据连接失败'); 
mysql_select_db($db,$conn) or die('数据库不存在'.mysql_error());
Copy after login

上面是一种最简单的mysql与php数据库连接方法了,下来来一段稍稍具有判断性的连接代码.

<?php
$liketype = &#39;p&#39;; //这里是判断是使用长久连接还是临时连接
$charset = &#39;gbk&#39;; //设置连接mysql数据库编码,这样就不会出来连接数据库出现乱码了。
try {
    if (&#39;p&#39; == $links) {
        $conn = mysql_pconnect($localhost, $user, $upwd) or die(mysql_error());
    } else {
        $conn = mysql_connect($localhost, $user, $upwd) or die(mysql_error());
    }
    mysql_select_db($db, $conn);
    mysql_query("set names &#39;$charset&#39;");
}
catch(exception $e) {
    echo &#39;数据库连接失败,请联系相关人员!&#39;;
    exit;
}
?>
Copy after login


永久地址:

转载随意~请带上教程地址吧^^

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template