Menu
Is free
check in
the main  /  Navigators / Adding to MySQL via PHP. How to record in MySQL database using PHP code

Adding to MySQL via PHP. How to record in MySQL database using PHP code

Comments transferred from blog

SERGEY
09/14/2016 at 01:25
Good afternoon!
Interested in such a question: how to easily organize data storage and program settings without using the database? I do not want to get tied to MySQL or Access ..

Admin.
09/14/2016 at 22:14.
Hello!

Properties.settings.
App.config
XML file.
Serialization
Try to choose something from this from the list.

Nikolai
09/16/2016 at 02:28.
Hello, how to remove the selected string in DataGridView from DataGridView and PhpmyAdmin.

PhpmyAdmin? This is just a shell to work with the database, can you explain?

Nikolai
09/18/2016 at 02:24
It is necessary that the dedicated string would be removed from DataGridView and from the database.

Admin.
09/19/2016 at 07:00
How to delete a string in the MySQL database - added an article.

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

DIMA
09/20/2016 at 10:24
Hello, can this method Implement 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 the database of System.Windows.Forms.TextBox, Text: Ge

To the stack, this (ge) to the end it is written the gene. At least in the table settings, the text is specified. The genet should be fit further. I bring this table to my program and it turns out that it displays me all this unnecessary text.

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

In TextBox1 I enter a name: gene.

SQL query: "INSERT INTO Name Table Values \u200b\u200b(TextBox1, ..)"; Result: System.Windows.Forms.TextBox.

And you need to transmit: "Insert Into The name of the Values \u200b\u200btable (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. And how to implement adding to database via TextBox?

Admin.
09/26/2016 at 20:53
All the same in principle. For example, take the latest example, you need:

// Create parameters and add them to the CMD.parameters.AdDWithValue collection ("@ name", textbox1.text); cmd.parameters.addwithvalue ("@ LastName", textbox2.text);

now Parameters: Name and LastName Get values \u200b\u200bentered in TextBox-s and transmit them to the database

Linara
09/27/2016 at 17:45.
Hello, how are the selected string in DataGridView and phpMyadmin?

Admin.
09/29/2016 at 02:06.
I do not know how you can highlighted the line in phpmyAdmin. And in DataGridView, for example, this can be done using the selectionchanged event.

Psh.
09/30/2016 at 03:48.
2 cable:
If you want to edit the rows so much, take the A la Hedisql tool, configure and change the lines.

2Admin.
Good day! Thanks for the materials - everything is very cool)
Question: I add data to this request (it is test):

String SQL \u003d "Insert Into Users (` Fio`, `Tour`,` count`, `Cost`,` date`, `Passport`,` Birth`) Values \u200b\u200b("Kolyan", "Moscow", "1 + 1 ", 1100," 2011-11-11 "," 1111 1111 "," 9.11.1900 ");";

Data is made all ok, but in the database (mysql) instead of Cyrillic turn out to be "????".

Visual Studio said that System.String is a sequence of Unicode.

Also tried:

Alter Database `Test` Collate" koi8R_GENERAL_CI "; ALTER TABLE `Users` Collate \u003d" koi8r_general_ci "; Alter Database `Test` Collate" UTF8_Unicode_ci "; Alter Table `Users` Collate \u003d" UTF8_Unicode_ci ";

But does not help ..
What can be wrong? Different VS encoding and database? Or what?
Could send that read / change.
Thank you

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

In the database (and in the table), the matching utf_general_ci

Is there such a comparison? Perhaps UTF8_GENERAL_CI?

Usually create a MYSQL database choosing a UTF8_GENERAL_CI comparison, so there are no problems with Cyrillic, unless the client come from the client to the server.

Collation is used for comparison, and in this case the encoding is important (Charset). Therefore, first you need to make sure that it is set on the server correctly, for example in UTF8, and not Latin1.

When you connect through .NET connector (default) used Latin1, so it is sometimes necessary to explicitly specify in the connection string UTF8:

MysqlConnection Mycon; MyCon \u003d New MySqlConnection ("Server \u003d 127.0.0.1; uid \u003d vasya; pwd \u003d 123; database \u003d test; Charset \u003d UTF8;"); // MysqlConnectionStringBuilder: mysqlcsb.characterset \u003d "UTF8";

Psh.
10/01/2016 at 11:34.
You are right, described, UTF8_GENERAL_CI!
Yes helped,; Charset \u003d UTF8;
Thanks OGMNO!

Sergiy.
10/02/2016 at 11:02.
Thanks for the working example, right. Question
I created a text field to which I would like to enter a database address, but I do not know how to substitute this data here

String Constr \u003d " [Email Protected]; User \u003d Test; "+
"Database \u003d Test; password \u003d test;";
Please tell me how to insert data from text fields in Windows Form into this design ....

Admin.
03.10.2016 at 11:50
"[Email Protected]; User \u003d ...
In general, it is better to use the properties in this article as in this article, or the String.Format () method

OLGA2203.
05/15/2017 at 20:14

String Connect \u003d "Server \u003d 127.0.0.1; port \u003d 3306; Database \u003d Base; Data Source \u003d localhost; user \u003d root;"; MySqlConnection CON \u003d New MySqlConnection (Connect); con .Open (); // Install the connection to the database. Mysqlcommand cmd \u003d new mysqlcommand (); cmd.commandText \u003d @ "Insert Into Tovar (ID, Category, Name, Trademark, Price, Photo, Size, Color, Material, Count) Values \u200b\u200b(@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 \u003d con; cmd.executenonquery (); MessageBox.Show ("Addition was successful", "Addition was successful", MessageBoxButtons.ok, MessageBoxicon.asterisk);

The error "Column 'ID' Cannot Be Null" is issued, remove the addition of the ID to the column - the same thing about the next column writes, etc.
If you put any constant values \u200b\u200bin brackets in Values, the string is added to the database.
Tell me, please, what's the problem? I need to record data and values \u200b\u200bin the database

Last updated: 1.11.2015

To add data to use the expression "Insert":

$ Query \u003d "Insert Into Tovars Values \u200b\u200b(NULL," Samsung Galaxy III, "samsumg") ";

The "INSERT" expression inserts one line into the table. After keywords Into indicates the name of the table, and after Values \u200b\u200bin brackets indicate a set of values \u200b\u200bfor all columns. Since we have three columns in the table, we specify three values.

Since in the last topic when creating a table, we indicated the following column sequence: ID, NAME, COMPANY, then in this case, the NULL value is transmitted to the ID column, for Name - "Samsung Galaxy III", and for the company - "samsumg".

Since the ID column is defined as AUTO_INCRement, we do not need to specify a certain numeric value for it, and you can pass the NULL value, and MySQL assigns the following accessible value.

Now consider adding data to the example. Create a file create.php. With the following contents:

Data added";) // Close the connection of MySQLI_Close ($ Link);)?\u003e

Add a new model

Enter the model:

Manufacturer:

Here, the interaction code with the database is combined with the functionality of forms: with the help of the form, we enter the data to add to the database.

Security and MySQL

Here we used the mysqli_real_escape_string () function. It serves to screen symbols in a row, which is then used in sQL request. As parameters, it accepts an object of connection and a string that needs to be shielded.

Thus, we apply the screen shielding actually twice: first for SQL expressions using the mysqli_real_escape_string () function, and then for HTML using the HTMLENTIES () function. This will allow us to defend directly from two types of attacks: XSS attacks and SQL injections.

In this article we will discern, perhaps, one of the most important SQL queries. it requests for adding and deleting records from the database table. Since, very often has add new entries to the table, and do it in automatic modeThis material is required to be studied.

To start SQL request for adding new recording in Table:

INSERT INTO USERS (LOGIN, PASS) VALUES ("TestUser", "123456")

When adding an entry, the team comes at the beginning. " INSERT INTO", Then the name of the table in which we insert the record. Next goes to the heads of the fields, which we want to fill. And then in parentheses after the word" values."We start listed the values \u200b\u200bof those fields that we have chosen. After executing this request, a new entry will appear in our table.

Sometimes required refresh entry in the tablefor this there is the following SQL request:

Update Users Set Login \u003d "TestUser2", pass \u003d "1234560" WHERE LOGIN \u003d "TestUser"

This request is more difficult, as it has a design " Where.", but about it just below. At first there is a team" Update.", then the name of the table, and after" SET."We describe the values \u200b\u200bof all the fields that we want to change. It would be simple, but the question arises:" What kind of recording should be updated?". For this exists" Where."In this case, we update the entry, the field" login."Which is important" Testuser.". Please note that if there are several such records, then absolutely everything will be updated! It is very important to understand, otherwise you risk losing your table.

Let's talk a little about " Where."In addition to simple checks on equality there are also inequalities, as well as logical operations: And. and Or..

Update Users Set Login \u003d "TestUser2", Pass \u003d "1234560" WHERE ID< 15 AND login="TestUser"

The SQL request Update those records id which are less 15 AND field " login." has the meaning " Testuser."I hope you dealt with the design" Where.", Because it is very important. It is" Where."Used by sampling records from tablesAnd this is the most part-to-use task when working with databases.

And, finally, simple SQL request to delete records from the table:

Delete from Users WHERE LOGIN \u003d "TestUser2"

After the team " Delete from."There is a name of the table in which you want to delete records. Then describe the" WHERE "design. If the record will comply with the conditions described, it will be deleted. Again, pay attention, depending on the number of records that satisfy the condition after" Where.", Any amount of their number can be deleted.


The lesson will be based on form feedback necessary virtually any site.

Step one: Creating a database in Mysql

Open phpmyAdmin. (enters the base package Denwer`a), and create a database with the title" test_Base.", I choose the encoding" cP1251_GENERAL_CI".

Step second: Creating Table B. Mysql via SQL request

You can create a table, of course, with standard tools phpmyAdmin.But the structure of the table being created will be visible.

Create a table with the title " test_table"And with six fields with names:
"Name" - users will be stored here;
"Email" - addresses will be stored here electronic boxes users;
"Theme" - the subject of the message will be stored here;
"Message" - messages will be stored here;
"DATA" - the date of sending the message will be stored here;
"ID" - Identification number of the record (strings), key field.

SQL query:
CREATE TABLE TEST_TABLE (
ID Int (11) Not NULL AUTO_INCREMENT,
Name Varchar (255) Not NULL,
Email Varchar (255) Not NULL,
Theme Varchar (255) Not NULL,
Message TEXT NOT NULL,
DATA DATE NOT NULL,
PRIMARY KEY (ID)
);

Step Three: Creating a form

index.html:

Form with saving in MySQL

Example form with data saving in MySQL

























Sending request
Name:
E-mail:
Message subject:
Message:
























Step four: Creating a form handler " save_form.php."With the preservation of the data obtained in Mysql

save_form.php:





/ * MYSQL table in which data will be stored * /
$ table \u003d "test_table";

/ * Create a connection * /

/ * Determine the current date * /
$ cdate \u003d date ("Y-M-D");

/ * Make a request to insert information in the table
Name ... Date - the name of the specific fields in the database;
In $ _post ["test_name"] ... $ _post ["test_mess"] - these variables contain data obtained from the form * /
$ Query \u003d "Insert Into $ Table Set Name \u003d" ". $ _ POST [" test_name "]." ", email \u003d". "$ _ post [" test_mail "]." ",
Theme \u003d "". $ _ post ["test_theme"]. "", message \u003d "". $ _ post ["test_mess"]. "", Data \u003d "$ CDATE" ";

/ * Close the connection * /
mysql_close ();

/ * In case of successful saving, display the message and refund link * /
Echo ("


Data successfully saved!



come back
");

Pitch Fifth: Conclusion of saved data " view_data.php."

view_data.php:

/ * Connect the database * /
$ hostname \u003d "localhost"; // Title / Server Path, with MySQL
$ username \u003d "root"; // username (in denwer`e by default "root")
$ password \u003d ""; // Password of the user (in denwer`e by default password is missing, this parameter can be left blank)
$ dbname \u003d "test_base"; // Database Name


$ table \u003d "test_table";

/ * Create a connection * /
MySQL_Connect ($ HostName, $ Username, $ Password) OR DIE ("I CALCE CONCEPT");

/ * Select the database. If an error occurs - output it * /
mysql_select_db ($ dbName) or DIE (mysql_error ());

/ * Making a request to extract data from the "Name" fields, "Email", "Theme",
"Message", "Data" table "test_table" * /
$ Query \u003d "Select ID, Name, Email, Theme, Message, Data from $ Table";

/ * Perform a request. If an error occurs - output it. * /


Echo ("

Data output from MySQL

Withdrawing previously saved data from the MYSQL table










");



Echo "

\\ n ";
Echo " \\ n ";
Echo " \\ n ";
Echo " \\ n ";
Echo " \\ n ";
Echo " \\ n ";
Echo " \\ N.\\ n ";
}

Echo ("

# date of the application Users names E-mail users Message subject Messages of users
"$ row [" id "].""$ ROW [" DATA "].". "$ ROW [" NAME "].". "$ ROW [" Email "].""$ row [" Theme "]."". $ row [" message "]."
\\ n ");

/ * Close the connection * /
mysql_close ();

Step Six: Deleting records from the database " del_data.php."

del_data.php:

/ * Connect the database * /
$ hostname \u003d "localhost"; // Title / Server Path, with MySQL
$ username \u003d "root"; // username (in denwer`e by default "root")
$ password \u003d ""; // Password of the user (in denwer`e by default password is missing, this parameter can be left blank)
$ dbname \u003d "test_base"; // Database Name

/ * MYSQL table in which data is stored * /
$ table \u003d "test_table";

/ * Create a connection * /
MySQL_Connect ($ HostName, $ Username, $ Password) OR DIE ("I CALCE CONCEPT");

/ * Select the database. If an error occurs - output it * /
mysql_select_db ($ dbName) or DIE (mysql_error ());

/ * If the removal link has been pressed, delete the entry * /
$ del \u003d $ Query \u003d "Delete from $ Table WHERE (id \u003d" $ del ")";
/ * Perform a request. If an error occurs - output it. * /
MySQL_Query ($ Query) OR DIE (mysql_error ());



/ * Perform a request. If an error occurs - output it. * /
$ Res \u003d MySQL_Query ($ Query) or DIE (mysql_error ());

$ row \u003d mysql_num_rows ($ RES);

/ * Display data from the table * /
Echo ("

Display and delete data from MySQL

Displays and delete previously saved data from the MYSQL table











");

/ * Data output cycle from the base of specific fields * /
While ($ row \u003d mysql_fetch_array ($ res)) (
Echo "

\\ n ";
Echo " \\ n ";
Echo " \\ n ";
Echo " \\ n ";
Echo " \\ n ";
Echo " \\ n ";
Echo " \\ n ";
/ * We generate a link to remove the field * /
Echo " \\ n ";
Echo "\\ n ";
}

Echo ("

# date of the application Users names E-mail users Message subject Messages of users Removal
"$ row [" id "].""$ ROW [" DATA "].". "$ ROW [" NAME "].". "$ ROW [" Email "].""$ row [" Theme "]."". $ row [" message "]."Delete
\\ n ");

/ * Close the connection * /
mysql_close ();

Step seventh: Editing and updating entries in the database " update_Data.php."

update_Data.php:

/ * Connect the database * /
$ hostname \u003d "localhost"; // Title / Server Path, with MySQL
$ username \u003d "root"; // username (in denwer`e by default "root")
$ password \u003d ""; // Password of the user (in denwer`e by default password is missing, this parameter can be left blank)
$ dbname \u003d "test_base"; // Database Name

/ * MYSQL table in which data is stored * /
$ table \u003d "test_table";

/ * Create a connection * /
MySQL_Connect ($ HostName, $ Username, $ Password) OR DIE ("I CALCE CONCEPT");

/ * Select the database. If an error occurs - output it * /
mysql_select_db ($ dbName) or DIE (mysql_error ());

/ * If the edit button has been pressed, make changes * /
if (@ $ submit_edit) (
$ Query \u003d "Update $ Table Set Name \u003d" $ test_name ", email \u003d" $ test_mail ", theme \u003d" $ test_theme ", message \u003d" $ test_mess "where id \u003d" $ update "";
/ * Perform a request. If an error occurs - output it. * /
MySQL_Query ($ Query) OR DIE (mysql_error ());
}

/ * We enter the $ RS variable the entire database * /
$ Query \u003d "Select * from $ table";
/ * Perform a request. If an error occurs - output it. * /
$ Res \u003d MySQL_Query ($ Query) or DIE (mysql_error ());
/ * We will find out the number of entries in the database * /
$ row \u003d mysql_num_rows ($ RES);

/ * Display data from the table * /
Echo ("

Editing and updating data

Editing and updating data in the MYSQL table


");

/ * Data output cycle from the base of specific fields * /
While ($ row \u003d mysql_fetch_array ($ res)) (
Echo "

\\ n ";
Echo " \\ n ";
Echo " \\ n ";
Echo " \\ n ";
Echo " \\ n ";
Echo "\\ n ";
Echo " \\ n ";
Echo "\\ n ";
Echo " \\ n ";
Echo "\\ n ";
Echo " \\ n ";
Echo "\\ n ";
Echo " \\ n ";
Echo "\\ n ";
Echo " \\ n ";
Echo "
# "$ row [" id "]."
"$ ROW [" DATA "]."
Username:
E-mail user:
Message subject:
Message:
\\ N \\ n ";
}

/ * Close the connection * /
mysql_close ();

Well, that's all, pleasant coding: 1133:

_________________________________

In this article, we will look at how to use PHP to insert rows to the MySQL database.

Step 1 - Creating a Table

First you need to create a table for data. it simple procedurewhich can be performed using PHPMYAdmin in the Hosting Control Panel.

After entering you phpMyadmin you will see such an interface:
Create a table with the student name in the U266072517__name database by clicking on the "Create Table" button. After that we will see new pageon which you specify all the necessary parameters of the table:

This is the most simple setupwhich can be used for the table and receiving for more information On the structure of tables / databases.

Column parameters:

  • Name is the name of the column that is displayed in the top of the table.
  • Type - type of column. For example, we chose VARCHAR because we will enter string values.
  • LENGTH / VALUES - Used to indicate the maximum length, which may be recorded in this column.
  • Index - We used the "primary" index for the "ID" field. When creating a table, it is recommended to apply only one column as a primary key. It is used to list entries in the table and is required when setting up the table. I also noted "A_i", which means "AUTO Increment" - the automatic assignment parameter of the recorder (1,2,3,4 ...).
    Click the Save button, and the table will be created.

Step 2. Writing a PHP code to insert data in MySQL.

Option 1 - Mysqli method

First you need to establish a connection to the database. After that, use the insert SQL request. Full sample code:

". mysqli_error ($ Conn);) Mysqli_Close ($ Conn);?\u003e

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

Let's start from line number 19:

$ SQL \u003d "INSERT INTO STUDENTS (Name, Lastname, Email) Values \u200b\u200b(" Thom "," Vial "," [Email Protected]")";

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

Next is the list of columns in which the values \u200b\u200bare inserted: Name, Lastname, Email. Data will be added in the specified order. If we wrote (email, lastname, name), the values \u200b\u200bwould be added in another order.

The next part is the VALUES operator. Here we specify the values \u200b\u200bfor columns: name \u003d Thom, LastName \u003d Vial, email \u003d [Email Protected]

We launched a request using PHP code. IN program code SQL requests must be shielded with quotes. The next part of the code (20-22 row) checks whether our request was successful:

if (Mysqli_Query ($ Conn, $ SQL)) (Echo "New RecordCreatedSuccessFully";)

This code displays a message about the successful query.

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

eLSE (Echo "error:". $ SQL. "
". mysqli_error ($ Conn);)

Option 2 - PHP data object method (PDO)

First, we need to connect to the database by creating a new PDO object. When working with it, we will use various PDO methods. Methods of objects are caused as follows:

$ The_object-\u003e The_Method ();

PDO allows you to "prepare" SQL code before it is executed. SQL request is evaluated and "corrected" before launching. For example, the simplest attack using SQL injection can be performed through a simple introduction of the SQL code in the form field. For example:

Since it is syntactically correct SQL- code, a comma point makes a drop database user_table with a new SQL query, and the custom table is deleted. Prepared expressions (related variables) do not allow the semicolon and quotation point to complete the source request. Therefore, the DROP DATABASE command will never be executed.

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

Correct code:

getMessage (); ) // Set the variables for the person we want to add $ first_name \u003d "thom" to the database; $ last_name \u003d "vial"; $ email \u003d " [Email Protected]"; // Create a variable that causes the Prepare database method () // SQL query that you want to perform is entered as a parameter, and the fillers are written as follows: Placeholder_name $ My_insert_statement \u003d $ My_DB_Connection-\u003e Prepare Name, LastName, Email) Values \u200b\u200b(: first_name ,: last_name ,: email) "); // Now we specify the script, which variable refers to each placeholder to use the BINDParam () method // The first parameter is a filler in the operator above , the second is a variable to which it must refer $ My_insert_statement-\u003e Bindparam (: first_name, $ first_name); $ My_insert_statement-\u003e BindParam (: Last_Name, $ Last_Name); $ My_insert_statement-\u003e BindParam (: email, $ email); // Perform a query using the data that has just been determined // Execute () Returns True if it is successful, and False, if not, providing you with the ability to display your own IF message ($ My_insert_statement-\u003e Execute ()) (Echo "New Reco. rdcreatedSuccessfully "; ) ELSE (Echo "Unable to CreateRecord";) // At this point, you can change these variables and execute the request to add other data to the Data to the Database $ first_name \u003d "John" database; $ last_name \u003d "smith"; $ email \u003d " [Email Protected]"; $ MY_INSERT_STATEMENT-\u003e EXECUTE (); // Perform again when the variable is changed if ($ My_insert_statement-\u003e Execute ()) (Echo" New RecordCreatedSuccessFully ";) Else (Echo" Unable to CreateRecord ";

In 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 estimates the data when the Execute method is reached. For the first time, when the script reaches the EXECUTE () method, it sees that $ first_name corresponds to "Thom". Then binds this value and starts the request. When the script reaches the second EXECUTE () method, it sees that $ first_name now corresponds to "John". After that connects this value and again starts a request with new values. It is important to remember that we once defined the request and re-use it with different data at different points of the script.
  • bINDVALUE () - This method evaluates the data as soon as BindValue () is achieved. Since for $ first_name, the "Thom" value was set to bindvalue (), it will be used each time the Execute () method is called for $ My_insert_statement.
    Please note that we re-use the $ first_name variable and assign it a new value for the second time. After starting the script in the database, both names will be specified, despite the fact that the $ first_name variable at the end of the script is "John". Remember that PHP checks the entire script before running it.

If you update the script to replace BindParam on BindValue, you insert twice into the "Thom Vial" database, and John Smith will be ignored.

Step 3 - confirmation of successful implementation and solving problems

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

Eliminating common mistakes

Mysqli.

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

The first part of the code is in order, the connection was successfully established, but the SQL request did not pass.

"Error: INSERT INTO STUDENTS (Name, Lastname, Email) Values \u200b\u200b(" Thom "," Vial "," [Email Protected]") 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 \u200b\u200b("Thom", "Vial", " [Email Protected]")" AT LINE 1 "

A syntax error has been made that caused a script failure. The error was here:

$ SQL \u003d "INSERT INTO STUDENTS (Name, Lastname, Email) Values \u200b\u200b(" Thom "," Vial "," [Email Protected]")";

We used curly brackets instead of normal. It is incorrect, and the script issued a syntactic error.

Pdo

In line 7 PDO connections for error mode set "Display All Exceptions". If another value is specified, and the request would not succeed, we would not receive any error messages.

This setting should be used only when developing the script. When it is activated, the database names and tables can be displayed that it is better to hide for security purposes. In the case described when, instead of conventional brackets used curly, the error message looks like this:

FATAL ERROR: UNCAGHTEXCEPTION "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 \u200b\u200b(" Thom "," Vial "," [Email Protected]")" AT LINE 1 "

Other possible problems:

  • The columns are incorrectly indicated (non-existent columns or spelling errors in their names).
  • One type of value is assigned another type column. For example, if you try to insert the number 47 in the Name column, we will get a mistake. In this column, you must use a string value. But if we pointed out a number in quotes (for example, "47"), it would work, because it is a string.
  • Attempting to enter data into a table that does not exist. As well as an admitted spelling error in the table name.

After successful data entry, we will see that they are added to the database. Below is an example of a table in which the data added.

Conclusion

In this article, we told how to use PHP to insert data into the MySQL database using Mysqli and PDO. And also on how to eliminate common errors. These knowledge will be useful in learning programming and when developing your own website.

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