Steps of using MySql db from Php.
- Create a database connection.
- Select a database.
- Perform a SQL query.
- Perform your operations on SQL query results.
- Close database connection.
Php uses following funtions for making a databse connection .
mysql_connec(server,user,pwd,newlink,clientflag) // Non persistance connection
mysql_pconnec(server,user,pwd,newlink,clientflag) // Persistance connection.
Parameter | Description |
---|---|
server | Optional. Hostname of server. Default value is "localhost:3306" |
user | Optional. Username on the database. Default value is the name of the user that owns the server process |
pwd | Optional. Username on the database. Default is "" |
newlink | Optional. Reuse database connection created by previous call to mysql_connect |
clientflag | Optional. Can be a combination of the following constants:
|
2. Select a database.
Php use following function for selecting database.
mysql_select_db(database,connection)
database -- Specifies the database to select.
connection -- (Optiona)l. Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.
3. Perform a SQL query.
Php have following function to executes a query on a MySQL database.
mysql_query(query,connection)
query -- SQL query to execute (eg. SELECT query, UPDATE query...etc);
connection -- (Optional) MySQL connection name. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.
This function returns the query handle for SELECT queries, TRUE/FALSE for other queries, or FALSE on failure.
4. Close database connection.
Php uses following function for closing a connection.
mysql_close(connection) // function closes a non-persistent MySQL connection.
Sample Code :
<?php
$con = mysql_connect("server","username","password");
if (!$con) {
die('Unable to connect: ' . mysql_error());
}else{
mysql_select_db('database_name');
}
$sql = "SELECT * FROM Customer";
mysql_query($sql,$con);
// do some more precessing ..
mysql_close($con);
?>