Insert Data into MySQL Database – Php Basics for Beginners

This will be a brief 101 post for inserting data into MySQL database using Php.

I find it very easy and straight forward to insert data into MySQL database using Php, compared to inserting data into MS SQL using C#.

Below you will see that too. Just 3 lines and it is done.

Insert Data into MySQL Database

1- $my_connection = mysqli_connect (“Hostname”, “Username”, “Password”, “DB Name”) or die (mysql_error());

2- $my_queryString = ” INSERT INTO ┬áTableName (Col1,Col2,…,Coln) VALUES (‘Val1′,’Val2′,…,’Valn’)”;

3- mysqli_query ($my_connection, $my_queryString);

And that is all you need to insert data into MySQL database.

Now a little explanation for the beginners.

mysqli_connect: The “mysqli_connect()” function opens a new connection to the MySQL server.

You provide 4 parameters to get the connection:

Hostname: Name of the host machine where the MySQL server resides

Username: Name of the user with authentication to write to the database

Password: Password of the user

DB Name: Name of the database that we are going to manipulate after successful connection

There are also “port” and “socket” parameters┬ábut as a beginner you don’t need them right now.

mysqli_query: The “mysqli_query()” function performs a query against the database.

You provide 2 parameters to execute the query:

Connection: This is the connection object we will use to connect to the server

Query: This is the query we want to execute on our table(s)

There is also an optional “resultmode” parameter┬ábut as a beginner you don’t need it right now.

die:

The “die()” function prints a message and exits the current script.

So the “or die (mysql_error())” part in our first line means “If you can’t connect print the MySQL error message and exit”.

This should be enough for a 101 lesson on how to insert data into MySQL database.

If you need more info you can check out sites like w3schools.

Hope this helps.
Good Luck,
Serdar

Leave a Reply

Your email address will not be published. Required fields are marked *