将mysql配置转换为mysqli [关闭]
问题描述:
I want to convert this little piece of code that I did with mysql into mysqli, anyone who can help it will be appreciated alot. I tried a couple of times to do it but I failed but I need to do it with mysqli because mysql in future will be depreciated. . .thank you in advance.
<?php
CLASS DB_Class {
//database selection classes
function DB_Class($dbname, $username, $password) {
$this->db = mysql_connect ('host', 'guest', 'dbacess')
or die ("Unable to connect to Database Server");
mysql_select_db ($dbname, $this->db) or die ("Could not select database");
}
function query($sql) {
$result = mysql_query ($sql, $this->db) or die ("Invalid query: " . mysql_error());
return $result;
}
function fetch($sql) {
$data = array();
$result = $this->query($sql);
while($row = MYSQL_FETCH_ASSOC($result)) {
$data[] = $row;
}
return $data;
}
function getone($sql) {
$result = $this->query($sql);
if(MYSQL_NUM_ROWS($result) == 0)
$value = false;
else
$value = MYSQL_RESULT($result, 0);
return $value;
}
}
?>
答
The clash on the query method was probably catching you, I've renamed this _query as you might noticed. I've tested each method to ensure they work also. Let me know if you have any issues.
class DB_Class {
//database selection classes
private $db;
function DB_Class($dbname, $host, $username, $password) {
$this->db = new mysqli($host, $username, $password, $dbname);
}
function _query($sql) {
$result = $this->db->query($sql) or die ("Invalid query: " . mysqli_error());
return $result;
}
function fetch($sql) {
$data = array();
$result = $this->_query($sql);
while($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
return $data;
}
function getone($sql) {
$result = $this->_query($sql);
if(mysqli_num_rows($result) == 0)
$value = false;
else
$value = $result->fetch_row();
return $value;
}
}