SQL query to add and remove records. How to use PHP to insert rows into a MySQL database Php mysql add a record to a table

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=

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 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 designed 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 that 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 in order to use the bindParam() method // The first parameter is the placeholder in the statement above , the second is the variable it should reference $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

Comments moved from the blog

SERGEY
09/14/2016 at 01:25
Good afternoon!
I am interested in the following question: what is the easiest way to organize the storage of data and program settings without using a database? I don't want to be tied to MySQL or Access..

ADMIN
09/14/2016 at 22:14
Hello!

Properties.Settings
App.Config
XML file
serialization
Try to choose one of these from the list.

NICHOLAY
09/16/2016 at 02:28
Hello, how can I delete the selected row in dataGridVIew from dataGridVIew and phpMyAdmin.

PhpMyAdmin? This is just a shell for working with a database, can you explain?

NICHOLAY
09/18/2016 at 02:24
It is necessary that the selected row be deleted from the DataGridView and from the database.

ADMIN
09/19/2016 at 07:00
How to delete a row in a Mysql database - added an article.

NICHOLAY
09/20/2016 at 09:20
Thanks a lot.

DIMA
09.20.2016 at 10:24
Hello, is it possible to implement this method not through DataGridView, but through ComboBox? If so, how? Thank you.

ADMIN
09/22/2016 at 03:21
Hello. Example:

GENNADY
09.22.2016 at 18:25
why should I enter such text into the database System.Windows.Forms.TextBox, Text: ge

By the way, this (ge) at the end it is written by gene, even though the text is specified in the table settings. The word of gene should have fit further, I display this table in my program and it turns out that it displays all this unnecessary text for me

ADMIN
09/24/2016 at 04:17
Most likely the SQL query is written incorrectly, for example:

In textBox1 enter the name: Gena.

Sql query: “Insert into table name values(textBox1, ..)”; Result: System.Windows.Forms.TextBox

And you need to pass: “Insert into table name values(textBox1.Text, ..)”;
Result: Gena

GENNADY
09.24.2016 at 18:41
That is how it is. Thank you

SERGEY
09.25.2016 at 11:51
Hello. How to implement adding to the database via textBox?

ADMIN
09.26.2016 at 20:53
Everything is the same in principle. For example, let's take the very last example, it needs:

//create parameters and add them to the collection cmd.Parameters.AddWithValue("@Name", textBox1.Text); cmd.Parameters.AddWithValue("@LastName", textBox2.Text);

now the parameters: Name and LastName receive the values ​​​​entered in the textboxes and transfer them to the database

LINARA
09.27.2016 at 17:45
Hello, how can I select a row in dataGridVIew and phpMyAdmin?

ADMIN
09.29.2016 at 02:06
I don't know how to highlight a line in phpMyAdmin. And in dataGridView, for example, this can be done using the SelectionChanged event.

P.S.H.
09/30/2016 at 03:48
2Linara:
If you want to edit rows that way, take a tool a la HediSQL, configure and change the rows.

2admin
Good day! Thanks for the materials - everything is very cool)
Question: I add data with the following request (it’s a test):

String sql = "INSERT INTO users (`FIO`, `Tour`, `Count`, `Cost`, `Date`, `Passport`, `Birth`) VALUES ("Kolyan", "Moscow", "1+1 ", 1100, "2011-11-11", "1111 1111", "9.11.1900");";

The data is entered ok, but in the database (mysql) instead of the Cyrillic alphabet it appears “????”.

Visual studio says that System.String is a Unicode sequence.

Also tried:

ALTER DATABASE `test` COLLATE "koi8r_general_ci"; ALTER TABLE `users` COLLATE="koi8r_general_ci"; ALTER DATABASE `test` COLLATE "utf8_unicode_ci"; ALTER TABLE `users` COLLATE="utf8_unicode_ci";

But it doesn't help...
What can be wrong? Different VS and DB encodings? Or what?
Could you direct me what to read/change.
Thank you

ADMIN
10/01/2016 at 09:49
Hello.

In the database (and in the table) the mapping is utf_general_ci

Is there such a comparison? Perhaps utf8_general_ci?

Usually they create a Mysql database by choosing the utf8_general_ci comparison, so there are no problems with the Cyrillic alphabet, unless, of course, crooks come from the client to the server.

COLLATION is used for comparison, but in this case the encoding (charset) is important. Therefore, first you need to make sure that it is set correctly on the server, for example in utf8, and not latin1.

When connecting via the .net connector (by default), latin1 is used, so sometimes you need to explicitly specify the utf8 encoding in the connection string:

MySqlConnection mycon; mycon = new MySqlConnection("server=127.0.0.1;uid=vasya;pwd=123;database=test;Charset=utf8;"); //MySqlConnectionStringBuilder: mysqlCSB.CharacterSet = "utf8";

P.S.H.
10/01/2016 at 11:34
You're right, I peed myself, utf8_general_ci!
Yes it helped, ;Charset=utf8;
Thank you so much!

SERGY
10/02/2016 at 11:02
Thanks for the working example. Question
I created a text field in which I would like to enter the IP address of the database, but I don’t know how to insert this data here

String conStr = "server=@textBox2;user=test;" +
"database=test;password=test;";
Please tell me how to insert data from text fields in a windows form into this design...

ADMIN
10/03/2016 at 11:50
"[email protected];user=...
In general, it is better to use properties instead of such a string, as in this article, or the String.Format() method

OLGA2203
05/15/2017 at 20:14

String Connect = “Server=127.0.0.1;Port=3306;Database=base;Data Source=localhost;user=root;”; MySqlConnection con = new MySqlConnection(Connect); con.Open(); //Establish a connection to the database. MySqlCommand cmd = new MySqlCommand(); cmd.CommandText = @”INSERT INTO tovar(ID,Category,Name,TradeMark,Price,Photo,Size,Color,Material,Count) VALUES (@pr, @Category, @Name, @TradeMark, @Price, @Photo, @Size, @Color, @Material, @Count)”; cmd.Parameters.AddWithValue(“@pr”,counter); cmd.Parameters.AddWithValue(“@Category”, comboBox1.SelectedItem.ToString()); cmd.Parameters.AddWithValue(“@Name”, textBox1.Text); cmd.Parameters.AddWithValue(“@TradeMark”, textBox2.Text); cmd.Parameters.AddWithValue(“@Price”, Convert.ToInt32(textBox4.Text)); cmd.Parameters.AddWithValue(“@Photo”, textBox3.Text); cmd.Parameters.AddWithValue(“@Size”, textBox6.Text); cmd.Parameters.AddWithValue(“@Color”, textBox5.Text); cmd.Parameters.AddWithValue(“@Material”, textBox8.Text); cmd.Parameters.AddWithValue(“@Count”, Convert.ToInt32(textBox7.Text)); cmd.Connection = con; cmd.ExecuteNonQuery(); MessageBox.Show(“The addition was successful”, “The addition was successful”, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

The error “Column ‘ID’ cannot be null” is displayed, I remove the addition to the ID column - the same thing is written about the next column, etc.
If I enter any constant values ​​in parentheses into VALUES, the row is added to the database.
Tell me, please, what is the problem? I need to record exactly the data and values ​​entered through the form into the database

All modules of a site or web application where it is necessary to enter and record some data (for example, name, age, address, etc.) use a simple function in the mysql language INSERT INTO `name_base` (name,value1,value2) VALUES ('Vasya ','1','2');

All variables are entered into the database according to the values ​​we set in the first brackets. It is important to consider the encoding of the handler script, database, and configuration file. It is advisable to use the most common encoding UTF-8.

Please note that you can write to the database in two ways.

First way if we do not initially specify the cell names of the database tables. Then we have to list all the variables for each cell, namely how many cells are in the database table, so many variables should be listed in parentheses after the VALUE value.

For example:
There are four cells in a database table. This means that after the VALUE (..) element, all four variables must be listed in parentheses. And one more thing: if the variable does not exist, let's say it is an optional parameter. Then we just write an empty value in quotes ‘’,

"INSERT INTO `name_base` VALUES (NULL, `".$name."`,``,`2`)"; // the third empty value is written in quotes

But this request has some minor drawbacks. If you add one cell or two cells to a database table, this query will return an error. Because in this method, listing all cells in the query is mandatory.

Second way if after an INSERT INTO `name_base` (...) query, list all the cells after the database name. An example has already been discussed above. If you forgot, let's write it again:

"INSERT INTO `name_base`(`name`,`value`,`value2`) VALUES (NULL, `".$name."`,``,`2`)";

Here we have listed all the cells (name,value1,value2) . And if you add an additional two cells to the database table, then the query syntax will not have to be changed. But unless we need to immediately add in one request those very additional variables that we need for those very new created cells.

This error occurs very often after a small change on the site. Let's say the administrator added an additional cell to the database, let's say status. But the script processor did not have time to change the module, or simply forgot. But some sites have a very complex structure, and finding an error can take a lot of time and effort. Therefore, it is advisable to use the second method of writing to the database. Although this kind of mistake is more often made by novice web programmers.

Php entry to mysql database. Practical examples

So, now we get to the heart of the matter when working with database queries. We will do everything using practical examples. Let's create a simple script to record comments that site visitors will leave.

First, let's create a table msg in the database with four cells. In the first cell we write the id of the comment. The number of characters in the cell is up to ten characters with the auto-increment parameter. This automatic setting will change every time a comment is added to +1.

The next cell is the name of the user. Number of characters - up to two hundred - three hundred characters of your choice, parameter char. Then the comment cell - in this cell we will enter the text of the comment itself. If you want to record large comment texts, then you can set the text parameter - then you can enter simply huge texts, more than five hundred thousand characters, or set the tinytext parameter, then a little less characters will fit in, but it will work a little faster.

But in our case, we will keep in mind that visitors will not write huge texts. And therefore, we will limit ourselves and record two thousand characters with the varchar parameter to record string values.

In the last cell we will write the date the comment text was recorded. We will write in numerical format in seconds, using the current date and time function time(); For simplicity, we will set the function to the variable $time=time(); And let's create a cell in the database. Let's call it the same name as time with the int parameter (for numeric values). Let's write down the number of characters - eleven is better (with a small margin for the future :-).

The database dump is as follows:

Table structure `msg` -- CREATE TABLE IF NOT EXISTS `msg` (`id` int(10) NOT NULL AUTO_INCREMENT, `name` char(250) NOT NULL, `coment` varchar(2000) NOT NULL, `time` int(11) NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

That's it, a table for comments has been created. Now we write a form to write a comment and the script handler itself. The HTML code for the comment form is as follows.

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 passed into the PHP script (written above) using the POST method, and using the global array $_POST, the data is formed into the $name and $email variables:

$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...

Share