Php mysqli class library

The mysqli class

Represents a connection between PHP and a MySQL database.

Class synopsis

public __construct (
? string $hostname = null ,
? string $username = null ,
? string $password = null ,
? string $database = null ,
? int $port = null ,
? string $socket = null
)

public connect (
? string $hostname = null ,
? string $username = null ,
? string $password = null ,
? string $database = null ,
? int $port = null ,
? string $socket = null
): bool

public static poll (
? array &$read ,
? array &$error ,
array &$reject ,
int $seconds ,
int $microseconds = 0
): int | false

public real_connect (
? string $hostname = null ,
? string $username = null ,
? string $password = null ,
? string $database = null ,
? int $port = null ,
? string $socket = null ,
int $flags = 0
): bool

public ssl_set (
? string $key ,
? string $certificate ,
? string $ca_certificate ,
? string $ca_path ,
? string $cipher_algos
): true

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 current character set of the database connection
  • 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 description of the last connection 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::execute_query — Prepares, binds parameters, and executes SQL statement
  • mysqli::$field_count — Returns the number of columns for the most recent query
  • mysqli::get_charset — Returns a character set object
  • mysqli::$client_info — Get MySQL client info
  • mysqli::$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 an object for use with mysqli_real_connect()
  • mysqli::$insert_id — Returns the value generated for an AUTO_INCREMENT column by 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 one or more queries 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 — Prepares 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 — Removes the named savepoint from the set of savepoints of the current transaction
  • mysqli::rollback — Rolls back current transaction
  • mysqli::savepoint — Set a named transaction savepoint
  • mysqli::select_db — Selects the default database for database queries
  • mysqli::set_charset — Sets the client character set
  • 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
Читайте также:  Mysql and java in ubuntu

User Contributed Notes

  • MySQLi
    • Introduction
    • Overview
    • Quick start guide
    • Installing/Configuring
    • The mysqli Extension and Persistent Connections
    • Predefined Constants
    • Notes
    • The MySQLi Extension Function Summary
    • mysqli
    • mysqli_​stmt
    • mysqli_​result
    • mysqli_​driver
    • mysqli_​warning
    • mysqli_​sql_​exception
    • Aliases and deprecated Mysqli Functions
    • Changelog

    Источник

    PHP Class MySQLi — СУБД MySQL

    На сегодняшний день существует множество статей с готовыми решениями, как работать с СУБД MySQL. Однако, почти в каждой статье приводятся примеры процедурного вызова функций. Начиная с php-версии 5.5.0 расширение MySQL будет удалено из сборки и вообще, это расширение уже устарело. Вместо него будем использовать расширение MySQLi в ООП.
    Данная статья является готовым решением для работы с СУБД.

    При разработке очередного проекта, я столкнулся с тем, что в каждом методе следующего написанного класса с обращением к СУБД, мне нужно было обращаться к классу работы с СУБД, для очередного select, insert, update и т.п., то есть тягать в функции параметра global с объявленной переменной вне класса. А устанавливать новое соединение с базой — слишком затратно, да и не выгодно, только ресурсы системы тратить. И решил написать переписать класс работы с базой, с сохранением экземпляра класса, чтобы обращаться сразу напрямую к методам класса из любой области видимости переменной.

    Для просмотра исходника смотрим под кат.

    Для инициализации класса достаточно создать экземпляр класса.
    Переменную $db не следует удалять после объявления, т.к. ее адрес используется для дальнейшей работы со статическими методами класса.

     catch (Exception $e) < exit($e->getMessage()); > ?> 

    Ниже приведу содержимое класса DB.class.php

    connect_error) throw new Exception("Connect failed: %s", $mysqli->connect_error); self::$mysqli = &$mysqli; self::$mysqli->query('SET NAMES utf8 COLLATE utf8_general_ci'); > public static function GetRows($rows, $single = false) < $result = array(); if ($rows === false) return $result; if ($single) return $rows->fetch_assoc(); while ($row = $rows->fetch_assoc()) array_push($result, $row); $rows->free(); return $result; > public static function Select($sql, $single = false) < $result = self::$mysqli->query($sql); return self::$db->GetRows($result, $single); > public static function Update($data, $table, $where) < $sets = ''; foreach ($data as $column =>$value) < $sets .= $sets ? ', ' : ''; $sets .= "`$column` = '$value'"; >$sql = "UPDATE $table SET $sets WHERE $where"; self::$mysqli->query($sql); > public static function Insert($data, $table) < $columns = ""; $values = ""; foreach ($data as $column =>$value) < $columns .= $columns ? ', ' : ''; $columns .= "`$column`"; $values .= $values ? ', ' : ''; $values .= "'$value'"; >$sql = "INSERT INTO $table ($columns) VALUES ($values)"; self::$mysqli->query($sql); return self::$mysqli->insert_id; > public static function CountRows($table, $request = false) < $sql = "SELECT COUNT(*) FROM $table "; $sql .= $request ? $request : ''; $result = self::$mysqli->query($sql); $count = $result->fetch_array(); $result->free(); return $count[0]; > public static function Query($sql) < return self::$mysqli->query($sql); > public static function Delete($table, $where) < $sql = "DELETE FROM $table WHERE $where"; self::$mysqli->query($sql); > public static function Close() < self::$mysqli->close(); > function __destruct() < self::$db->Close(); > > ?> 

    Источник

    Saved searches

    Use saved searches to filter your results more quickly

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

    Simple Mysqli Library for PHP

    License

    bencagri/PHP-Mysqli-Class

    This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

    Name already in use

    A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

    Sign In Required

    Please sign in to use Codespaces.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching Xcode

    If nothing happens, download Xcode and try again.

    Launching Visual Studio Code

    Your codespace will open once ready.

    There was a problem preparing your codespace, please try again.

    Latest commit

    Git stats

    Files

    Failed to load latest commit information.

    README.md

    Simple Mysqli Library for PHP

    | id | user_name | user_email | ------------------------------------ | 1 | John Doe | john@google.com | | 2 | Jen Doe | jen@google.com | | 3 | Junior Doe| junior@google.com| 

    This class has query,table,update,delete and insert methods to easily usage. First we need to configure our database connection.

    require("mysqli.class.php"); $config['db_host'] = "localhost"; $config['db_username'] = "root"; $config['db_password'] = "password"; $config['db_name'] = "testdb"; $db = new db(); 

    ###Inserting Data This method gets two parameters. First is «table name», second is our data in array. @param Array Data

    $db->insert("users", array("user_name" => "John Doe", "user_email" => "john@google.com") ); 

    ###Update This method gets three parameters. First is «table name», second is our data in array and third is «where situation»

    $db->update("users", array("user_name" => "Jen Doe", "user_email" => "jen@google.com), array("id" => "1"); 

    Important : If you dont set second param, this method drops your table!

    ###List Table This method returns array object.

     $users = $db->table("SELECT * FROM users); foreach($users as $user)< echo $user->user_name; > 

    ###List One Row This method list one row by your query.

    $user = $db->row("SELECT * FROM users WHERE $user->user_name; //output John Doe 
    $count = $db->field("SELECT COUNT(id) FROM users); echo $count; //output 3 

    Источник

Оцените статью