框架用多啦,别忘记了原生,多练练手 phpmysqli 链接数据库
<?php class mysql{ private $db_name; private $db_host; private $db_user; private $db_pwd; private $conn; private $querysql; private $result; private $resultarray=array(); private $row; //创建构造函数 数据库名 主机名 用户名 密码 function __construct($dbname,$dbhost,$dbuser,$dbpwd){ $this->db_name=$dbname; $this->db_host=$dbhost; $this->db_pwd=$dbpwd; $this->db_user=$dbuser; } //连接数据库 private function db_connect(){ $this->conn = mysqli_connect($this->db_host,$this->db_user,$this->db_pwd,$this->db_name) or die("Could not Connect MySql Server"); return $this->conn; } //选择数据库 private function selectdb(){ mysql_select_db($this->db_name) or die("unable to select dbname"); } //执行sql语句 private function query($sql){ $conn = self::db_connect(); return $this->result=mysqli_query($conn,$sql); } //$result返回值为 bool类型 false为没有数据 private function get_num($result){ return $this->num=mysqli_num_rows($result); } //执行结果 返回数据 public function get_result($sql){ $result = $this->query($sql); if($this->get_num($result)>0){ //mysql_fetch_assoc()和 mysql_fetch_array(,MYSQL_ASSOC)从结果集中取得一行作为关联数组 没有则返回false while($this->rows=mysqli_fetch_array($result)){ //赋值 数组赋值 resultarray[]= 将影响的行数赋值给数组 $this->resultarray[]=$this->rows; } return $this->resultarray; }else{ echo "暂无数据!"; } } //版本信息 function version() { $conn = self::db_connect(); return mysqli_get_server_info($conn); } //关闭资源 function close() { $conn = self::db_connect(); return mysqli_close(); } //向$table表中插入值 function fn_insert($table,$name,$value){ $this->query("insert into $table ($name) value ($value)"); } //根据$id值删除表$table中的一条记录 function fn_delete($table,$id,$value){ $this->query("delete from $table where $id=$value"); echo "id为". $id." 的记录被成功删除!"; } } $m = new mysql("admin","127.0.0.1","root","root"); $arreresult = $m->get_result("select * from yii_msg");