使用PHP连接MYSQL数据库(面向过程方式,面向对象方式)

2009-09-06 17:30:40 by 【6yang】, 93 visits, 收藏 | 返回


<?php //数据库配置文件,db_config.php
$db_server = "localhost";
$db_user = "root";
$db_pwd = "root";
$db_name = "nhnews";
//mysql_query("SET character_set_connection=utf8, character_set_results=utf8, character_set_client=utf8");


?>


<?php
class NewsInfo{
private $nid; //属性
private $ntitle; //属性
private $ncontent;
private $ndate;
private $newsInfo; //存储数据库返回信息的数组变量.

public function __construct($id){
   require_once("includes/connectdb_odb.php"); //包含配置信息.
   $sql = "select * from  news where nid=$id"; //书写sql
   $conn = mysql_pconnect($db_server, $db_user, $db_pwd) or die("Could not connectaaaaaaa: " . mysql_error());//建立mysql连接
   $my_db = mysql_select_db($db_name,$conn);//选择数据库
   $result = mysql_query($sql,$conn); // 执行查询语句
   $this->newsInfo=mysql_fetch_array($result); //返回查询结果到数组
   mysql_close($conn); //关闭数据库连接
   $this->getInfo(); //调用传递信息的方法.
}
// 获取信息传递给属性的方法
private function getInfo(){
   $this->nid = $this->newsInfo["nid"];
   $this->ntitle = $this->newsInfo["ntitle"];
   $this->ncontent = $this->newsInfo["ncontent"];
   $this->ndate = $this->newsInfo["ndate"];
}

//返回每个属性的public 方法.
public function getNewsid(){
   return $this->nid;
}

public function getNewstitle(){
   return $this->ntitle;
}

public function getNewscontent(){
   return $this->ncontent;   
}

public function getNewsdate(){
   return $this->ndate;
}
}
?>
<?php

$id='2';
$info = new NewsInfo($id); //创建一个user对象.
$nid = $info->getNewsid(); //分别调用方法取得数据
$ntitle = $info->getNewstitle();
$ncontent = $info->getNewscontent();
$ndate = $info->getNewsdate();

echo "your id is ".$nid."<br>"; //输出数据
echo "your title is ".$ntitle."<br>" ;
echo "your content is ".$ncontent."<br>" ;
echo "your date is ".$ndate."<br>" ;

?>

分享到:
share

    图片原图

    loading

    loading