php连接mysql数据库

来源:互联网 发布:淘宝卖家账号买卖 编辑:程序博客网 时间:2024/04/29 23:44

最近工作需要,于是开发部分php,记录下来,以后使用。

谅解mysql数据库

<?php
header("Content-Type:text/html; charset=utf-8"); //设置php编码格式
error_reporting(E_ALL ^ E_DEPRECATED);//调整报错等级,防止mysql_connect连接报错
    $db_host='localhost';  //连接数据库位置
$db_database='ultrax';//连接的数据库
$db_username='root';//用户名
$db_password='';//密码--我的是空
$connection=mysql_connect($db_host,$db_username,$db_password);//连接到数据库

//诊断数据库连接错误
if(!$connection){
die("could not connect to the database:</br>".mysql_error());
   }
   
   $db_selecct=mysql_select_db($db_database);//连接数据库
     if(!$db_selecct)
{
   die("could not to the database</br>".mysql_error()); 
}
//设置mysql连接编码格式
mysql_query("SET NAMES UTF8");
    mysql_query("set character_set_client=utf8"); 
    mysql_query("set character_set_results=utf8");

    $query="select a.subject,b.votes from pre_forum_thread a,pre_forum_polloption b where b.tid=a.tid and b.polloption='有' order by b.votes desc limit 0,5";
$result=mysql_query($query);//执行sql语句
$num=mysql_num_rows($result);//获取行数
//判断查询结果
if($num=='0'){
die("未查询到结果!</br>".mysql_error());//诊断连接错误
}else{
while($row = mysql_fetch_array($result))
{
      $subject=$row['subject'];
      $votes=$row['votes'];
           echo  "$subject";
      echo "$votes</br>";
         }


}


mysql_close($connection);//关闭数据库连接
?>

运行可到结果,其中$query为执行的sql语句,我用的是多表查询,分别查询两个的结果。

为防止查询结果为空,获取了查询结果的行数,并判断。

只是我的第一个微博,以后会有更多。 为梦想,奋斗!

参考文章:http://www.cnblogs.com/blackhorse/archive/2012/05/07/2487365.html

0 0