Hardware and software setup

MySQL getting started and importing data. PHP language and working with MySQL database Mysql training

MySQL is one type of relational database. MySQL is a server to which different users can connect.

When you connect to the Internet, do you enter your login and password, as well as the name of the server you are connecting to? When working with MySQL, the same system is used.

One more point: what is a relational database? Relational means table-based. The famous electronic editor Excel tables from Microsoft is actually a relational database editor.

Connecting to a MySQL server

PHP uses the mysqli_connect() function to connect to a MySQL server. This function takes three arguments: server name, username, and password.

The mysqli_connect() function returns a connection ID, which is stored in a variable and then used to work with databases.

MySQL server connection code:

$link = mysqli_connect("localhost", "root", "");

In this case, I'm working on local computer on Denwere, so the hostname is localhost, the name root user and no password.

The connection also needs to be closed when MySQL is finished. The mysqli_close() function is used to close the connection. Expanding the example:

$link = mysqli_connect("localhost", "root", ""); if (!$link) die("Error"); mysqli_close($link);

Here we checked the connection identifier for truth, if something is wrong with our connection, then the program will not be executed, the die () function will stop its execution and display an error message in the browser.

Connection errors

The following functions are used to check the connection:

  • mysqli_connect_errno() - Returns the error code of the last connection attempt. Returns zero if there are no errors.
  • mysqli_connect_error() - Returns a description of the last error connecting to the MySQL server.
define("HOST", "localhost"); define("DB_USER", "root"); define("DB_PASSWORD", ""); define("DB", "tester"); $link = mysqli_connect(HOST, DB_USER, DB_PASSWORD, DB); /* check connection */ if (mysqli_connect_errno()) ( printf("Failed to connect: %s\n", mysqli_connect_error()); exit(); ) else ( printf("Connected successfully: %s\n", mysqli_get_host_info($link)); )

The mysqli_get_host_info() function returns a string containing the type of connection being used.

Also note that using the define command, I saved all connection parameters in constants. When will you write big projects, and there will be many files connecting to the MySQL server, it is convenient to store the connection parameters in separate file and insert it using the include or require function.

Database selection

A MySQL server can have multiple databases. First of all, we need to select the base we need to work with. In PHP, there is one more parameter for this in the mysqli_connect() function - the name of the database.

I created on my computer via phpMyAdmin named tester. We connect to it:

$link = mysqli_connect("localhost", "root", "", "tester"); if (!$link) die("Error"); mysql_close($link);

So, we have chosen a database to work with. But as we know, a relational database consists of tables, and our database does not yet have tables. The database is created empty, without tables. Tables must be added to it separately. Let's add a table to it using PHP.

Create a table

In the name of the MySQL databases, the SQL part stands for Structured Query Language, which translates as a structured query language. In the SQL language, we will write queries and send them from the PHP program to the MySQL server.

To create a table, we just need to issue the CREATE TABLE command. Let's create a table called users whose columns will store logins (login column) and passwords (password column) of users.

$query = "CREATE TABLE users(login VARCHAR(20), password VARCHAR(20))";

In this code, we have assigned a string of text to the $query variable, which is an SQL query. We create a table named users which contains two columns login and password, both of data type VARCHAR(20). We will talk about data types later, for now I will only note that VARCHAR (20) is a string with a maximum length of 20 characters.

To send our query to the MySQL server we use PHP function mysqli_query() . This function returns a positive number if the operation was successful and false if an error occurred (the syntax of the request is invalid or the program does not have permission to execute the request).

$link = mysqli_connect("localhost", "root", "", "tester"); if (!$link) die("Error"); $query = "CREATE TABLE users(login VARCHAR(20), password VARCHAR(20))"; mysqli_query($query); mysqli_close($link);

The SQL query does not have to be written to a variable, it can be immediately written as an argument to the mysql_query() function. It just makes the code more readable.

This script has one drawback - it does not output anything to the browser. Let's add a message:

$link = mysqli_connect("localhost", "root", "", "tester"); if (!$link) die("Error"); $query = "CREATE TABLE users(login VARCHAR(20), password VARCHAR(20))"; if (mysqli_query($query)) echo "The table has been created."; else echo "Table not created."; mysqli_close($link);

If we re-run this script for execution, we will see a message in the browser: "The table has not been created." The fact is that the table was created at the first start, and it is impossible to create a table with the same name again. We are faced with an error situation, so it's time to talk about error handling when working with MySQL.

Error processing

When debugging a program, we may need precise information about the error. When an error occurs in MySQL, the database server sets the error number and a line describing the error. PHP has special functions to access this data.

  • mysqli_errno() - returns the error number.
  • mysqli_error() - returns a string describing the error.

Now let's add the mysql_error() function to our script:

$link = mysql_connect("localhost", "root", "", "tester"); if (!$link) die("Error"); $query = "CREATE TABLE users(login VARCHAR(20), password VARCHAR(20))"; if (mysqli_query($query)) echo "The table has been created."; else echo "Table not created: ".mysqli_error(); mysqli_close($link);

Now our script will return the string to the browser: "Table not created: Table "users" already exists".

Deleting a table

So, we now have a table that we do not need. It's time to learn how to delete tables from the database.

To drop a table, use the DROP TABLE command followed by the table name.

$link = mysqli_connect("localhost", "root", "", "tester"); if (!$link) die("Error"); $query = "DROP TABLE users"; if (!mysqli_query($query)) echo "Error dropping table: ".mysqli_error(); else echo "Table deleted."; mysqli_close($link);

Results

So we have mastered MySQL basics. What we have learned to do:

  • Connect to a MySQL database using the mysqli_connect() function.
  • Close the connection to the MySQL server using the mysqli_close() function.
  • Send SQL queries to the MySQL server using the mysqli_query() function.
  • We have learned the SQL query to create a table: create table.
  • We have learned the SQL query for dropping a table: drop table.
  • We have learned how to handle errors using the mysqli_errno() and mysqli_error() functions.

Then we'll take a closer look at MySQL data types.

Read the following lesson:

In MySQL, getting started is primarily authorization, creating a database and tables, and filling tables with data. Initially, information can be added by making queries to the database server or, for example, by importing data from text documents. This is how data will be loaded from documents into tables REAL_ESTATE and PEOPLE.

This material is a continuation.

MySQL getting started and importing data

mysql -h host -u user -p

Enter password: **********

You can also enter the password directly

mysql -h host -u user -pPASSWORD

There must not be a space between the -p switch and the password itself, otherwise the password will be perceived as the name of the database. This option is bad because the password will remain in history and can be viewed in the future.

MySQL Basics

Any request (except USE, QUIT and a few more) must end with a semicolon. The query can be spread over several lines and will be executed only after the introduction of a semicolon

SELECT
-> *
-> FROM
-> gebwoocommerce_api_keys
-> ;
Empty set (0.01 sec)

MariaDB >

You can refuse to execute the query after entering the introduction of several lines by executing \c

SELECT
-> *
-> FROM
-> gebwoocommerce_api_keys
-> \c

By the way the MySQL prompt looks like, you can understand the status of the query and what exactly the server expects from the administrator

(or variations: mysql > , MariaDB > ) Input pending

2) ->

The next query string is expected to be multiple lines long

3) ">

Expect the next query string to be several lines long if the query started with a single quote

4) «>

Expect the next query string to be several lines long if the query started with a double quote

Expect the next query string to be several lines long if the query started with a backtick (“`”)
6) /*>

Expect the next query string to be several lines long if the query starts with a comment sign /*

Creating a MySQL database and populating it with data

Running as root is not desirable, the best solution is

For example, let's add the user user (in the test environment, you can also work as root). After logging in to the MySQL console, create a database and tables

CREATE DATABASE REAL_ESTATE_AGENCY;

Query OK, 1 row affected (0.00 sec)

+——————————+
| database |
+——————————+
| information_schema |
| mysql |
| performance_schema |
| REAL_ESTATE_AGENCY |
+——————————+
4 rows in set (0.03 sec)

database change

CREATE TABLE REAL_ESTATE (type VARCHAR(20), city VARCHAR(20), floorspace INT, district VARCHAR(20), street VARCHAR(20), rentorsale VARCHAR(20), PRICE VARCHAR(20));

CREATE TABLE PEOPLE (name VARCHAR(20), profession VARCHAR(20), age INT, city VARCHAR(20), district VARCHAR(20), rentorsale VARCHAR(20), PRICE VARCHAR(20));

Query OK, 0 rows affected (0.01 sec)

+——————————+
| tables_in_REAL_ESTATE_AGENCY |
+——————————+
| PEOPLE |
| REAL_ESTATE |
+——————————+
2 rows in set (0.00 sec)

Information about the table structure and all existing columns and columns can be obtained by issuing the DESCRIBE command

+————+————-+——+——+———+——-+
| field | type | Null | key | default | extra |
+————+————-+——+——+———+——-+
| type | varchar(20) | YES | | NULL | |
| city ​​| varchar(20) | YES | | NULL | |
| floor space | int(11) | YES | | NULL | |
| district | varchar(20) | YES | | NULL | |
| street | varchar(20) | YES | | NULL | |,

| rentorsale | varchar(20) | YES | | NULL | |
| PRICE | varchar(20) | YES | | NULL | |
+————+————-+——+——+———+——-+
7 rows in set (0.00 sec)

You can display the entire contents of the table using the most general SELECT query (this type of query is used most often and will be discussed in detail later)

SELECT * FROM REAL_ESTATE;

Empty set (0.00 sec)

There is no data now - let's fill the tables. You can do this by performing UPDATEs with the necessary values ​​or by loading data from text documents. At the initial boot stage, the second method is much more convenient. Let's use it.

Loading data into MySQL tables

We save the information in /tmp/real_estate.txt - we separate the values ​​​​in the columns with tabs. After that, in the console, we load the data by first selecting the table.

The following error may occur.

ERROR 1148 (42000): The used command is not allowed with this MySQL version

If an error occurs to MySQL, you need to connect with the option --local-infile=1:

mysql --local-infile=1 -u root -p

LOAD DATA LOCAL INFILE "/tmp/real_estate.txt" INTO TABLE REAL_ESTATE;

Query OK, 13 rows affected (0.00 sec)
Records: 13 Deleted: 0 Skipped: 0 Warnings: 0

SELECT results now look different:

SELECT * FROM REAL_ESTATE;


If a column or row needs a NULL value in text document it must be represented as \N. In MySQL, getting started with databases and tables looks like this. Next, let's look at the basics of using .

MySQL 8. Designing and creating databases

MySQL is one of the popular relational database servers. Used on a huge number of sites and content management systems (CMS). Wordpress, Joomla, Drupal, Bitrix and other CMS can and do work with MySQL DBMS. The most popular PHP frameworks can work with MySQL: Laravel, Symfony, yii and others. To use MySQL effectively, you need to know its tools, capabilities, and features.

On course "MySQL 8. Designing and creating databases for the web" you will master the basic techniques and methods effective work with MySQL server 8. In the course of training, you will consider the stages of designing and creating databases, study SQL statements in detail, learn how to manage transactions on the MySQL server. You will be able to create stored procedures and triggers, learn how to effectively use the storage ("engines") of the MySQL server. This course is essential for any website developer.

The course is intended for web developers and webmasters who plan to use the MySQL server in their practice. The course will be of particular interest to professionals using PHP and Perl.

By the end of the course, you will have accumulated a large amount of SQL queries that you can use in your projects in the future, create a database for the selected project. Each module contains a large number of practical tasks and ends with a test to consolidate knowledge. All course participants are given homework assignments.

The course program meets the requirements of the professional standard "Programmer". After successful completion of the course, a prestigious certificate of the center of advanced training is issued.

Teachers and mentors who teach MySQL can offer their own options for organizing the sequence of learning MySQL in the comments to this section textbook. Also, readers who lead independent study MySQL. For self-learning MySQL to be effective, it is necessary to draw on the methodological experience that learning MySQL provides. The primer should help quick start developer.

Databases: basic concepts

Document table of contents

In life, we often face the need to store any information, and therefore we often deal with databases.

For example, we use notebook to store the phone numbers of your friends and plan your time. The phone book contains information about people living in the same city. All this is a kind of database. Well, since these are databases, let's see how data is stored in them. For example, the phone book is a table (Table 10.1).

In this table, the data is actually phone numbers, addresses and full names, i.e. the lines "Ivanov Ivan Ivanovich", "32-43-12", etc., and the names of the columns of this table, i.e. the lines "Full name", "Phone number" and "Address" define the meaning of this data, their semantics.

Table 10.1. Database example: phonebook

Now imagine that there are not two, but two thousand records in this table, you are creating this directory and an error has occurred somewhere (for example, a typo in the address). Apparently, it will be difficult to find and fix this error manually. You need to use some kind of automation. For management large quantity data programmers (not without the help of mathematicians) came up with database management systems (DBMS). Compared with text databases, electronic DBMSs have a huge number of advantages, from the ability to quickly search for information, the relationship of data among themselves to the use of these data in various application programs ah and simultaneous access to the data of several users.

For accuracy, let's give the definition of a database offered by Glossary.ru

A database is a collection of related data organized according to certain rules that provide general principles description, storage and manipulation, independent of application programs. The database is information model subject area. Databases are accessed using a database management system (DBMS). The DBMS provides support for the creation of databases, centralized management and organization of access to them by various users.

So, we came to the conclusion that it is advisable to store data independently of programs, so that they are interconnected and organized according to certain rules. But the question of how to store data, according to what rules they should be organized, remained open. There are many ways (by the way, they are called presentation or data storage models). The most popular are object and relational data models.

Author relational model E. Codd is considered to be the first to propose using the apparatus of set theory for data processing (union, intersection, difference, Cartesian product) and showed that any data representation is reduced to a set of two-dimensional tables of a special type, known in mathematics as a relation.

Thus, a relational database is a set of tables (exactly the same as the one above) linked together. A row in the table corresponds to a real-world entity (in the example above, this is information about a person).

Examples relational DBMS: MySQL, PostgreSQL. The basis object model the concept of object-oriented programming was laid, in which data is represented as a set of objects and classes related to each other, and work with objects is carried out using hidden (encapsulated) in them
methods.

Examples of object DBMS: Cache, GemStone (by Servio Corporation), ONTOS (ONTOS).

Recently, DBMS vendors have been striving to combine these two approaches and advocate an object-relational data presentation model. Examples of such DBMS are IBM DB2 for Common Servers, Oracle8.

Since we are going to work with Mysql, we will only discuss aspects of working with relational databases. We still have to consider two more important concepts from this area: keys and indexing, after which we can start learning the language SQL queries.

1. Keys

To begin with, let's think about the following question: what information should be given about a person so that the interlocutor can say for sure that this is exactly the person, there can be no doubt, there is no second such? Reporting a surname is obviously not enough, since there are namesakes. If the interlocutor is a person, then we can approximately explain who we are talking about, for example, remember the act that that person committed, or in some other way. The computer, however, will not understand such an explanation; it needs clear rules on how to determine who it is. In database management systems, to solve such a problem, the concept of a primary key was introduced.

The primary key (PK) is the minimum set of fields that uniquely identifies a record in a table. This means that the primary key is primarily a set of table fields, secondly, each set of values ​​​​of these fields must define a single record (row) in the table, and, thirdly, this set of fields must be the minimum of all those having the same property.

Because a primary key defines only one unique record, no two records in a table can have the same primary key value.

For example, in our table (see above), the full name and address make it possible to unambiguously select a record about a person. Speaking in general, without connection with the problem being solved, then such knowledge does not allow us to accurately point to a single person, since there are namesakes living in different cities at one address. It's all about the boundaries we set for ourselves. If we believe that knowing the full name, phone number and address without specifying the city is enough for our purposes, then everything is fine, then the full name and address fields can form a primary key. In any case, the problem of creating a primary key falls on the shoulders of the one who designs the database (designs the data storage structure). The solution to this problem can be either the selection of characteristics that naturally define a record in the table (setting the so-called logical, or natural, PK), or the creation of an additional field designed specifically for uniquely identifying records in the table (setting the so-called surrogate, or artificial, P.K.).

An example of a logical primary key is a passport number in a database of residents' passport data, or a full name and address in phone book(table above). To set a surrogate primary key, we can add an id (identifier) ​​field to our table, the value of which will be an integer that is unique for each table row. The use of such surrogate keys makes sense if the natural primary key is a large set of fields or its extraction is not trivial.

In addition to uniquely identifying a record, primary keys are used to organize relationships with other tables.

For example, we have three tables: one containing information about historical figures (Persons), one containing information about their inventions (Artifacts), and one containing images of both persons and artifacts (Images) (Figure 10.1).

The primary key in all these tables is the id (identifier) ​​field. The Artifacts table has an author field that records the identifier assigned to the author of the invention in the Persons table. Each value of this field is a foreign key to the primary key of the Persons table. In addition, the Persons and Artifacts tables have a photo field that refers to an image in the Images table. These fields are also foreign keys to the primary key of the Images table and establish a one-to-one logical relationship between Persons-Images and Artifacts-Images. That is, if the value of the foreign key photo in the person table is 10, then this person's photo has id=10 in the image table. In this way, foreign keys are used to organize relationships between database tables (parent and child) and to maintain data referential integrity constraints.

2. Indexing

One of the main tasks that arise when working with databases is the task of searching. At the same time, since, as a rule, there is a lot of information in the database, programmers are faced with the task of not just searching, but effective searching, i.e. search in a relatively short time and with sufficient accuracy.

To do this (to optimize query performance), some table fields are indexed. Using indexes is useful for quickly finding rows with a given single column value. Without an index, the table is read over the entire table, starting with the first entry, until matching rows are found. The larger the table, the greater the overhead. If the table contains an index on the columns in question, then the database can quickly locate a search position in the middle of the data file without going through all the data. This is because the database places the indexed fields closer in memory so that their values ​​can be found more quickly. For a table containing 1000 rows, this will be at least 100 times faster than iterating through all the records. However, in the case where almost all 1000 rows need to be accessed, sequential reads will be faster because no disk seeks are required. So sometimes indexes are just a hindrance. For example, if a large amount of data is being copied into a table, then it is better not to have any indexes. However, in some cases it is necessary to use several indexes at once (for example, to process queries on frequently used tables).

If we talk about Mysql, then there are three types of indexes: PRIMARY, UNIQUE, and INDEX, and the word key (KEY) is used as a synonym for the word index (INDEX). All indexes are stored in memory as B-trees.

PRIMARY- unique index(key) with the restriction that all fields indexed by it cannot have empty value(i.e. they are NOT NULL). A table can only have one primary index, but it can have multiple fields.

UNIQUE is a key (index) that defines fields that can only have unique values.

INDEX is a regular index (as we described above). In Mysql, it is also possible to index string fields by a given number of characters from the beginning of the string.

3. Mysql DBMS

Let's continue talking about the Mysql DBMS. mysql is relational system database management. That is, the data in its databases are stored in the form of logically interconnected tables, which are accessed using the SQL query language. Mysql is a freely distributed system, i.e. You don't have to pay to use it. In addition, it is a fairly fast, reliable and, most importantly, easy-to-use DBMS, which is quite suitable for not too global projects.

You can work with Mysql not only in text mode, but also in graphic mode. There is a very popular visual interface (written in PHP, by the way) for working with this DBMS. It's called PhpMyAdmin. This interface makes it much easier to work with databases in Mysql.

PhpMyAdmin allows you to enjoy all the advantages of a browser, including scrolling an image if it does not fit on the screen. Many of the basic SQL data manipulation functions in PhpMyAdmin have been reduced to intuitive clear interfaces and actions reminiscent of following links on the Internet. But, nevertheless, it is still worth working in text mode.

Before proceeding to a detailed study of the SQL language, a few words about mysql installation and preparation for work. If you are not going to administer the server, then the information below will be useful to you only for general development. So, Mysql is installed very simply - automatically, click OK a couple of times, and that's it. After that, you can go to the directory where files like Mysql.exe, Mysqld.exe, etc. are located. (under Windows XP this is c:\Mysql\bin) The last file starts the Mysql server. On some systems, the server runs as a service. After starting the server, start the Mysql client by running the Mysql.exe program. They won't even ask for a password. Moreover, if you type shell> Mysql.exe -u root or shell>Mysql -u root Mysql you will get full administrator rights of the Mysql server. By the way, you need to execute these commands while in the directory where the Mysql.exe files are located.
To begin with, without going into the details of the commands, we will fix these two shortcomings (the lack of a password for the administrator and the ability to log in to anonymous users):

Mysql stores all data about users in the user table in a special database mysql data, which can only be accessed by the server administrator. Therefore, to change any password, you need to change this table. The password is set using the PASSWORD function, which encodes the entered data. In addition to changing the administrator password, you also need to delete all users who do not have a login (DELETE command). The Flush Privileges command causes the changes that have taken place in the system database (Mysql) to take effect.

Now let's create a database that we will work with (we are still working as a server administrator):
mysql>create database book;

As you can see, all commands in Mysql end with a semicolon. If you forgot to put this sign, then an invitation is issued to put it up until it is done:

mysql>show tables
->
->

Now the last step is to create simple user, give it access to the created database, and start working.

Mysql> GRANT ALL PRIVILEGES ON book.* TO [email protected]
IDENTIFIED BY "123";

The GRANT command gives the user nina, logged into the server from the same machine (from localhost) and identified by the password "123", certain rights (in this case, all) to all tables in the book database. Now we can log out and log in as user nina with the appropriate password:

shell>Mysql -u nina -p
Enter password : ***
Welcome to the MySQL monitor!...
mysql>

If you are going to use the database on someone else's server, then its administrator will do all the steps described above for you, i.e. everything will set up and create the user and database. The next chapter describes the SQL commands that are useful for working with data stored in the Mysql DBMS.

4.

5.

6.

7. Building an interface for adding information

So, we have some kind of table in the database. To build an interface for adding information to this table, you need to display its structure (i.e., a set of its fields) in an html form.

Let's break this task down into the following subtasks:

  • establishing a connection to the database;
  • selection of a working database;
  • getting a list of table fields;
  • display fields in html form.
After that, the data entered in the form must be written to the database.

Let's consider all these tasks in order.

8. Establishing a connection

So, the first thing to do is to establish a database connection.

Let's use the Mysql_connect function.

Mysql_connect Syntax

resource Mysql_connect ([string server
[, string username [, string password
[, boolean new_link
[, integer client_flags]]]]])

This function establishes a connection with mysql server and returns a pointer to that connection, or FALSE on failure.

Missing options are set to the following default values:
server = "localhost:3306"
username = username of server process owner
password = empty password

If the function is called twice with the same parameters, then a new connection is not established, but a reference to the old connection is returned.

To avoid this, the new_link parameter is used, which forces one more connection to be opened anyway.

The client_flags parameter is a combination of the following constants:

MYSQL_CLIENT_COMPRESS (use compression protocol),
MYSQL_CLIENT_IGNORE_SPACE (allows inserting spaces after function names), MYSQL_CLIENT_INTERACTIVE (wait interactive_timeout seconds - instead of wait_timeout - before closing the connection).

The new_link parameter was introduced in PHP 4.2.0 and the client_flags parameter was introduced in PHP 4.3.0.

The connection to the server is closed when the script execution ends, if it has not been closed before using the Mysql_close() function.

So, we establish a connection to the database on local server for user nina with password “123”:

$conn = mysql_connect(

or die( "Unable to install
connection: "
. mysql_error());
echo "Connection established";
mysql_close($conn);
?>

The Mysql_connect action is equivalent to the command

shell>Mysql -u nina -p123

9. Database selection

After the connection is established, you need to select the database with which we will work. Our data is stored in the book database. In MySQL, database selection is done using the use command:

mysql>usebook;


PHP has the Mysql_select_db function for this.

Mysql_select_db syntax:

Boolean

mysql_select_db(string database_name[, resource link_identifier])

This function returns TRUE on successful database selection and FALSE

  • otherwise.
Let's make the book database work:

$conn = mysql_connect(
"localhost" , "nina" , "123" )
or die( "Unable to install
connection: "
. mysql_error());
echo "Connection established";
mysql_select_db("book");
?>

10. Getting a list of table fields

Now you can do the actual problem solving. How to get a list of table fields? Very simple. PHP also has its own command for this case - Mysql_list_fields.

10.1. Mysql_list_fields Syntax

resource Mysql_list_fields (
database_name string,
row table_name
[, link_identifier resource])

This function returns a list of fields in table table_name in database database_name. It turns out that we didn’t have to choose a database, but this will come in handy later. As you can see, the result of this function is a resource type variable. That is, this is not quite what we wanted to get. This is a link that can be used to get information about the fields in a table, including their names, types, and flags.

The Mysql_field_name function returns the name of the field returned from the query. The Mysql_field_len function returns the length of a field. The Mysql_field_type function returns the type of the field, and the Mysql_field_flags function returns a space-separated list of field flags. Field types can be int, real, string, blob, etc. Flags can be not_null, primary_key, unique_key, blob,
auto_increment etc.

The syntax for all these commands is the same:

string Mysql_field_name (resource result, integer field_offset)
string Mysql_field_type (resource result, integer field_offset)
string Mysql_field_flags (resource result, integer field_offset)
string Mysql_field_len (resource result, integer field_offset)

Here result is the ID of the result of the query (for example, the query sent by the Mysql_list_fields or Mysql_query functions (more on that later)), and field_offset is the ordinal number of the field in the result.

Generally speaking, what is returned by functions like Mysql_list_fields or Mysql_query is a table, or rather, a pointer to it. To get specific values ​​from this table, you need to use special functions that read this table line by line. These functions include Mysql_field_name and so on. To iterate over all rows in the query result table, you need to know the number of rows in this table. Mysql_num_rows(result resource) command returns the number of rows in the result set
result.

And now let's try to get a list of fields in the Artifacts table (a collection of exhibits).

$conn = mysql_connect(
"localhost" , "nina" , "123" )
or die( "Unable to install
connection: "
. mysql_error());
echo "Connection established";
mysql_select_db("book");
$list_f = mysql_list_fields(
"book" , "Artifacts" , $conn );
$n = Mysql_num_fields($list_f );
for($i = 0 ; $i< $n ; $i ++){



$flags_str = mysql_field_flags(
$list_f , $i );
echo "
Field name: " . $name_f ;
echo "
Field type: " . $type ;
echo "
Field length: " . $len ;
echo "
Field flag string: "
.
$flags_str . "


" ;
}
?>

The result should be something like this (if there are only two fields in the table, of course):

Field name: id
Field type: int
Field length: 11
Field flag string:
not_null primary_key auto_increment
Field name: title
Field type: string
Field length: 255
Field flag string:
Displaying a list of fields in an html form

Now let's slightly correct the previous example. We will not just display information about the field, but display it in a suitable html form element. So, let's translate the elements of the BLOB type into textarea (note that the description field, which we created with the TEXT type, is displayed as having the BLOB type), we will display numbers and strings into text input lines , and the element with the auto-increment label will not be displayed at all, since its value is set automatically.

All this is solved quite simply, with the exception of selecting the auto_increment flag from the list of flags. To do this, you need to use the explode function.

Explode syntax:

array explode(string separator, string string [, int limit ])

This function splits the string string into parts using the delimiter separator and returns an array of the resulting strings.

In our case, we need to take a space “ " as a separator, and a string of field flags as a source string for splitting.

So, let's create a form for entering data into the Artifacts table:

$conn = Mysql_connect ("localhost" , "nina" , "123" );
// establish connection
$database = "book" ;
$table_name = "Artifacts" ;
mysql_select_db($database); // select database for
// work

// number of rows in the result
// previous request (i.e. how many
// fields in Artifacts table)
echo "

" ;
// create a data entry form
echo "

Add new row in
$table_name
"
;
echo "" ;
// for each field we get its name, type, length and flags
for($i = 0 ; $i< $n ; $i ++){
$type = Mysql_field_type ($list_f , $i );
$name_f = Mysql_field_name ($list_f , $i );
$len = Mysql_field_len ($list_f , $i );
$flags_str = Mysql_field_flags ($list_f , $i );
// make an array from the flags string,
// where each array element is a field flag
$flags = explode (" " , $flags_str );
foreach ($flags as $f )(
if ($f == "auto_increment" ) $key = $name_f ;
// remember the name of the autoincrement
}
/* for each non-autoincrement field in
depending on its type, display the appropriate form element */
if ($key<>$name_f )(
echo "" ;
switch ($type )(
case "string" :
$w = $len / 5 ;
echo "" ;
break;
case "int" :
$w = $len / 4 ;
echo "" ;
break;
case "blobs" :
echo "" ;
break;
}
}
echo "" ;
}
echo "

" . $name_f . "
size = $w>size = $w>
" ;
echo "" ;
echo "" ;
?>

If there are no open connections, the function tries to connect to the DBMS, similar to the Mysql_connect() function without parameters. The query result is buffered.

Note: The query string must NOT end with a semicolon.

For SELECT, SHOW, EXPLAIN, DESCRIBE queries only, Mysql_query() returns a pointer to the result of the query, or FALSE if the query was not executed. Otherwise, Mysql_query() returns TRUE if the query succeeds and FALSE if it fails. A value other than FALSE indicates that the request was successful. It doesn't say how many rows were affected or returned. It is quite possible that a successful request will not affect any of the rows. Mysql_query() also fails and will return FALSE if the user does not have sufficient permissions to access the table specified in the query.

So now we know how to send a request to insert rows into the database.
$list_f = Mysql_list_fields ($database , $table_name );
// get a list of fields in the database
$n = Mysql_num_fields($list_f ); // number of rows in the result
// previous request
// compose one query for all fields of the table at once
$sql = "INSERT INTO $table_name SET "; // start creating
// query, iterate over all fields of the table
for($i = 0 ; $i< $n ; $i ++){
$name_f = Mysql_field_name ($list_f , $i ); // calculate field name
$value = $_POST [ $name_f ]; // calculate field value
$j = $i + 1 ;
$sql = $sql. $name_f . " = "$value"" ; // append to
// string $sql pair name=value
if ($j<>$n ) $sql = $sql . ", "; // if the field is not
// last in the list, then put a comma
}
// before writing something to the database,
// you can see what request was received
//echo $sql;
$result = Mysql_query ($sql , $conn ); // send request
// display a message if the request was successful
if (! $result ) echo " Can"t add ($table_name) " ;
else echo "Success!
" ;
?>

Listing 11.0.2. insert.php

So, we solved the problem of adding data using the web interface. However, there is one subtlety here. When deciding, we did not take into account the fact that the values ​​of some fields (author, photo) should be taken from other tables (Persons, Images). Since Mysql does not work with foreign keys, this moment remains on the conscience of the system developers, i.e. on our conscience. It is necessary to complete the program in such a way that it is possible to enter the correct values ​​​​in such fields. But we will not do this, since the purpose of the lecture is to introduce the reader to the elements of technology, and not to create a working system. In addition, the knowledge available to the reader is quite enough to solve this problem on their own. We will turn to another task - displaying data stored in the Mysql DBMS database.

12.

13.

14.

15. Literature

http://mysql.ru/docs/man/
http://www.intuit.ru/department/database/mysql/

If you want to understand technical terminology easily and without frustration, you've come to the right place. We keep it simple, and we do our best to explain it in simple terms. So what is MySQL? Let's figure it out right now.

What is MySQL?

First of all, you need to know how to pronounce it: MY-ES-KYOO-EL '[my-es-ky-el]. You may hear other pronunciations, but at least now you know the official pronunciation. The Swedish company MySQL AB originally developed MySQL in 1994. Then the American technology company Sun Microsystems acquired full ownership by buying MySQL AB in 2008. American tech giant Oracle acquired Sun Microsystems in 2010, and MySQL has been virtually owned by Oracle ever since.

As for the general definition, MySQL is an open source relational database management system (RDBMS) with a client-server model. RDBMS is a software or service used to create and manage databases based on the relational model. Now let's take a closer look at each term:

Database

A database is simply a collection of structured data. For example, when you take a selfie: you press a button and take a photo of yourself. Your photo is the data, and your phone's gallery is the database. A database is a place where data is stored. The word "relational" means that the data stored in the dataset is organized in tables. Each table is related in some way. If the software does not support the relational data model, just call it DBMS.

open source

Open source means you are free to use and modify it. Anyone can install the software. You can also explore and tweak the source code to better suit your needs. However, the GPL (GPU Public License) defines exactly what you can do depending on the conditions. A commercial licensed version is available if you need more flexible ownership and extended support.

Client-server model

The computers that install and run the RDBMS software are called clients. When they need to access data, they connect to the RDBMS server. This is a client-server system.

MySQL is one of many RDBMS software options. RDBMS and MySQL are considered to be the same due to the popularity of MySQL. Name a few major web applications such as Facebook, Twitter, YouTube, Google, and Yahoo! everyone uses MySQL for data storage. While it was originally created for limited use, it is now compatible with many important computing platforms such as Linux, macOS, Microsoft Windows, and Ubuntu.

SQL

Remember that MySQL is one of the most popular brands of RDBMS software that implements the client-server model. So how do client and server interact in a RDBMS environment? They use a domain-specific language, Structured Query Language (SQL). If you've ever come across other names that have SQL in them, such as PostgreSQL and Microsoft SQL Server, they are most likely brands that also use SQL syntax. RDBMS software is often written in other programming languages, but always uses SQL as the primary language for interacting with the database. MySQL itself is written in C and C++. Think about the countries of South America, they are all geographically different and have different histories, but they all mostly speak Spanish.

Computer engineer Ted Codd developed SQL in the early 1970s based on the IBM relational model. It became more widely used in 1974 and quickly replaced the similar then obsolete languages, ISAM and VISAM. Beyond the history, SQL tells the server what to do with the data. This is similar to your WordPress password or code. You enter it into the system to access the control panel area. In this case, SQL statements can tell the server to perform certain operations:

  • Data Query: Request specific information from an existing database.
  • Data processing: adding, deleting, modifying, sorting, and other operations to change data, values, or visual elements.
  • Data Identification: Identifying data types, such as changing numeric data to integers. This also includes defining the schema or relationship of each table in the database.
  • Data access control: providing security measures to protect data, including deciding who can view or use any information stored in the database.

How does MySQL work?

The image explains the basic client-server structure. One or more devices (clients) connect to the server through a specific network. Each client can make a request from a graphical user interface (GUI) on their screens, and the server will produce the desired result if both ends understand the instruction. Without getting too technical, the basic processes that take place in a MySQL environment are the same:

  1. MySQL creates a database to store and manage the data that defines the relationships of each table.
  2. Clients can make queries by entering certain SQL commands on MySQL.
  3. The server application will respond with the requested information and appear on the client side.

That's all. Clients usually specify which MySQL GUI to use. The lighter and more user-friendly the graphical user interface, the faster and easier data management operations will be. Some of the most popular MySQL GUIs are MySQL WorkBench, SequelPro, DBVisualizer and Navicat DB Admin Tool. Some are free, some are commercial, some work exclusively for macOS, and some are compatible with major operating systems. Clients should choose a GUI based on their needs. For database management, including website management, the most obvious approach is phpMyAdmin.

Why is MySQL so popular?

MySQL is not really the only RDBMS on the market, but it is one of the most popular and second only to Oracle Database when evaluated using important parameters such as the number of mentions in search results, professional profiles on LinkedIn, and the frequency of technical discussions on Internet forums. The fact that many of the big tech giants rely on it further solidifies the well-deserved position. Why is that? Here are the reasons:

Flexibility and ease of use

You can modify the source code to meet your own expectations, and you don't have to pay anything for this level of freedom, including options to upgrade to an extended commercial version. The installation process is relatively simple and shouldn't take more than 30 minutes.

High performance

A wide range of clustered servers support MySQL. Whether you're storing large amounts of e-commerce data or doing heavy business intelligence, MySQL can help you with optimal speed.

industry standard

Industries have been using MySQL for years, which means there are abundant resources available for experienced developers. MySQL users can look forward to rapid software development, while freelance experts who want to work less will need them.

Safety

The security of your data should be your top concern when choosing the right RDBMS software. With the help of a system of access and account management, MySQL establishes a high level of security. Host-based verification and password encryption are available.

Now you know what MySQL is. Do you already have experience using MySQL? Please let me know by leaving a comment below or on Hostinger.

Liked the article? Share with friends!
Was this article helpful?
Yes
Not
Thanks for your feedback!
Something went wrong and your vote was not counted.
Thank you. Your message has been sent
Did you find an error in the text?
Select it, click Ctrl+Enter and we'll fix it!