Skip to content

Instantly share code, notes, and snippets.

@jonashansen229
Last active April 21, 2021 10:26
Show Gist options
  • Save jonashansen229/4463750 to your computer and use it in GitHub Desktop.
Save jonashansen229/4463750 to your computer and use it in GitHub Desktop.
php mysqli database class
<?php
class Database {
protected $_link;
protected $_result;
protected $_numRows;
private $_host = "HOST";
private $_username = "DATABASE USERNAME";
private $_password = "DATABASE PASSWORD";
private $_database = "DATABASE";
// Establish connection to database, when class is instantiated
public function __construct() {
$this->_link = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
}
// Sends the query to the connection
public function Query($sql) {
$this->_result = $this->_link->query($sql) or die(mysqli_error($this->_result));
$this->_numRows = mysqli_num_rows($this->_result);
}
// Inserts into databse
public function UpdateDb($sql) {
$this->_result = $this->_link->query($sql) or die(mysqli_error($this->_result));
return $this->_result;
}
// Return the number of rows
public function NumRows() {
return $this->_numRows;
}
// Fetchs the rows and return them
public function Rows() {
$rows = array();
for($x = 0; $x < $this->NumRows(); $x++) {
$rows[] = mysqli_fetch_assoc($this->_result);
}
return $rows;
}
// Used by other classes to get the connection
public function GetLink() {
return $this->_link;
}
// Securing input data
public function SecureInput($value) {
return mysqli_real_escape_string($this->_link, $value);
}
}
?>
@engramiahmed
Copy link

what is the use of this variable (protected $_link;)

@n1shantshrivastava
Copy link

n1shantshrivastava commented Jul 24, 2020

In Method Query and UpdateDb ;

die(mysqli_error($this->_result));

should be

die(mysqli_error($this->_link));

as mysqli_error needs connection object from mysqli

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment