Someone recently sent me a message asking me to explain how to use a database with PHP. So, here it is as an article so everyone can take advantage of it.
The following 5 things will be enough for a lot of PHP programmers (and get you started).
- Connect to MySQL
- Select the database you want to work with
- Read information from it
- Insert, update or delete information in it
- Close the connection
Connecting To MySQL And Selecting The Database
Regardless of what you want to do (insert, select, update or delete) you will always need to first connect to the MySQL server and select the database you want to work with.
Let's say we want to maintain a list of contacts. We want to store their first name, last name and their email. For this, we will need to create a table. Then, we can insert our contacts in it and get them when we need to
Creating A Table
Now that we have the table, let's insert a contact in there.
Inserting Into The Database
Now that we have a table and we have some data in it. Let's try reading that data.
\nLast Name:{$row['last_name']}
\n Email: {$row['email']} \n\n";
}
When you open a persistent connection, it stays open. When you fresh the page or when you need to connect to the DB again, the same connection is used instead of creating a new one, which is good because you don't want to exhaust all your available connections. So, you will usually not have to close the connection. However, if for some unforeseen reason you need to close a connection to MySQL, here's how to do it.
Closing The Connection
Leave a Reply