|
|
|
Openning a connectionOpening a connection to MySQL database from PHP is easy. Just use the mysql_connect() function like this$dbhost is the name of MySQL server. When your webserver is on the same machine with the MySQL server you can use localhost or 127.0.0.1 as the value of $dbhost. The $dbuser and $dbpass are valid MySQL user name and password. Don't forget to select a database using mysql_select_db() after connecting to mysql. If no database selected your query to select or update a table will not work. Closing the ConnectionThe connection opened in a script will be closed as soon as the execution of the script ends. But it's better if you close it explicitly by calling mysql_close() function.To create a database use the mysql_query() function to execute an SQL query like this QueriesPlease note that the query should not end with a semicolon. To create tables in the new database you need to do the same thing as creating the database. First create the SQL query to create the tables then execute the query using mysql_query() function.Inserting data to MySQL is done by using mysql_query() to execute INSERT query. Note that the query string should not end with a semicolon. Below is an example of adding a new MySQL user by inserting a new row into table user in database mysql : Using PHP you can run a MySQL SELECT query to fetch the data out of the database. You have several options in fetching information from MySQL. PHP provide several functions for this. The first one is mysql_fetch_array()which fetch a result row as an associative array, a numeric array, or both. Below is an example of fetching data from MySQL, the table contact have three columns, name, subject and message. Of course you can also do it like this Other sql queries can also be used, some examples are: |
|