This interaction between php and mysql has become quite famous since the language and the database are widely used Web now, and they are fairly simple to master.
Explanations
What is a database?
A database, as its name suggests, is used to store data.
For example, if each load of your web page, you want to save information from visitors to make the latest statistics, or if (another example) you want to make any form to your site, then you'll need a database to store all the information.
A database consists generally of tables that contain records. These records are broken down into fields. Example: a database called "mon_site" may contain a table visitors and a table "members" if I resumed the previous example. The fields of the table "members" can be: id, name, surname, city, date_inscription, etc..
We will not see how to use mysql itself, as this is not the goal. But it is clear that we must create the structure of your database before you can use with PHP. For this you can use the now famous Hawaii for example, which is an outline of a concrete table "sites":
2 - Connect to a database with php mysql
To connect to a php mysql, use the function mysql_connect () as in the example below. Usually we put the code below into a separate file that is included in all pages that need the database. (with include ())
Code:
<?. Php
$ dbhost = "localhost", / / address of the server mysql
$ dbuname = "Damien"; / / username mysql
$ dbpass = "7kuPlKKv8"; / / password mysql
$ dbname = "monsite_www"; / / name of the database to which you connect
$ idbase = mysql_connect ($ dbhost, $ dbuname, $ dbpass); / / logs on ...
mysql_select_db ($ dbname); / / selected on the basis of data
>
So, with this you are connected to your MySQL database, it can only do what we call queries, ie to trade standards on the database, including we will see the most common combinations: add, delete, modify, view recordings.
Note that you have all the complete syntax for functions that can be used in php mysql
3 - Add a record in mysql
To queries mysql, know first that a php recurrent, it is the function mysql_query (). This function will be setting an SQL, if you already know the syntax of SQL another database, the task will be very simple for you, if not read well after ;-)
To add a record with php mysql, php instruction look like this:
Code:
<?. Php
$ reqadd = mysql_query ( "INSERT INTO members (name, surname, date_inscription) VALUES ( 'Desrousseaux', 'Damien', now ())) / / add a record (a) in the table" members "
/ / Write the function mysql now () which inserts the current date
>
The result of the request contained in $ reqadd be TRUE if the request was executed correctly or FALSE if it is not good. In the case of false, you can do an echo mysql_error (); "just to view the details of the error, and so easy to debug your script.
Bookmarks