Computer lessons

Php entry to mysql database. Practical examples

In this tutorial we'll look at how to insert data into a database directly from your PHP scripts.

Inserting data using SQL

You use SQL to insert data into a database in the same way you use SQL to create databases and tables. The SQL query syntax is:

INSERT INTO TableName (column1, column 2, ...) VALUES(value1, value 2, ...)

As you can see, you can update multiple columns in a single SQL statement by specifying them in a comma-separated list. But of course, you can also specify only one column and one value. Columns not mentioned in this SQL statement will remain empty.

Example: Inserting a new person into a table

In this example we use the database from Lesson 18. Let's say we want to insert a person into the database. It could be Gus Goose with phone number 99887766 and date of birth 1964-04-20 .

The SQL statement might look like this:

$strSQL = "INSERT INTO people(FirstName,LastName,Phone,BirthDate) VALUES("Gus","Goose","99887766 ","1964-04-20"");

As you can see, SQL statements can be quite long, and it can be easy to lose track. Therefore, it is better to write the SQL statement slightly differently:

strSQL = "INSERT INTO people("; strSQL = strSQL . "FirstName, "; strSQL = strSQL . "LastName," strSQL = strSQL . "Phone," strSQL = strSQL . "birth)"; strSQL = strSQL . "VALUES ("; strSQL = strSQL . ""Gus", "; strSQL = strSQL . ""Goose", "; strSQL = strSQL . ""99887766", "; strSQL = strSQL . ""1964-04-20""); mysql_query($strSQL) or die(mysql_error());

Here the SQL statement is constructed by dividing the sentence into small parts and then combining them into a variable $strSQL.

In practice there is no difference in using one or the other method, but when working with large tables the ability to "keep track" becomes extremely important, so choose the most appropriate method.

Let's try the following code to insert Gus Goose into the database:

Inserting data into the database // Connection to the database server mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error());// Select database mysql_select_db("mydatabase") or die(mysql_error()); //Building the SQL statement $strSQL = "INSERT INTO people("; $strSQL = $strSQL . "FirstName, "; $strSQL = $strSQL . "LastName, "; $strSQL = $strSQL . "Phone," $strSQL = $strSQL . "BirthDate"; $strSQL = $strSQL . "VALUES("; $strSQL = $strSQL . ""Gus", "; $strSQL = $strSQL . ""Goose", "; $strSQL = $strSQL . ""99887766", "; $strSQL = $strSQL . ""1964-04-20""); // SQL statement is executed mysql_query($strSQL) or die (mysql_error()); //Close connection mysql_close(); ?>

DB updated!

Saving user input to the database

You've probably already figured out that you can create a form to do this, as in Lesson 11, and the values ​​from the form can be inserted into an SQL statement. Let's say you have a simple form:

This form is submitted to the file insert.php, where you, as shown in Lesson 11, can receive user input by requesting the contents of the form. In this particular case, the SQL statement could be like this:

strSQL = "INSERT INTO people(FirstName) values("" . $_POST["FirstName"] . "")"

Similarly, you can request data from cookies, query string sessions, etc.

The most common beginner mistakes

At first, you'll probably get a bunch of error messages when you try to update the database. When working with the database, no errors are allowed at all. An incorrect comma may mean that the database is not updated and you will receive an error message. Below we describe the most common mistakes.

Invalid data type

It is important that the data and data type of the column match each other. Each column can contain data of a certain type. The following screenshot shows the data types of the "people" table from our example.

An error is thrown if, for example, you try to insert text or a number into a data field. Therefore, set the data type as precisely as possible.

The most common data types are listed below:

Meaning Data Type Size
CHR
Text or a combination of text and numbers. Can also be used for numbers not used in calculations (eg telephone numbers). Up to 255 characters - or the length specified in "Length"
TEXT
Large blocks of text or a combination of text and numbers. Up to 65,535 characters
INT
Numerical data for mathematical calculations. 4 bytes
DATE
Dates in YYY-MM-DD format 3 bytes
TIME
Time in hh:mm:ss format 3 bytes
DATETIME
Date and time in YYY-MM-DD hh:mm:ss format 8 bytes

SQL statements with quotes or backslashes

If you try to insert text that contains single quote ("), double quote ("), or backslash (\) characters, the record will not be inserted into the database. The solution would be to substitute backslashes in front of characters that must be mnemonized when inserted into database queries.

Last update: 11/1/2015

To add data, use the "INSERT" expression:

$query ="INSERT INTO products VALUES(NULL, "Samsung Galaxy III","Samsumg"");

The "INSERT" statement inserts a single row into a table. After the INTO keyword, the table name is indicated, and after VALUES, the set of values ​​​​for all columns is indicated in parentheses. Since we have three columns in the table, we indicate three values.

Since in the previous topic, when creating a table, we specified the following order of columns: id, name, company, in this case the value NULL is passed for the id column, “Samsung Galaxy III” for name, and “Samsumg” for company.

Since the id column is defined as AUTO_INCREMENT, we don't have to give it a specific numeric value and can pass in a NULL value and MySQL will assign the next available value to the column.

Now let's look at adding data using an example. Let's create a file create.php with the following content:

Data added"; ) // close the connection mysqli_close($link); ) ?>

Add new model

Enter model:

Manufacturer:

Here, the code for interacting with the database is combined with the functionality of the forms: using the form, we enter data to be added to the database.

Security and MySQL

Here we have used the mysqli_real_escape_string() function. It is used to escape characters in a string, which is then used in an SQL query. It takes as parameters a connection object and a string to be escaped.

Thus, we actually use character escape twice: first for the sql expression using the mysqli_real_escape_string() function, and then for the html using the htmlentities() function. This will allow us to protect ourselves from two types of attacks at once: XSS attacks and SQL injections.

From the author: oh, you can’t take the words out of the song! But you can delete them, update them, or insert others. The main thing is that the words are entered into the database. Today we will tell you how data is recorded in MySQL and how to do it correctly so that the song sounds!

Adding entries using phpMyAdmin

The phpMyAdmin shell for administering the MySQL DBMS implements “lightweight” functionality for adding new records to database tables. Because of its simplicity, it is ideal for both green "dummies" and "lazy" professionals.

To enter new information into the table, you must log into the program with administrator rights. Then select the desired database and table from the lists on the left. Then in the top menu go through the “Insert” item.

After this, to make a record in the MySQL database, fill in the “Value” field for all columns in the next window and click “OK” at the bottom.

In the above screenshot you can see that the “Animals” table being modified consists of two columns (fields): id and name. The second section specifies the type of each column. We only need to enter a value for the name field, since the id column is the primary key and was set to auto-increment when the table was created. This means that the value of the id field will be generated automatically by MySQL by adding 1 to the previous integer value.

To find out which field of data records in MySQL is the primary key, in phpMyAdmin go to the menu (with the table selected on the left in the list) to the “Structure” tab of the top menu. Here is a description of all table fields, their type and additional characteristics.

Inserting data using SQL queries

But phpMyAdmin is just a shell, and real administrators “talk” to the MySQL server using Structured Query Language. That is, they “talk” to him in SQL language. Since we strive to become real professionals, we will dive a little into the study of SQL commands within the framework of the topic under consideration. Here is a query, entering which in the “SQL” field, you will create the same database:

CREATE TABLE Animal (id MEDIUMINT NOT NULL AUTO_INCREMENT, name CHAR(30) NOT NULL, PRIMARY KEY (id));

CREATE TABLE Animal (id MEDIUMINT NOT NULL AUTO_INCREMENT ,

name CHAR (30) NOT NULL, PRIMARY KEY (id));

After creating the table and writing the data into the MySQL database (via the “Insert” tab), the program will inform you that a row with an identifier value of 1 has been added to animals. And a little lower in the editor window the query code will be displayed, which the shell generated for us and sent to the database server .

Request code:

INSERT INTO `my_db1`.`animal` (`id`, `name`) VALUES (NULL, "Cat");

INSERT INTO ` my_db1 ` . ` animal ` ( ` id ` , ` name ` ) VALUES ( NULL , "Cat" ) ;

Let's study it in more detail. In SQL, the INSERT statement is used to insert a new row into a table. It tells the server that the specified values ​​(VALUES (NULL, ‘Cat’)) need to be inserted into the database table (my_db1 . animal) in the id and name fields.

Please note that we do not specify a numeric value for the id column, but NULL, since we have “turned on” autofill (autoincrement) for this field.

How to insert a record using PHP

Everything we have considered is only a “prelude” to the main action, in which “His Highness” the server-side programming language PHP comes onto the stage. It was thanks to him that MySQL as a DBMS became so widespread on the Internet.
Most of the World Wide Web is built on a combination of these two Internet technologies. Wherever you look, you will find them everywhere: in modern CMS, “home-written” engines and on the server.

It's no surprise that PHP provides so many built-in functions for writing data to MySQL. But we will focus on the most important of them. Here is the code that adds a new "animal" to the animals table. If you try hard enough, you can collect a whole menagerie this way :)

$con_str=mysql_connect("localhost", "root", "", "db1"); if(mysql_connect("localhost","root"))( echo "Hello!!"; ) mysql_select_db("db1",$con_str); $query_str="INSERT INTO `db1`.`animal` (`id`, `name`) VALUES (NULL, "dog")"; mysql_query($query_str); mysql_close();

$con_str = mysql_connect ("localhost" , "root" , "" , "db1" ) ;

if (mysql_connect("localhost" , "root" ) ) (

echo "Hello!!" ;

mysql_select_db("db1", $con_str);

$query_str= "INSERT INTO `db1`.`animal` (`id`, `name`) VALUES (NULL, "dog")";

mysql_query($query_str);

mysql_close();

This code needs to be pasted into a PHP file and placed on the server side.

Using the mysql_connect() function we connect to the MySQL database server. The function takes as arguments the host, the DBMS user name, the password, and the name of the database to which you want to connect. We have a blank password because we are using a server installed on the local (client) machine.

To demonstrate all the described examples of writing to a MySQL database using PHP, we used the “gentleman’s kit” from Denver. It includes a local Apache server, a MySQL server, phpMyAdmin and several other useful tools for creating and testing program code.

Then, in the logical if block, we checked for a connection to the database server. After that, in the mysql_select_db() function we designated the database to which we will connect. Using the mysql_query() function, we launched the SQL query recorded in the $query_str variable. And at the end the established connection was closed (mysql_close() function). Now, if we look at our menagerie (the animal table), we will find a new “pet” there.

To write it into MySQL, PHP “kindly” provided the entire necessary set of functions. The main thing that beginners get burned by when using SQL in program code is incorrect writing of queries, violation of syntax and alternation of escaping characters (quotes).

To avoid the appearance of extra “gray” hair on your head, it is better to check the correct spelling of the request using phpMyAdmin. To do this, place the SQL code in the program editor and run it. If something is wrong, the application will start swearing, display a red message and indicate the location of the error.

As you can see, with the help of MySQL you can “collect” your own menagerie and correctly change the words of any “song”. And PHP is ideal for writing to the MySQL database, so we advise you to make a “close” friendship with this “great” programming language!

In this post I want to tell you, how to transfer the entered data into the form to the Database. And so we create a simple form where we will have two fields: the user’s name and his email:

Your name:
Your email:


This form can be used to register a new user, to send out news, to collect statistics, or for anything... In general, the user enters his data into this form: name and email, clicks on the button and then the data goes into the PHP script:

$name = $_POST["name"]; $email = $_POST["email"]; $result = mysqli_query("INSERT INTO user (name, email) VALUES ("$name", "$email")"); if ($result) ( echo "Data saved successfully!"; ) else ( echo "An error occurred, please try again."; )


What's going on in this script? Let's figure it out now!
The data entered into the form is transferred using the POST method to the php script (which is written above), and using the global array $_POST, the data is formed into the variables $name and $email:

$name = $_POST["name"]; $email = $_POST["email"];


After the variables are ready to be entered into the database, we create a request. But first, your scripts must already be connected to the database; I wrote in this thread how to connect to the database: . The request itself looks like this:

$result = mysqli_query("INSERT INTO user (name, email) VALUES ("$name", "$email")");


In this code, we have indicated that the following variables will be added to the name and email cells that are in the user table: $name and $email.
Next, if everything went well, we will receive a message from the condition:

Data saved successfully!


If any problems arise and the data has not been entered, we will receive an error message:

An error occurred, please try again.


That's all!

*** *** *** *** ***

If desired, you can add more fields for entering information, for example, we need to add a field for entering the user's city. We already have a ready-made script (written above), now we’ll just add a field Your city, let's call the variable: $city . And so on in the data entry form, after:

Your email:


add:

Your city:


In the php script, after:

$email = $_POST["email"];


add:

$city = $_POST["city"];


And of course we add it in the request too, like this:

$result = mysqli_query("INSERT INTO user (name, email, city) VALUES ("$name", "$email", "$city")");


This is what you should end up with:
Input form:

Your name:
Your email:
Your city:


Script:

$name = $_POST["name"]; $email = $_POST["email"]; $city = $_POST["city"]; $result = mysqli_query("INSERT INTO user (name, email, city) VALUES ("$name", "$email", "$city")"); if ($result == true) ( ​​echo "Data saved successfully!"; ) else ( echo "An error occurred, please try again."; )


As you can see, nothing complicated! If necessary, you can add another field, and another, and another...

In this article, we'll look at how to use PHP to insert rows into a MySQL database.

Step 1 - Creating a Table

First you need to create a table for the data. This is a simple procedure that can be done using phpMyAdmin in your hosting control panel.

After logging into phpMyAdmin you will see this interface:
Let’s create a table named Students in the u266072517_name database by clicking on the “Create Table” button. After this, we will see a new page on which we set all the necessary table parameters:

This is the simplest setting that can be used on a table and get more information about the table/database structure.

Column options:

  • Name is the column name that appears at the top of the table.
  • Type — column type. For example, we chose varchar because we will be entering string values.
  • Length/Values ​​- Used to specify the maximum length that an entry in this column can have.
  • Index - We used the "Primary" index for the "ID" field. When creating a table, it is recommended to use only one column as the primary key. It is used to list the records in the table and is required when setting up the table. I also noted “A_I”, which means “Auto Increment” - the parameter for automatically assigning record numbers (1,2,3,4...).
    Click the "Save" button and the table will be created.

Step 2: Write PHP code to insert data into MySQL.

Option 1 - MySQLi method

First you need to establish a connection to the database. After this we use the SQL INSERT query. Full code example:

" . mysqli_error($conn); ) mysqli_close($conn); ?>

The first part of the code (line 3 - 18) is intended to connect to the database.

Let's start with line number 19:

$sql = "INSERT INTO Students (name, lastname, email) VALUES ("Thom", "Vial", " [email protected]")";

It inserts data into a MySQL database. INSERT INTO is a statement that adds data to a specified table. In our example, data is added to the Students table.

Next is a list of columns into which the values ​​are inserted: name, lastname, email. The data will be added in the order specified. If we had written (email, lastname, name), the values ​​would have been added in a different order.

The next part is the VALUES statement. Here we specify the values ​​for the columns: name = Thom, lastname = Vial, email = [email protected].

We ran the request using PHP code. In program code, SQL queries must be escaped with quotes. The next piece of code (line 20-22) checks if our request was successful:

if (mysqli_query($conn, $sql)) ( echo "New recordcreatedsuccessfully"; )

This code displays a message indicating the request was successful.

And the last part (line 22 - 24) displays a notification if the request was not successful:

else ( echo "Error: " . $sql . "
" . mysqli_error($conn); )

Option 2 - PHP Data Object (PDO) Method

First we need to connect to the database by creating a new PDO object. When working with it we will use various PDO methods. Object methods are called as follows:

$the_Object->the_Method();

PDO allows you to "prepare" SQL code before it is executed. The SQL query is evaluated and "corrected" before running. For example, a simple SQL injection attack can be carried out by simply entering SQL code into a form field. For example:

Since this is syntactically correct SQL, the semicolon makes DROP DATABASE user_table a new SQL query and the user table is dropped. Prepared expressions (bound variables) do not allow semicolons and quotes to terminate the original query. Therefore, the DROP DATABASE command will never execute.

To use prepared expressions, you need to write a new variable that calls the prepare() method of the database object.

Correct code:

getMessage(); ) // Set variables for the person we want to add to the database $first_Name = "Thom"; $last_Name = "Vial"; $email = " [email protected]"; // Create a variable that calls the database object's prepare() method // The SQL query you want to run is entered as a parameter, and the placeholders are written like this: placeholder_name $my_Insert_Statement = $my_Db_Connection->prepare("INSERT INTO Students ( name, lastname, email) VALUES (:first_name, :last_name, :email)"); // We now tell the script which variable refers to each placeholder to use the bindParam() method // The first parameter is the placeholder in the statement above , the second is the variable it should refer to $my_Insert_Statement->bindParam(:first_name, $first_Name); $my_Insert_Statement->bindParam(:last_name, $last_Name); $my_Insert_Statement->bindParam(:email, $email); // Execute the query using the data we just defined // The execute() method returns TRUE if successful and FALSE if not, giving you the option of printing your own if message ($my_Insert_Statement->execute()) ( echo "New recordcreatedsuccessfully"; ) else ( echo "Unable to createrecord"; ) // At this point you can change the variable data and run a query to add more data to the database data to the database $first_Name = "John"; $last_Name = "Smith"; $email = " [email protected]"; $my_Insert_Statement->execute(); // Execute again when the variable is changed if ($my_Insert_Statement->execute()) ( echo "New recordcreatedsuccessfully"; ) else ( echo "Unable to createrecord";

On lines 28, 29, and 30, we use the bindParam() method of the database object. There is also a bindValue() method, which is very different from the previous one.

  • bindParam() - This method evaluates the data when the execute() method is reached. The first time the script reaches the execute() method, it sees that $first_Name matches "Thom". Then binds this value and runs the request. When the script reaches the second execute() method, it sees that $first_Name now matches "John". Then it binds this value and runs the query again with new values. It is important to remember that we have defined a query once and reuse it with different data at different points in the script.
  • bindValue() - This method evaluates the data once bindValue() is reached. Since $first_Name was set to "Thom", when bindValue() is reached, it will be used every time the execute() method is called on $my_Insert_Statement.
    Notice that we are reusing the $first_Name variable and assigning it a new value a second time. After running the script, both names will be listed in the database, despite the fact that the $first_Name variable at the end of the script has the value “John”. Remember that PHP checks the entire script before it runs.

If you update the script to replace bindParam with bindValue, you will insert "Thom Vial" into the database twice and John Smith will be ignored.

Step 3 - Confirm Success and Resolve Problems

If the request to insert rows into the database was successful, we will see the following message:

Troubleshooting Common Errors

MySQLi

In any other case, an error message will be displayed. For example, let's make one syntax error in the code and we'll get the following:

The first part of the code is ok, the connection was established successfully, but the SQL query failed.

"Error: INSERT INTO Students (name, lastname, email) VALUES ("Thom", "Vial", " [email protected]") You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the rights syntax to use near "(name, lastname, email) VALUES ("Thom", "Vial", " [email protected]")" at line 1"

There was a syntax error that caused the script to crash. The error was here:

$sql = "INSERT INTO Students (name, lastname, email) VALUES ("Thom", "Vial", " [email protected]")";

We used curly braces instead of regular ones. This is incorrect and the script generated a syntax error.

PDO

Line 7 of the PDO connection sets the error mode to "display all exceptions". If set to a different value and the request failed, we would not receive any error messages.

This setting should only be used when developing a script. When activated, database and table names may be displayed that are best hidden for security reasons. In the case described above, when curly braces were used instead of regular braces, the error message looks like this:

Fatal error: Uncaughtexception "PDOException" with message "SQLSTATE: Syntax error or accessviolation: 1064 You have an error in your SQL syntax; check the manualthatcorresponds to your MySQL server version for the rightsyntax to use near "(name, lastname, email) VALUES ("Thom", "Vial", " [email protected]")" at line 1"

Other possible problems:

  • Columns are incorrectly specified (non-existent columns or misspelled column names).
  • One value type is assigned to a column of another type. For example, if you try to insert the number 47 into the Name column, you will get an error. This column must use a string value. But if we specified a number in quotes (for example, "47") it would work, because it is a string.
  • An attempt was made to enter data into a table that does not exist. There was also a spelling mistake in the table name.

After successfully entering the data, we will see that it has been added to the database. Below is an example of a table with data added.

Conclusion

In this article, we have shared how to use PHP to insert data into a MySQL database using MySQLi and PDO. And also how to eliminate common mistakes. This knowledge will be useful when learning programming and when developing your own website.

This publication is a translation of the article “ How to Use PHP to Insert Data Into MySQL Database", prepared by the friendly project team