Mysql queries examples in php. SQL - queries and their processing with PHP

WORKING WITH A MySQL DATABASE WITH PHP

Lecture. Prepared by V.S. Prokhorov


1. CONNECTING PHP SCENARIOS TO MySQL tables

Let's consider the most frequently used functions that allow you to work with a MySQL database using PHP.

When PHP and MySQL interact, the program interacts with the DBMS through a set of functions.

1.1 Connecting to the server. Functionmysql_connect

Before working with the database, you need to install with it network connection, as well as to authorize the user. This is done using the mysql_connect () function.

resource mysql_connect (]])

This function establishes a network connection to the MySQL database located on the $ server host (by default, this is localhost, i.e. the current computer) and returns the identifier of the open connection. All further work is carried out with this identifier. All other functions that take this identifier (descriptor) as an argument will uniquely identify the selected database. When registering, the username $ username and password $ password are specified (by default, the username from which the current process is launched - when debugging scripts: root, and an empty password):

$ dbpasswd = ""; //Password

// Display a warning

echo ("

");

The variables $ dblocation, $ dbuser and $ dbpasswd store the server name, username and password.

1.2 Disconnecting from the server. Functionmysql_close

The connection to the MySQL server will be automatically closed when the script ends, or when the mysql_close function is called

bool mysql_close ()

This function breaks the connection to the MySQL server, and returns true if the operation is successful and false otherwise. The function takes as an argument a handle to the database connection returned by the mysql_connect function.

$ dblocation = "localhost"; // Server name

$ dbuser = "root"; //Username

$ dbpasswd = ""; //Password

// Connect to the database server

// Suppress error output with the @ symbol before calling the function

$ dbcnx = @ mysql_connect ($ dblocation, $ dbuser, $ dbpasswd);

if (! $ dbcnx) // If the descriptor is 0, the connection is not established

// Display a warning

echo ("

B currently the database server is not available, so the page cannot be displayed correctly.");

if (mysql_close ($ dbcnx)) // close the connection

echo ("Database connection terminated");

echo ("Unable to complete connection");

1.3 Creation of a database. CREATE DATABASE function

The command - create a database is available only to the server administrator, and on most hosting services it cannot be executed:

CREATE DATABASE DatabaseName

Creates a new database named DatabaseName.

An example of working with this function:

@mysql_query ("CREATE DATABASE $ dbname");

It is recommended to use apostrophes ("SQL - command") everywhere as delimiters for lines containing SQL - commands. This can ensure that no $ - variable is accidentally interpolated (i.e. not replaced with its value), and the safety of the scripts will increase.

The CREATE DATABASE database creation command is available only to the superuser, and on most hosting sites it is impossible for an ordinary user to execute it. It is available only to the server administrator.

For experimentation, let's create a testbase database by running an SQL query from the command line. To do this, you need to login to MySQL and type in command line MySQL:

mysql> create database testbase;

After that, you should type:

mysql> use testbase;

Database created:


1.4 Database selection. Functionmysql_select_db

Before sending the first query to the MySQL server, you need to specify which database we are going to work with. The mysql_select_db function is intended for this:

bool mysql_select_db (string $ database_name [, resource $ link_identifier])

It notifies PHP that further operations on the $ link_identifier connection will use the $ database_name database.

Using this function is equivalent to calling the use command in an SQL query, that is, the mysql_select_db function selects a database for further work, and all subsequent SQL queries are applied to the selected database. The function takes as arguments the name of the database to select, database_name, and the connection descriptor resource. The function returns true if the operation is successful and false otherwise:

// Database connection code

if (! @mysql_select_db ($ dbname, $ dbcnx))

// Display a warning

echo ("

The database is currently not available, so the page cannot be displayed correctly.");

1.5 Error handling

If in the process of working with MySQL errors occur (for example, the brackets are not balanced in the query or there are not enough parameters), then the error message and its number can be obtained using the following two functions.

It is important to use these functions carefully and in a timely manner, because otherwise it can be difficult to debug scripts.

● Function:

int mysql_errno ()

returns the number of the last logged error. The connection identifier $ link_identifier can be omitted if only one connection has been established during the script operation.

● Function:

string mysql_error ()

returns not a number, but a string containing the text of the error message. It is useful for debugging purposes. Usually mysql_error is used in conjunction with the or die () construct, for example:

@mysql_connect ("localhost", "user", "password")

or die ("Error while connecting to database:" .mysql_error ());

The @ operator, as usual, serves to suppress the standard warning that may occur in the event of an error.

V latest versions PHP warnings are not logged in MySQL functions by default.

1.6 Automating connection to MySQL. File (config.php)

Usually, there are several scripts on the site that need access to the same database.

It is recommended to highlight the code responsible for connecting to MySQL in separate file and then connect using the include function to necessary scripts.

It makes sense to put the functions for connecting, selecting and creating a database in the same file (config.php) where variables with the server name $ dblocation, username $ dbuser, password $ dbpasswd and database name $ dbname are declared:

Listing config.php:

//config.php code of the file containing the parameters for connecting to the server and selecting the database

// prints connection error messages to the browser

$ dblocation = "localhost"; // Server name

$ dbname = "insert database name" // Database name: created or already existing

$ dbuser = "root"; // Database username

$ dbpasswd = ""; //Password

// Connect to the database server

// Suppress error output with the @ symbol before calling the function

[email protected] _connect ($ dblocation, $ dbuser, $ dbpasswd);

if (! $ dbcnx) // If the handle is 0, the connection to the database server is not established

// Display a warning

echo ("

The database server is currently not available, so the page cannot be displayed correctly.

");

// Create database $ dbname - only superuser can do this

// If the database already exists, there will be a non-fatal error

@mysql_query ("CREATE DATABASE if not exists $ dbname ');

// Code for connecting to the database: we unambiguously select a newly created database or an existing database

// Suppress error output with the @ symbol before calling the function

if ( [email protected] _select_db ($ dbname, $ dbcnx)) // If descriptor is 0, no database connection established

// Display a warning

echo ("

The database is currently not available, so the page cannot be displayed correctly.

");

// Small helper function which prints the message

// about an error in case of a database query error

function puterror ($ message)

echo ("");


2. FULFILLMENT OF REQUESTS TO THE DATABASE

2.1 Creating a table. FunctionCREATE TABLE:

CREATE TABLE Table Name (FieldName type, FieldName type,)

This command creates a new table in the database with columns (fields) defined by their names (FieldName) and the specified types. After creating a table, you can add records to it, consisting of the fields listed in this command.

Listing test_11.php. The program that creates a new table in the database:

include "config.php"; // Connect to the server and select the database

mysql_query ("CREATE TABLE if not exists people

id INT AUTO_INCREMENT PRIMARY KEY,

or die ("MySQL error:" .mysql_error ());


This script creates a new people table with two fields. The first field is of type INT (integer) and the name is id. The second is the type TEXT (text string) and the name name.

If the table exists, or die () will fire.

The optional if not exists clause, if specified, tells the MySQL server not to generate an error message if a table with the specified name already exists in the database.

I remember the days when I didn't know what it was mysql and often searched the internet for such articles. But, for some reason, they were rarely found. Now I decided to post such that useful articles about mysql and php became one more. I will try to write everything in an accessible language.

getting started with mysql and php

So, first we need a local server in order to be able to run php scripts and connect to the database (hereinafter I will call the database, which means "database"). If you do not already have a local server, then you should first read Installation and Configuration localhost, and then start studying the database mysql and its DBMS (database management tool).

If you already have this server, then we do this. First, I want to introduce you to the DBMS PhpMyAdmin, it allows you to manage (add, delete, change) records in the database.

This is the home page PhpMyAdmin DBMS... From here you can create your own database and store the necessary records in it. This is very convenient when creating sites, since the information is structured and you can very quickly get any record from the database.

As already mentioned, the first part of the article, acquaintance with mysql and phpmyadmin... I think now you understand what mysql is and we can start exploring the functionality of phpmyadmin. To get started, we need to create the database itself (database). She will have her own name, by which we will then look for her.

Here is the general structure of the structure of the database:

In order to create a database, enter any name (not Cyrillic!) For the future database in the input field under the line "Create a new database" (on the main page of PhpMyAdmin). I will create a database named "baza". Now, following the schema of the structure of the database, we need to make a table. To do this, after creating the base, you will have a window like this:

Here I am creating a table named users and 3 fields in it. Next phpmyadmin will ask us to define a structure for each field:

Here in the “Field” column you need to specify the name, in the “Type” we indicate the type of data that will be stored there (INT is a number, VARCHAR is a string or small (!) Text). In the "Additional" field, we indicate the "id" parameter to the "id" field, which means that it will increase every time any data is inserted, and set the "Primary key" parameter to it (put a round), this means that the first column, we can uniquely identify the field.

“Unambiguously identify the field” - it means that even if the first and last names are the same, the “id” column will have different values ​​(since it is automatically incremented by one each time).

Now click "Save". Thus, we have created the users table, in which we can store the first and last name (id does not need to be inserted, mysql will do everything for us), in the users database. We created the table to store records. And how to insert them there? Read below 😉

Select the "Insert" menu and write the required values ​​in the required fields. Now how to delete or change values ​​in a mysql database with PhpMyAdmin ... To delete, simply go to the Browse menu and click the red cross next to the entry:

And to edit, click on the pencil and replace the required fields. Well, this lesson is over. You can now manage your mysql database using PhpMyAdmin. In the next lesson, I will teach you how to store, receive, delete and update data in the database. using php... It is very convenient and practical.

Working with mysql database from php

So, first you need to learn how to connect to an already known database. For this, the following code is used:

In the above code, I connected to the localhost server using login root which does not require a password (therefore, we do not specify it). After connecting to the database, we can carry out all those operations that were performed in the phpmyadmin DBMS. That is, the insertion, deletion, modification and retrieval of various information. Now, point by point:

Inserting records into SQL database in php

$ query = "INSERT INTO` table` (`specify a field`,` specify a field`) VALUES ("any value", "any value") "; $ result = mysql_query ($ query); if ($ result == true) (echo "Success!";) else (echo "Error!
".mysql_error ();)

That is, the insertion is done with the INSERT function. If everything went well, then mysql will return true, otherwise - false.

You can specify at least how many fields, the main thing is that they all exist in the database. That is, for example, there is a table in which there are fields "name", "surname" and "city". To insert values ​​into it, we will use the following code:

$ query = "INSERT INTO` users` (`name`,` surname`, `city`) VALUES (" Ruslan "," Huzin "," Kokshetau ")"; $ result = mysql_query ($ query); if ($ result == true) (echo "Success!";) else (echo "Error!
".mysql_error ();)

Deleting records from SQL database in php

Deletion is performed by the DELETE function. To do this, there will be something like this code:

$ query = "DELETE FROM` users` WHERE `name` =" Ruslan ""; $ result = mysql_query ($ query); if ($ result == true) (echo "Success!";) else (echo "Error!
".mysql_error ();)

That is, we will delete all rows from the users table (well, or one), where the name column is equal to the Ruslan value.

Changing values ​​in MySQL database in php

We can also make changes to existing records in the table. For example, we want to replace the value of the name column in the row where the surname column is Huzin. To do this, execute the following code:

$ query = "UPDATE` users` SET `name` =" myname "WHERE` surname` = "Huzin" "; $ result = mysql_query ($ query); if ($ result == true) (echo "Success!";) else (echo "Error!
".mysql_error ();)

Retrieving values ​​from the database

Now comes the fun part. Since we recorded something, shouldn't we get it back? For example, we need to get the entire row from the users table where the name column is equal to Ruslan. To do this, we need a slightly different code than in the first examples. Here is he actually:

$ query = "SELECT * FROM WHERE` name` = "Ruslan" "; $ result = mysql_query ($ query); if ($ result == true) (echo "Success!";) else (echo "Error!
".mysql_error ();) $ data = mysql_fetch_array ($ result); / * Now the variable stores data from the table * /

Here we needed one more function to write the selected data to a variable (array) in php. In order to refer to the selected line, we write like this:

$ data ["column name"]

that is, to get the surname from the selected line (where the name was Ruslan), we must write to the output:

echo $ data ["surname"];

And when selecting from a table, they wrote SELECT *, this asterisk means that you need to select all columns from the row. If we need, for example, to select only surname, we write SELECT `surname`. And to select several rows from the table at once, you will also need a loop to display them. This is if, for example, there will be several rows with the Ruslan column. Here is the code:

$ query = "SELECT * FROM WHERE` name` = "Ruslan" "; $ result = mysql_query ($ query); while ($ data = mysql_fetch_array ($ result)) (echo $ data ["name"]. "
". $ data [" surname "]."


"; }

Now all rows for which the name column is equal to the Ruslan value will be displayed.

Now you have met the basic control functions. mysql database directly from php script.

In this article we will learn send database queries via PHP... This article is very important and must be understood by you. However, I will reassure you - the material is very simple, so there should be no difficulties.

Before moving on to the topic of the article, I warn you in advance that I will not analyze in detail SQL language... All the necessary information is sorted out in the category dedicated, and here we are only working with MySQL via PHP.

Now let's move on to sending database queries in PHP:


}
$ mysqli-> query ("INSERT INTO mytable (name, email) VALUES (" MyName "," [email protected]")");
$ mysqli-> close ();
?>

In this example, we connected to the database, checked the connection was successful, and sent a request using the method query () and then closed the connection. As you can see, everything is very simple. To send any SQL queries just one method is enough - query (), so in this case everything is insanely simple.

Now let's complicate the task a little. Let's analyze with you the requests that return result_set- result. The most popular query returning result_set is a selection of data from a table. In the following example, we will make a selection of data with you, and then display the result:

$ mysqli = @new mysqli ("localhost", "Admin", "pass", "mybase");
if (mysqli_connect_errno ()) (
echo "Unable to connect:" .mysqli_connect_error ();
}
$ result_set = $ mysqli->
while ($ row = $ result_set-> fetch_assoc ()) (
print_r ($ row);
echo "
";
}
$ result_set-> close ();
$ mysqli-> close ();
?>

To begin with, I will explain a little what it is. result_set. Result_set is a table with the result. This table has a set of records (table rows). And to display all records, you need to iterate over each row of the table and display it. And now I will explain an example: after sending a request, we have formed result_set... Then, in a loop, we assign to the variable row the value of the next row, that is, a one-dimensional array that the method returns fetch_assoc ()... When all lines run out, the method fetch_assoc () will return false, and the loop will be exited. Inside the loop while we just output the array using the debug function print_r () although it certainly could have been inferred using foreach but this is not needed now.

Let's briefly summarize how to work with result_set:

  1. Receive result_set by sending an appropriate query to the database.
  2. In the loop, at each iteration, assign the next line (record) from result_set using method fetch_assoc () some variable row... Then you can work with this variable as with a one-dimensional associative array, in which the keys are the names of the fields in the table, and the values ​​correspond to the current record.
  3. Be sure to close result_set method close () to master resources.

As you can see, the method fetch_assoc () always returns the next record. That is, first the 1st, then the 2nd, then the 3rd, and so on. If you have some good programming experience, then you will immediately guess that this is due to the internal pointer, which you, of course, can move. Where is it used? For example, this can be used when you need to work with result_set not 1 , a 2 and more times. In order not to form the same request again, you can simply move the pointer to the beginning. And then you can brute force again result_set using the fetch_assoc () method.

To change the position of the pointer, there is a method data_seek () which takes an integer from 0 before " number of records - 1", respectively, the pointer goes to the entry corresponding to the parameter:

$ mysqli = @new mysqli ("localhost", "Admin", "pass", "mybase");
if (mysqli_connect_errno ()) (
echo "Unable to connect:" .mysqli_connect_error ();
}
$ result_set = $ mysqli-> query ("SELECT * FROM mytable");
$ result_set-> num_rows;
while ($ row = $ result_set-> fetch_assoc ()) (
print_r ($ row);
echo "
";
}
$ result_set-> data_seek (0);
while ($ row = $ result_set-> fetch_assoc ()) (
print_r ($ row);
echo "
";
}
$ result_set-> close ();
$ mysqli-> close ();
?>

In this example, we have deduced number of records in result_set using the property num_rows... And also got acquainted with the method data_seek ()... That is, we iterated over the entire result, then returned a pointer to 0th record and iterate over the result again.

In this article, we repeated connecting to the database and closing the connection. And also learned how to send database queries via PHP... Learned, how to get result_set and how to work with it. That's all you need to know to be successful. working with MySQL in PHP.

In order to get the most out of your MySQL database, it is important to understand how to connect from a custom PHP program to a MySQL database.

This tutorial describes the following three methods, along with a corresponding PHP sample program that explains how to connect using PHP to a database.

  • Connecting with Mysqli Extension (Recommended)
  • PDO Connection (Recommended)
  • Connecting using legacy mysql_ traditional functions (deprecated)

To do this, you need to install the PHP-MySQL package.

Based on RedHat distribution including, use yum to install PHP-MySQL as shown below.

Yum install php-mysql

Depending on your system, we will install or update the following dependencies above:

  • php-cli
  • php-common
  • php-pdo
  • php-pgsql

Once everything is installed, the phpinfo page will display the MySQL module as shown below:

For all the examples below, we will be connecting to a MySQL database that already exists. If you're new to MySQL, this is a good place to start:.

Note: Everything described here will also work with MariaDB as it does with MySQL.

1. Connection in PHP using the Mysqli extension

MySQLi stands for MySQL Improved.

Please note that on most distributions (ex: CentOS), PHP-MySQLi is already part of the PHP-MySQL package. This way you don't have to search and install the PHP-MySQLi package. All you need to do is install the PHP-MySQL package to get the Mysqli extension working on your system.

Create the following mysqli.php file in DocumentRoot in Apache:

connect_error) (die ("Error: unable to connect:". $ conn-> connect_error);) echo "Connecting to the database.
"; $ result = $ conn-> query (" SELECT name FROM employee "); echo" Number of rows: $ result-> num_rows "; $ result-> close (); $ conn-> close ();?>

In the above:

  • MySQLi - This function will initiate a new connection using the Mysqli extension. This function will take four arguments:
    1. Hostname where MySQL database is running
    2. MySQL connection username
    3. Password for mysql user
    4. MySQL database to connect.
  • Query Function - Use this to specify your MySQL query. In this example, we select the name column from the employee database.
  • Finally, we display the number of rows selected using the num_rows variable. We also close the connection as shown above.

Database connection. Number of rows: 4

Note: If you are trying to connect to a remote MySQL database, then you can do so to avoid the host connection denied error: How to allow a MySQL client to connect to a remote MySQL server.

2. Connecting using PHP to MySQL with the PDO extension

PDO stands for PHP Data Objects.

PDO_MYSQL implements the PDO interface provided by PHP for connecting a program to a MySQL database.

On most Linux distributions (eg CentOS and RedHat), the PHP-PDO package is already included in the PHP-MySQL package. This way, you don't have to search and install the PHP-PDO package. All you need to do is install the PHP-MySQL package to get the PDO_MYSQL PHP extension working on your system.

Create the following MySQL-pdo.php file in your Apache DocumentRoot:

setAttribute (PDO :: ATTR_ERRMODE, PDO :: ERRMODE_EXCEPTION); echo "Connecting to database.
"; $ sql =" SELECT name FROM employee "; print" Employee Name:
"; foreach ($ conn-> query ($ sql) as $ row) (print $ row [" name "]."
";) $ conn = null;) catch (PDOException $ err) (echo" Error: unable to connect: ". $ err-> getMessage ();)?>

In the above:

  • new PDO - Creates a new PDO object that will take the following three arguments:
    1. MySQL connection string: will be in the format “mysql: host = $ hostname; dbname = $ dbname”. In the above example, the DB is running on localhost and we are connecting to the grayex database.
    2. Username to connect to MySQL.
    3. The password for the mysql user.
  • $ sql variable - Create the SQL query you want to execute. In this example, we select the name column from the employee table.
  • query ($ sql) - here we are executing the SQL query we just created.
  • foreach - here we go through the above commands and store them in the $ variable string, and then we display them using the print command.
  • In MySQL PDO, to close a connection, simply set the $ conn variable to zero.

When you call mysqli.php from your browser, you will see the following output, which indicates that PHP was able to connect to the MySQL database and fetch the data.

Database connection. Employee Name: slan Maria Oleg website

3. PHP connection using mysql_ functions (deprecated)

Use this method only if you are using an older version of PHP and cannot upgrade to a newer version for some reason.

This is a deprecated extension of PHP 5.5 version. But starting from PHP 7.0 version, this will not work as it has been removed.

As of PHP 5.5, when you use these functions, they will generate an E_DEPRECATED error.

Create the following MySQL-legacy.php file under Apache DocumentRoot:

"; $ result = mysql_query (" SELECT name FROM employee "); $ row = mysql_fetch_row ($ result); echo" Employee 1: ", $ row,"
\ n "; mysql_close ($ conn);?>

In the above:

  • The mysql_connect function takes three arguments: 1) the hostname where the MySQL database is running, 2) The username for connecting to MySQL, 3) The password for the MySQL user. Here we connect to the MySQL database running on the local server using the root username and password.
  • Mysql_select_db function - As the name suggests, will select the database you want to connect to. This is equivalent to the "use" command. In this example, we are connecting to the andreyex database.
  • Mysql_query function - Use this to specify your MySQL query. In this example, we select the name column from the employee database.
  • mysql_fetch_row - Use this function to fetch rows from the SQL query we just created.
  • Finally close the connection using mysql_close command as shown above.

When you call MySQL-legacy.php from your browser, you will see the following output, which indicates that PHP was able to connect to the MySQL database and fetch the data.

Database connection. Employee 1: AndreyEx

With php ...

Creating a connection in different ways:

1) the old old-fashioned way of connecting to MySQL:

$ conn = mysql_connect ($ db_hostname, $ db_username, $ db_password) or die ("No connection to server");
mysql_select_db ($ db_database, $ conn) or die ("Failed to connect to the database");

The explanations for the variables are below.

In this case, the following functions are used:

  • mysql_connect ()- to connect to the server;
  • mysql_select_db ()- to connect to the database;

At the same time, we constantly check for errors in this way: or die ("Such a mistake"); - translated as or die with such and such an error - to immediately find where the error is.

config.php

// variables for connecting to the database
$ host = "localhost"; / host
$ username = "root"; // password for connecting to the database
$ password = ""; // password for connecting to the database - on the local computer it can be empty.
$ database_name = "my-dolgi"; // database name

// old way of connecting to the database
mysql_connect ($ host, $ username, $ password) or die ("Can't connect to create a connection");

// select the database. If there is an error, print
mysql_select_db ($ database_name) or die (mysql_error ());

index.php

require_once "config.php";


$ result = mysql_query ("SELECT Name, Money FROM Dolg ORDER BY Money DESC LIMIT 5") or die (mysql_error ());



";


while ($ row = mysql_fetch_assoc ($ result)) (
";
}


mysql_free_result ($ result);

// Close the connection
mysql_close ();

2) More progressive procedural style - database connection using mysqli:

This way:

  1. more convenient;
  2. up to 40 times faster;
  3. increased security;
  4. there are new features and functions;

An example of connecting to a database in php with a selection from a table

config.php

// connect to database
$ link = mysqli_connect ("localhost", "username", "password", "name-database"); // here we enter your direct data: username, password and database name, the first field is usually localhost

// display connection error
if (! $ link) (
echo "Error connecting to database. Error code:". mysqli_connect_error ();
exit;
}

Pay attention - mysqli is used everywhere, not mysql !!!

index.php

require_once "config.php";

// Execute the request. If there is an error, we output
if ($ result = mysqli_query($ link,"SELECT Name, Money FROM Dolg ORDER BY Money DESC LIMIT 5")) (

Echo "Who Should I Descending:

";

// Fetching query results
while ($ row = mysqli_fetch_assoc($ result)) (
echo $ row ["Name"]. "with debt". $ row ["Money"]. "rubles.
";
}

// free used memory
mysqli_free_result($ result);

// Close the connection
mysqli_close($ link);
}

As you can see, some points have changed (in italics).

3) Object-oriented method of connecting to the MySQL database - using methods and classes:

Cons: Harder and less susceptible to errors.

Pros: brevity and convenience for experienced programmers.

$ conn = new mysqli ($ db_hostname, $ db_username, $ db_password, $ db_database);
if ($ conn-> connect_errno) (
die ($ conn-> connect_error);
) else (echo "Database connection successfully established";)

here, in principle, everything is intuitively clear:

  • $ db_hostname is host(mostly localhost),
  • $ db_database - DB name;
  • $ db_username and $ db_password are username and password respectively!

An example of connecting to a database in php OOP style with a selection from a table

config.php

// connect to database
$ mysqli = new mysqli ("localhost", "username", "password", "name-database"); // here we enter your direct data: username, password and database name, the first field is usually localhost

// display connection error
if ($ mysqli-> connect_error) (
die ("Error connecting to the database: (". $ mysqli-> connect_errno. ")". mysqli_connect_error);
}

Please note that mysqli is used everywhere, not mysql !!! and unlike the previous method, "->" arrows appear to indicate that this is an OOP style.

index.php

require_once "config.php";

// Execute the request. If there is an error, we output
if ($ result = $ mysqli-> query("SELECT Name, Money FROM Dolg ORDER BY Money DESC LIMIT 5")) (

Echo "Who Should I Descending:

";

// Fetching query results
while ($ row = $ result-> fetch_assoc()) {
echo $ row ["Name"]. "with debt". $ row ["Money"]. "rubles.
";
}

// free used memory
$result-> close ();

// Close the connection
$mysqli-> close();
}

Your task is to find the differences.

4) Communication with the database using PDO:

When connecting to a MySQL database, prepared statements are used (by the prepare method) and as a result, it is more secure and greatly increases performance.

config file from the previous method! - same

index.php

// PDO style for MySQL communication
if ($ stmt = $ mysqli-> prepare ("SELECT Name, Voney FROM Dolg ORDER BY Money< ? LIMIT 5")) {

$ stmt-> bind_param ("i", $ summa);
$ summa = 100000;

// start execution
$ stmt-> execute ();

// Declaring variables for prepared values
$ stmt-> bind_result ($ col1, $ col2);

Echo "Who Should I Descending:

";

// Fetching query results
while ($ stmt-> fetch ()) (
echo $ col1. "with debt". $ col2. "rubles.
";
}

// free used memory
$ stmt-> close ();

// Close the connection
$ mysqli-> close ();

As you can see, it is much more difficult here and it is necessary to study PDO - this is a separate topic.