Home  >  Article  >  php教程  >  php如何连接mysql数据库

php如何连接mysql数据库

WBOY
WBOYOriginal
2016-05-25 16:45:571088browse

很多的朋友在问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());

上面是一种最简单的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;
}
?>


永久地址:

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

Statement:
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