This is a very basic thing. We can use the constructor to create a class and automatically connect to the mysql server. We only need to set the values of the three variables $name, $pass, and $table.
The code is as follows |
Copy code |
class ConnectionMySQL{
//Host
private $host="localhost";
//Database username
private $name="root";
//Database password
private $pass="";
//Database name
private $table="phptest";
//Encoding form
private $ut="utf-8";
//Constructor
Function __construct(){
$this->ut=$ut;
$this->connect();
}
//Database link
Function connect(){
$link=mysql_connect($this->host,$this->name,$this->pass) or die ($this->error());
mysql_select_db($this->table,$link) or die("No such database:".$this->table);
mysql_query("SET NAMES '$this->ut'");
}
Function query($sql, $type = '') {
If(!($query = mysql_query($sql))) $this->show('Say:', $sql);
return $query;
}
Function show($message = '', $sql = '') {
If(!$sql) echo $message;
else echo $message.' '.$sql;
}
Function affected_rows() {
return mysql_affected_rows();
}
Function result($query, $row) {
return mysql_result($query, $row);
}
Function num_rows($query) {
return @mysql_num_rows($query);
}
Function num_fields($query) {
return mysql_num_fields($query);
}
Function free_result($query) {
return mysql_free_result($query);
}
Function insert_id() {
return mysql_insert_id();
}
Function fetch_row($query) {
return mysql_fetch_row($query);
}
Function version() {
return mysql_get_server_info();
}
Function close() {
return mysql_close();
}
//Insert values into $table
Function fn_insert($table,$name,$value){
$this->query("insert into $table ($name) value ($value)");
}
//Delete a record in table $table based on $id value
Function fn_delete($table,$id,$value){ $this->query("delete from $table where $id=$value");
echo "The record with id ".$id." was successfully deleted!";
}
}
//Call method
$db = new ConnectionMySQL();
$db->fn_insert('test','id,name,sex',"'','hongtenzone','M'");
$db->fn_delete('test', 'id', 1);
?>
|
Here I want to talk about the constructor
The code is as follows
代码如下 |
复制代码 |
//构造函数
function __construct(){
$this->ut=$ut;
$this->connect();
} |
|
Copy code
|
//Constructor
Function __construct(){ |
$this->ut=$ut;
$this->connect();
}
This page uses a constructor. In particular, you should not call the database connection class in the function. Otherwise, there will be multiple connections on the current page. If a large server is accessed, the statement "mysql has gone" will appear.
http://www.bkjia.com/PHPjc/632934.html
www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632934.htmlTechArticleThis is a very basic thing. We can use the constructor to create a class and automatically connect to the mysql server. We only need to set the values of the three variables $name, $pass, and $table. Generation...