- mysqli_info
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- mysql_get_server_info
- Description
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes 3 notes
- PHP Connect to MySQL
- Should I Use MySQLi or PDO?
- MySQL Examples in Both MySQLi and PDO Syntax
- MySQLi Installation
- PDO Installation
- Open a Connection to MySQL
- Example (MySQLi Object-Oriented)
- Example (MySQLi Procedural)
- Example (PDO)
- Close the Connection
- PHP MySQL Connection | Connect PHP To MySQL Database
- How to Connect PHP with MySQL Database
- 1. MySQLi Procedural
- 2. MySQLi Object-Oriented
- 3. MySQL PDO
- 4. MySQLi OOPS
- Database Connection File Inclusion
- My Suggestion
- Related posts:
mysqli_info
Функция mysqli_info() возвращает строку с информацией о последнем выполненном запросе к базе данных. Описание строки приведено ниже:
Тип запроса | Пример результирующей строки |
---|---|
INSERT INTO. SELECT. | Records: 100 Duplicates: 0 Warnings: 0 |
INSERT INTO. VALUES (. ),(. ),(. ) | Records: 3 Duplicates: 0 Warnings: 0 |
LOAD DATA INFILE . | Records: 1 Deleted: 0 Skipped: 0 Warnings: 0 |
ALTER TABLE . | Records: 3 Duplicates: 0 Warnings: 0 |
UPDATE . | Rows matched: 40 Changed: 40 Warnings: 0 |
Замечание:
Запросы, не попадающие в приведённый список, не поддерживаются. В таких ситуациях mysqli_info() вернёт пустую строку.
Список параметров
Только для процедурного стиля: объект mysqli , полученный с помощью mysqli_connect() или mysqli_init() .
Возвращаемые значения
Строка символов представляющая дополнительную информацию о последнем запущенном запросе.
Примеры
Пример #1 Пример использования $mysqli->info
mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$mysqli = new mysqli ( «localhost» , «my_user» , «my_password» , «world» );
$mysqli -> query ( «CREATE TEMPORARY TABLE t1 LIKE City» );
/* INSERT INTO . SELECT */
$mysqli -> query ( «INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150» );
printf ( «%s\n» , $mysqli -> info );
?>
mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$link = mysqli_connect ( «localhost» , «my_user» , «my_password» , «world» );
mysqli_query ( $link , «CREATE TEMPORARY TABLE t1 LIKE City» );
/* INSERT INTO . SELECT */
mysqli_query ( $link , «INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150» );
printf ( «%s\n» , mysqli_info ( $link ));
?>
Результат выполнения данных примеров:
Records: 150 Duplicates: 0 Warnings: 0
Смотрите также
- mysqli_affected_rows() — Получает число строк, затронутых предыдущей операцией MySQL
- mysqli_warning_count() — Возвращает количество предупреждений из последнего запроса заданного подключения
- mysqli_num_rows() — Получает количество строк в наборе результатов
mysql_get_server_info
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
Description
Retrieves the MySQL server version.
Parameters
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values
Returns the MySQL server version on success or false on failure.
Examples
Example #1 mysql_get_server_info() example
$link = mysql_connect ( ‘localhost’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) die( ‘Could not connect: ‘ . mysql_error ());
>
printf ( «MySQL server version: %s\n» , mysql_get_server_info ());
?>?php
The above example will output something similar to:
MySQL server version: 4.0.1-alpha
See Also
- mysql_get_client_info() — Get MySQL client info
- mysql_get_host_info() — Get MySQL host info
- mysql_get_proto_info() — Get MySQL protocol info
- phpversion() — Gets the current PHP version
User Contributed Notes 3 notes
An alternative to mysql_get_client_info() is to use the VERSION() function in MySQL language like:
$query = mysql_query ( «SELECT VERSION() as mysql_version» );
?>
The output is the same as mysql_get_client_info()
Here is something I put together because I needed a way to pull the MySQL version number from the server without actually having a connection. This was due to being part of a server info screen prior to installation of a cms. Users need to know if their MySQL is supported or not prior to installation right? 🙂
This will scrape the phpinfo page looking for the MySQL row that says Client API version and return the version number after it. This could also be used to scrape just about anything from the phpinfo page. 🙂
ob_start();
phpinfo(INFO_MODULES);
$info = ob_get_contents();
ob_end_clean();
$info = stristr($info, ‘Client API version’);
preg_match(‘/2.3.13/’, $info, $match);
$gd = $match[0];
echo ‘MySQL: ‘.$gd.’
‘;
This will output:
MySQL: 4.1.22 (which is the version on my server)
I know this is crude but it’s the only thing I could come up with and there isn’t anything like this info available online so here it is. I suck at preg_match and it would be helpful if someone could modify the string here to stand the test of time.
mysql_connect ( ‘localhost’ , ‘user’ , ‘password’ ) or
die( ‘Could not connect: ‘ . mysql_error ());
$a = mysql_get_server_info ();
$b = substr ( $a , 0 , strpos ( $a , «-» ));
echo $b ;
?>
- MySQL Functions
- mysql_affected_rows
- mysql_client_encoding
- mysql_close
- mysql_connect
- mysql_create_db
- mysql_data_seek
- mysql_db_name
- mysql_db_query
- mysql_drop_db
- mysql_errno
- mysql_error
- mysql_escape_string
- mysql_fetch_array
- mysql_fetch_assoc
- mysql_fetch_field
- mysql_fetch_lengths
- mysql_fetch_object
- mysql_fetch_row
- mysql_field_flags
- mysql_field_len
- mysql_field_name
- mysql_field_seek
- mysql_field_table
- mysql_field_type
- mysql_free_result
- mysql_get_client_info
- mysql_get_host_info
- mysql_get_proto_info
- mysql_get_server_info
- mysql_info
- mysql_insert_id
- mysql_list_dbs
- mysql_list_fields
- mysql_list_processes
- mysql_list_tables
- mysql_num_fields
- mysql_num_rows
- mysql_pconnect
- mysql_ping
- mysql_query
- mysql_real_escape_string
- mysql_result
- mysql_select_db
- mysql_set_charset
- mysql_stat
- mysql_tablename
- mysql_thread_id
- mysql_unbuffered_query
PHP Connect to MySQL
PHP 5 and later can work with a MySQL database using:
- MySQLi extension (the «i» stands for improved)
- PDO (PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in 2012.
Should I Use MySQLi or PDO?
If you need a short answer, it would be «Whatever you like».
Both MySQLi and PDO have their advantages:
PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases.
So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries. With MySQLi, you will need to rewrite the entire code — queries included.
Both are object-oriented, but MySQLi also offers a procedural API.
Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very important for web application security.
MySQL Examples in Both MySQLi and PDO Syntax
In this, and in the following chapters we demonstrate three ways of working with PHP and MySQL:
MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed in most cases, when php5 mysql package is installed.
PDO Installation
Open a Connection to MySQL
Before we can access data in the MySQL database, we need to be able to connect to the server:
Example (MySQLi Object-Oriented)
$servername = «localhost»;
$username = «username»;
$password = «password»;?php
// Create connection
$conn = new mysqli($servername, $username, $password);// Check connection
if ($conn->connect_error) die(«Connection failed: » . $conn->connect_error);
>
echo «Connected successfully»;
?>Note on the object-oriented example above:
$connect_error was broken until PHP 5.2.9 and 5.3.0. If you need to ensure compatibility with PHP versions prior to 5.2.9 and 5.3.0, use the following code instead:
// Check connection
if (mysqli_connect_error()) die(«Database connection failed: » . mysqli_connect_error());
>Example (MySQLi Procedural)
$servername = «localhost»;
$username = «username»;
$password = «password»;?php
// Create connection
$conn = mysqli_connect($servername, $username, $password);// Check connection
if (!$conn) die(«Connection failed: » . mysqli_connect_error());
>
echo «Connected successfully»;
?>Example (PDO)
$servername = «localhost»;
$username = «username»;
$password = «password»;?php
try $conn = new PDO(«mysql:host=$servername;dbname=myDB», $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo «Connected successfully»;
> catch(PDOException $e) echo «Connection failed: » . $e->getMessage();
>
?>Note: In the PDO example above we have also specified a database (myDB). PDO require a valid database to connect to. If no database is specified, an exception is thrown.
Tip: A great benefit of PDO is that it has an exception class to handle any problems that may occur in our database queries. If an exception is thrown within the try < >block, the script stops executing and flows directly to the first catch() < >block.
Close the Connection
The connection will be closed automatically when the script ends. To close the connection before, use the following:
PHP MySQL Connection | Connect PHP To MySQL Database
If you have to develop your application using PHP. you will have to stabilize PHP MySQL Connection. It helps to insert, retrieve, update & delete data in the database.
This tutorial will be helpful for learner developers as well as experienced developers. So, Not only experienced developers but also fresher can understand the concepts of this article.
Generally, most of the interviewers asked questions related to database connection. They expect the best answers from the candidates. Therefore they go into the depth of PHP Connect to MySQL. So, developers must read all the given steps. Because, every step contains more useful information.
How to Connect PHP with MySQL Database
You have to connect PHP to MySQL through the following steps.
- First of all, install Xampp /WapmServer on your pc
- Start Local Server
- Open PHPMyAdmin
- Create Database in PHPMyAdmin
- Create a project folder or PHP File
- Write the following MYSQL query to connect the database using PHP.
- MySQLi Procedural
- MySqli Object-Oriented
- PDO Connection
We need some information to connect database on local serve as
- Server name or IP Address – localhost or 127.0.0.1 is the server name
- username – root is the database username of the local database
- password– no password of the local database
- database name– custom database name of PHPMyAdmin
Now, I am going to share our types of database connection queries. you can use one of them according to your project.
1. MySQLi Procedural
This is a simple database connection query. If you are a learner and developing a small application then you can use it. It may be affected by SQL injection. So, It not secure.
2. MySQLi Object-Oriented
This is an advanced database connection query. Even it is more secure and protects the database from SQL injection. So. You should use this query to connect your project to the database.
connect_error) < die("Unable to Connect database: " . $conn->connect_error); ?>
3. MySQL PDO
PDO– It is a PHP extension that stands for PHP Data Object. It is lightweight and easy to make a database connection.
If you want to move your project to another database, then you can easily do that by changing the server, database information & name of the database language only.
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "database is Connected successfully"; > catch(PDOException $e) < echo "Unable to connect database: " . $e->getMessage(); > ?>
4. MySQLi OOPS
If you want to create a PHP MySQL connection by using the MySQLi OOPS Concept. You will write the MySQLi Query with OOPS Concept.
You have many options to create a database connection using OPPS Concept. But here, We have created only a single way.
hostname,$this->username,$this->password,$this->database); if(!$conn) < echo "database is not connected"; >> > $mysql= new Connection(); ?>
Database Connection File Inclusion
If you need to use your database connection on your other project files. you may include this file by using include() or require() method.
Suppose that, You write the PHP MySQL connection query in the file database.php . include it another file where you have to write PHP code with MySQL query.
My Suggestion
Dear Developers, If any questions are going in your mind related to PHP MySQL Connection. kindly, ask us without any hesitation through the comment box. I will definitely reply to your questions asap.
Related posts:
Hey there, Welcome to CodingStatus. My Name is Md Nurullah from Bihar, India. I’m a Software Engineer. I have been working in the Web Technology field for 4 years. Here, I blog about Web Development & Designing. Even I help developers to build the best Web Applications.