Adding data to the php database. Ask SQL to add and delete records. How to insert a record for additional help PHP

From whose post I want to confess, How to transfer to the Database, enter the data in the form. And so we create a simple form, where we will have two fields: Your name and your email address:

Your name:
Your email:


This form can be used for registering a new customer, for distributing new products, for collecting statistics, and it is always useful... Using this form, the customer enters his data: his name and email, clicks on the button and then the data goes to the php script:

$name = $_POST["name"]; $email = $_POST["email"]; $result = mysqli_query("INSERT INTO user (name, email) VALUES ("$name", "$email")"); if ($result) ( echo "Successfully saved data!"; ) else ( echo "It's been sweet, please try again."; )


What does this script contain? Let's figure it out right away!
Once you have entered the data form using the POST method, go to the php script (which is the most common spelling), and using the additional global $_POST array, the data is formed into the following names: $name and $email:

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


After the changes are ready to be added to the base, the order is added. Before your scripts are at fault, they will already be connected to the database, as soon as you connect to the database, I wrote in this thread: . The question itself looks like this:

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


In this code we have indicated that before the middle names and emails, like in the user table, the following changes will be added: $name and $email.
Now that everything went well, we withdraw this information from our minds:

Dani has been successfully saved!


If any problems arise and the data were not entered, we will withdraw notifications about the amendment:

There was a mercy, please, please try again.


That's all!

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

If necessary, you can add more fields to enter information, for example, we need to add a field to enter the location of the merchant. We already have a ready-made script (more writing), now we just add a field Your place, let's call it: $ city . And so in the data entry form, after:

Your email:


addable:

Your place:


In php scripts, after:

$email = $_POST["email"];


addable:

$city = $_POST["city"];


Well, first of all we add it like this:

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


The axis will appear as a result:
Entry form:

Your name:
Your email:
Your place:


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 "Successfully saved money!"; ) else ( echo "You've had a meal, please try again."; )


You see nothing foldable! If necessary, you can add another field, and another, and another...

Comments moved from the blog

SERGY
09/14/2016 about 01:25
Good day!
Quote this way: what is the easiest way to organize saving data and adjusting programs without database corruption? I don’t want to get tied to MySQL or Access.

ADMIN
09/14/2016 about 22:14
I'm flying!

Properties.Settings
App.Config
XML file
serialization
Try choosing something from this list.

MIKOLA
09/16/2016 about 02:28
Hello, how can I view the view row in dataGridVIew from dataGridVIew and phpMyAdmin.

PhpMyAdmin? What is the purpose of the shell for robots with a data base, can you explain?

MIKOLA
09/18/2016 about 02:24
It is necessary for the view row to be visible from the DataGridView and from the database.

ADMIN
09.19.2016 about 07:00
How to delete a row in a Mysql database - by adding an article.

MIKOLA
09.20.2016 about 09:20
Great.

DIMA
09.20.2016 about 10:24
Hello, is it possible to implement this method not through DataGridView, but through ComboBox? If so, then what? Dyakuyu.

ADMIN
09/22/2016 about 03:21
Vitannya. Butt:

GENADIY
09.22.2016 about 18:25
Why should I enter the following text into the database System.Windows.Forms.TextBox, Text: ge

To statti os tse (ge) to kintsya tse it is written gene want in the adjusted table of indications text.

ADMIN
09.24.2016 about 04:17
Shvidshe for all incorrect spellings of SQL is written, for example:

In textBox1 the name is entered: Gena.

Sql will write: “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

GENADIY
09.24.2016 about 18:41
It’s just like that. Dyakuyu

SERGY
09.25.2016 about 11:51
I'm flying. How to implement adding to the database via textBox?

ADMIN
09.26.2016 about 20:53
All the same in principle. For example, let's take the remaining butt, someone 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 retrieve the values ​​entered into the textbox and pass them to the database

LINARA
09.27.2016 about 17:45
Good afternoon, what is the view row in dataGridVIew and phpMyAdmin?

ADMIN
09.29.2016 about 02:06
I don't know how you can see the row in phpMyAdmin. And in dataGridView, for example, you can use the additional SelectionChanged method.

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

2admin
Good day! Thank you for the materials - everything is very well laid out)
Nutrition: I add the data in the following way (in 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.

Having 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";

Ale doesn’t help.
Why can you have a buti on the right? Rizny coding VS and DB? Or what?
You could send me something to read/change.
Dyakuyu

ADMIN
01.10.2016 about 09:49
Vitannya.

The database (and tables) have utf_general_ci

What kind of arrangement is this? Perhaps utf8_general_ci?

Create a Mysql database by selecting utf8_general_ci, so there are no problems with the Cyrillic alphabet, since the client will not necessarily send messages to the server.

COLLATION is used for equalization, and in this case the coding (charset) is important. Therefore, it is necessary to reconfigure that it is installed on the server correctly, for example in utf8, and not latin1.

When connecting via .net, the connector (behind the scenes) uses latin1, which requires explicitly specifying the utf8 encoding in the connection line:

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.
01.10.2016 about 11:34
You're talking, having peed yourself, utf8_general_ci!
So it helped, Charset = utf8;
Such majesty!

SERGY
02.10.2016 about 11:02
Thank you for a working butt, required. Food
I created a text field where I would like to enter the IP address of the database, but I don’t know how to enter the data here.

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

ADMIN
03.10.2016 about 11:50
"[email protected];user=...
It is better to replace such a row with the power of the authorities, as in this statti, or the String.Format() method

OLGA2203
05/15/2017 about 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(); //Install a connection to the database. MySqlCommand cmd = New MySqlCommand(); cmd.CommandText = @”INSERT INTO (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("Add was successful", "Add was successful", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

I see the error "Column 'ID' cannot be null", I remove the addition to the ID section - I also write about the upcoming step, etc.
When I enter constant values ​​in the arms of VALUES, the row is added to the base.
Tell me, kindly, who has a problem? It is necessary to record in the database the same data that is entered through the form, the same value

We will look at these statistics, perhaps some of the most important ones SQL queries. Tse query for additional records from the database table. Splinters happen SO often add new records to the table, and work automatically, then this material is bound to the wound.

For the cob SQL query to add a new record to the table:

INSERT INTO users (login, pass) values("TestUser", "123456")

When you add a record, the command " INSERT INTO", then the name of the table in which the record is inserted. Next, go to the round arms and name the fields you want to fill in. And then to the round arms after the words values We are beginning to overestimate the values ​​of the fields we have chosen. After this entry, a new entry will appear in our table.

Inodes required update the table entry for whom is the coming SQL query:

UPDATE users SET login="TestUser2", pass="1234560" WHERE login="TestUser"

This is more foldable, due to its design " WHERE", a little less about her. Let's go now, team" UPDATE", then the table name, and after " SET We describe the values ​​of all fields that we want to change. If everything were simple, but the food stopped: And what kind of record should you follow?"For whom is it necessary" WHERE". In this field we update the record, field" login"what has meaning" TestUser Please note that if there are only a few such records, then absolutely everything will be updated! It is very important to understand this, otherwise you risk wasting your table.

Let's talk a little more about " WHERE In addition to simple checks for equality, there are also some inequalities, as well as logical operations: ANDі OR.

UPDATE users SET login = "TestUser2", pass="1234560" WHERE id< 15 AND login="TestUser"

Denmark SQL query update those records, id there are fewer of them 15 І field " login"may matter" TestUser"I hope you got the hang of the design" WHERE", that's even more important. Same " WHERE"Vikorist at selecting records from the table, and this is the problem that is most often encountered when working with databases.

I, finally, simple SQL query for a range of records from a table:

DELETE FROM users WHERE login="TestUser2"

After the command " DELETE FROM"Go to the table where you need to delete the records. Next, we describe the "WHERE" construction. If the record is acceptable to the described minds, it will be deleted. Again, please respect the number of records, mind after " WHERE", you can go out anyway because of their strength.

All modules of the site or web add-ons, where you need to enter and record data (for example, names, ages, addresses, etc.) use a simple function in mysql language INSERT INTO `name_base` (name,value1,value2) VALUES ('Vasya' ,'1','2');

All changes are entered into the database according to the values ​​that were specified in the first arms. It is important to code the collection script, the data base and the configuration file. Bazhano vikoristuvat the widest encoding UTF-8.

There are two ways to create a track that can be written to the base.

First method Because we do not specify first names in the middle of the database table. Therefore, we are responsible for re-correcting all the changes for the skin center, and as many centers as there are in the database table, the same number of changes may be re-correcting for the arms after the VALUE value.

For example:
The database table has many middles. Also, after the VALUE (..) element, all changes will be redone in the arms. And one more point: if the change does not change, this non-binding parameter is permissible. Then we simply write empty meanings in the paws ‘’,

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

The ale is washed down with small portions. If you add one item or two items to the database table, this will be added back. Because in this method, the mixture of all the middle dishes is combined.

Another way If you type INSERT INTO `name_base` (…) to re-enter all the entries after the database name. The butt has already been looked at a little bit. If we forgot, let’s write it again:

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

Here we have re-sold all the coms (name, value1, value2). If you add two more entries to the database table, you will not be able to change the query syntax. Just because we don’t need to add in one drink the same additional changes that we need for these new creations of the middle.

This kind of warning appears even often after a minor change on the site. For example, the administrator has added an additional account to the database, for example status. But the script editor didn’t manage to change the module, or simply forgot. All these sites have a very complex structure, and it can take a lot of time and energy to find a solution. That's why I'll write down another method to the database. In order to achieve this kind of solution, web-based programs are more often used.

Php entry to database mysql. Practical butts

Well, now we have reached the very essence of the work with queries to the database. Everything works on practical stocks. Let's create a simple script for recording comments that will contribute to the site.

For starters, let’s create the msg table in the data base using several middle steps. We write the id comments first. The number of characters in the middle is up to ten characters with the auto-increment parameter. This parameter is automatically changed when a skin comment is added to +1.

The sale of the name of the owner is coming. Number of characters – up to two – three hundred characters of your choice, parameter char. Then the comment box - the text of the comment itself is entered into this box. If you want to record large texts of comments, then you can set the text parameter - you can also enter simply large texts, more than five hundred thousand characters, or set the tinytext parameter, then you can enter a few less characters, but you will only need a few less characters.

But in our opinion, we will respect our mothers so that our teachers will not write great texts. In addition, two thousand characters are combined and fixed with the varchar parameter to record row values.

In the remaining middle, write the date of entry into the text of the commentary. Write in numeric format in seconds, using the additional stream date and hour function time(); For simplicity, the function will be set to $time=time(); I make the middle in the database. Namely time with the int parameter (for numeric values). Let's write down the number of characters - more like eleven (with a small margin for Mayday :-).

Dump of offensive data:

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 ;

We've created a table for comments. Now we are writing a form for writing a comment and the script itself. HTML code of the form for making comments on upcoming events.

Author's view: Eh, you can’t get it out of the song of words! You can also delete them, update them, or insert others. Golovnya, so that the words are entered into the database. Today we know how to record MySQL data and how to do it correctly so that the song sounds!

Adding records for help phpMyAdmin

In the phpMyAdmin shell for administering the MySQL DBMS, an “improved” functionality has been implemented for adding new records to the database table. Due to its simplicity, it is ideal for both green “dummies” and “ice” professionals.

To add new information to the table, go to the program with administrator rights. Then, from the lists of evil, select the required database and table. Next, in the top menu, go through the “Insert” item.

After this, to create a record in the MySQL database, remember in the next window for all entries in the “Values” field and click “OK” at the bottom.

In the above screenshot you can see that the “Animals” table, which is being modified, consists of two columns (fields): id and name. In another section, the type of skin condition is indicated. We only need to enter values ​​for the name field, since id is the primary key, and auto-increment is set for the newly created table. This means that the values ​​of the id field will be generated automatically by MySQL, up to the leading integer numeric value of 1.

To find out which MySQL data record field is the primary key, in phpMyAdmin go to the menu (when you select the content table in the list) to the “Structure” tab of the top menu. Here you can find a description of all the fields in the table, their type and additional characteristics.

Inserting data using additional SQL queries

Ale phpMyAdmin is just a shell shell, and the administrators work with the MySQL server for additional language structuring queries. Then you can “distract” my SQL from it. So, since we are true professionals, we are a little “drilled” in the development of SQL commands within the framework of those that are considered. The axis is powered up, by entering this 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 recording the data in the MySQL database (via the “Insert” tab), the program will inform you that in animals a row of identifier values ​​has been added 1. And a few minutes below the editor window will display the code that the shell generated for us and sent to server B D .

The code will be:

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

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

Let's read more about it. In SQL, to insert a new row into a table, the INSERT operator is used. This notifies the server that the database table (my_db1 . animal) needs to insert values ​​(VALUES (NULL, 'Cat')) into the id and name fields.

Please note that the id section is not a numeric value, but NULL, for which we have enabled auto-completion (auto-increment).

How to insert a record for additional help PHP

Everything we look at is merely a “prelude” to the main action, in which the highest level of server-side PHP programming enters the scene. For the most part, MySQL as a DBMS has developed such expansion in Merezhi.
The connection between these two Internet technologies has inspired most of the world's Internet. Wherever you look, you will see them: in current CMSs, “home-written” engines, and on the server.

It’s not surprising that MySQL PHP provides many useful functions for recording data. Ale mi zupinimos on the most important of them. The axis is the code that adds a new “creature” to the animals table. If you try really hard, you can catch an entire animal 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 inserted into a PHP file and placed on the server side.

The additional function mysql_connect() allows us to connect to the MySQL database server. As arguments, the function accepts the host, the name of the DBMS server, the password and the name of the database to which you need to connect. We have entered an empty password, so we are installing the vikory server on the local (client) machine.

To demonstrate all applications, writing to the MySQL database using additional PHP, we created a “gentleman’s dial” from Denver. This includes a local Apache server, a MySQL server, phpMyAdmin and a number of other useful features for creating and testing program code.

Then, in a logical block, we verified the authenticity of the connection to the database server. After that, the mysql_select_db() function designated the database to which we will connect. For the additional function mysql_query(), we launched a search for SQL queries, records in the $query_str variable. And finally, the installed connection was closed (mysql_close() function). Now, if we take a look at our animal table (animal table), we can see a new “vikhovant” there.

For this, I’ll write it into MySQL PHP “lovingly” by adding all the necessary set of functions. It's a shame why newbies are complaining about SQL errors in program code - incorrect spelling of queries, broken syntax, and misprinting of characters for escaping.

To avoid the appearance of a strange “gray” hair on your head, it is better to check the correctness of the spelling with the help of phpMyAdmin. To do this, place the SQL code in the program editor and run it on your account. If this is not the case, then the program will continue to “bark”, resulting in the notification of the red color and, in each case, the need for mercy.

As you know, with the help of MySQL you can collect your animal and correctly change the words of any song. And PHP is ideal for writing to the MySQL database, so we would like you to establish a “close” friendship with my “great” program!