The mysqli class
(PHP 5)
Introduction
Represents a connection between PHP and a MySQL database.
Class synopsis
mysqli
{
/* Properties */
int $affected_rows;
string $client_info;
int $client_version;
string $connect_errno;
string $connect_error;
int $errno;
array $error_list;
string $error;
int $field_count;
int $client_version;
string $host_info;
string $protocol_version;
string $server_info;
int $server_version;
string $info;
string $sqlstate;
int $thread_id;
int $warning_count;
/* Methods */
__construct
([ string
$host
= ini_get("mysqli.default_host")
[, string $username
= ini_get("mysqli.default_user")
[, string $passwd
= ini_get("mysqli.default_pw")
[, string $dbname
= ""
[, int $port
= ini_get("mysqli.default_port")
[, string $socket
= ini_get("mysqli.default_socket")
]]]]]] )
bool real_connect
([ string
}$host
[, string $username
[, string $passwd
[, string $dbname
[, int $port
[, string $socket
[, int $flags
]]]]]]] )Table of Contents
- mysqli::$affected_rows — Gets the number of affected rows in a previous MySQL operation
- mysqli::autocommit — Turns on or off auto-committing database modifications
- mysqli::begin_transaction — Starts a transaction
- mysqli::change_user — Changes the user of the specified database connection
- mysqli::character_set_name — Returns the default character set for the database connection
- mysqli::$client_info — Get MySQL client info
- mysqli::$client_version — Returns the MySQL client version as a string
- mysqli::close — Closes a previously opened database connection
- mysqli::commit — Commits the current transaction
- mysqli::$connect_errno — Returns the error code from last connect call
- mysqli::$connect_error — Returns a string description of the last connect error
- mysqli::__construct — Open a new connection to the MySQL server
- mysqli::debug — Performs debugging operations
- mysqli::dump_debug_info — Dump debugging information into the log
- mysqli::$errno — Returns the error code for the most recent function call
- mysqli::$error_list — Returns a list of errors from the last command executed
- mysqli::$error — Returns a string description of the last error
- mysqli::$field_count — Returns the number of columns for the most recent query
- mysqli::get_charset — Returns a character set object
- mysqli::get_client_info — Get MySQL client info
- mysqli_get_client_stats — Returns client per-process statistics
- mysqli_get_client_version — Returns the MySQL client version as an integer
- mysqli::get_connection_stats — Returns statistics about the client connection
- mysqli::$host_info — Returns a string representing the type of connection used
- mysqli::$protocol_version — Returns the version of the MySQL protocol used
- mysqli::$server_info — Returns the version of the MySQL server
- mysqli::$server_version — Returns the version of the MySQL server as an integer
- mysqli::get_warnings — Get result of SHOW WARNINGS
- mysqli::$info — Retrieves information about the most recently executed query
- mysqli::init — Initializes MySQLi and returns a resource for use with mysqli_real_connect()
- mysqli::$insert_id — Returns the auto generated id used in the last query
- mysqli::kill — Asks the server to kill a MySQL thread
- mysqli::more_results — Check if there are any more query results from a multi query
- mysqli::multi_query — Performs a query on the database
- mysqli::next_result — Prepare next result from multi_query
- mysqli::options — Set options
- mysqli::ping — Pings a server connection, or tries to reconnect if the connection has gone down
- mysqli::poll — Poll connections
- mysqli::prepare — Prepare an SQL statement for execution
- mysqli::query — Performs a query on the database
- mysqli::real_connect — Opens a connection to a mysql server
- mysqli::real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
- mysqli::real_query — Execute an SQL query
- mysqli::reap_async_query — Get result from async query
- mysqli::refresh — Refreshes
- mysqli::release_savepoint — Rolls back a transaction to the named savepoint
- mysqli::rollback — Rolls back current transaction
- mysqli::rpl_query_type — Returns RPL query type
- mysqli::savepoint — Set a named transaction savepoint
- mysqli::select_db — Selects the default database for database queries
- mysqli::send_query — Send the query and return
- mysqli::set_charset — Sets the default client character set
- mysqli::set_local_infile_default — Unsets user defined handler for load local infile command
- mysqli::set_local_infile_handler — Set callback function for LOAD DATA LOCAL INFILE command
- mysqli::$sqlstate — Returns the SQLSTATE error from previous MySQL operation
- mysqli::ssl_set — Used for establishing secure connections using SSL
- mysqli::stat — Gets the current system status
- mysqli::stmt_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare
- mysqli::store_result — Transfers a result set from the last query
- mysqli::$thread_id — Returns the thread ID for the current connection
- mysqli::thread_safe — Returns whether thread safety is given or not
- mysqli::use_result — Initiate a result set retrieval
- mysqli::$warning_count — Returns the number of warnings from the last query for the given link
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- MySQL Drivers and Plugins
- Введение
- Краткий обзор
- Краткое руководство
- Установка и настройка
- Расширение mysqli и постоянные соединения
- Предопределенные константы
- Notes
- Основная информация о функциях расширения MySQLi
- Examples
- Класс mysqli
- The mysqli_stmt class
- The mysqli_result class
- Класс mysqli_driver
- Класс mysqli_warning
- The mysqli_sql_exception class
- Синонимы и устаревшие Функции Mysqli
- Список изменений
Коментарии
<?php
include_once("data/Book.php");
include_once("DatabaseFactory.php");
// CRUD methods for book objects
class BookDB{
private static function getConnection(){
return DatabaseFactory::getDatabase();
}
public static function getAll(){
$query = "SELECT * FROM Book";
// Execute query
$conn = self::getConnection();
$results = $conn->executeQuery($query);
$resultsArray = array();
for($i = 0; $i < $results->num_rows; $i++){
$row = $results->fetch_array(); // Retrieves the current selected row
// Make a book
$book = self::convertRowToObject($row);
// Add book to resultsArray
$resultsArray[$i] = $book;
}
return $resultsArray;
}
public static function convertRowToObject($row){
return new Book(
$row["BookId"],
$row["Title"],
$row["Releasedate"],
$row["Price"],
$row["EmailPublisher"]
);
}
public static function insert($book){
return self::getConnection()->executeQuery("INSERT INTO Book(Title, Releasedate, Price, EmailPublisher) VALUES ('?', '?', '?', '?')", array($book->title, $book->releasedate, $book->priceExclVAT, $book->emailPublisher));
}
}
?>
<?php
class Database{
protected $url;
protected $user;
protected $password;
protected $db;
protected $connection = null;
public function __construct($url, $user, $password, $db)
{
$this->url = $url;
$this->user = $user;
$this->password = $password;
$this->db = $db;
}
public function __destruct()
{
if($this->connection != null){
$this->closeConnection();
}
}
protected function makeConnection(){
$this->connection = new mysqli($this->url, $this->user, $this->password, $this->db);
if($this->connection->connect_error){
echo "Fail" . $this->connection->connect_error;
}
}
protected function closeConnection(){
if($this->connection != null){
$this->connection->close();
$this->connection = null;
}
}
public function executeQuery($query, $params = null){
// Is there a DB connection?
$this->makeConnection();
// Adjust query with params if available
if($params != null){
// Change ? to values from parameter array
$queryParts = preg_split("/\?/", $query);
// if amount of ? is not equal to amount of values => error
if(count($queryParts) != count($params) + 1){
return false;
}
// Add first part
$finalQuery = $queryParts[0];
// Loop over all parameters
for($i = 0; $i < count($params); $i++){
// Add clean parameter to query
$finalQuery = $finalQuery . $this->cleanParameters($params[$i]) . $queryParts[$i + 1];
}
$query = $finalQuery;
}
// Check for SQL injection
$result = $this->connection->query($query);
return $result;
}
protected function cleanParameters($parameters){
// prevent SQL injection
$result = $this->connection->real_escape_string($parameters);
return $result;
}
}
?>
<?php
include_once("Database.php");
class DatabaseFactory{
// Singleton
private static $connection;
public static function getDatabase(){
if(self::$connection == null){
$url = "dt5.ehb.be";
$user = "1920WEBINT038";
$passw = "94617528";
$db = "1920WEBINT038";
self::$connection = new Database($url, $user, $passw, $db);
}
return self::$connection;
}
}
?>
<?php
class Book{
public $bookId;
public $title;
public $releasedate;
public $priceExclVAT;
public $emailPublisher;
public function __construct($bookId, $title, $releasedate, $priceExclVAT, $emailPublisher)
{
$this->bookId = $bookId;
$this->title = $title;
$this->releasedate = $releasedate;
$this->priceExclVAT = $priceExclVAT;
$this->emailPublisher = $emailPublisher;
}
}
?>