You are on page 1of 2

Step 1 - Connecting to MySQL

Connecting to a MySQL database in PHP requires the following information to establish the
database username
database name
a) Connecting to the MySQL database server: The mysql_connect () function establish the
connection to the MySQL server.
mysql_connect ("server-name", "username", "password");
$dbConnection = mysql_connect ("localhost", "root", "toor")
or die(Failed to connect with server);
b) Selecting the MySQL database: The mysql_select_db() function selects the specified.
mysql_select_db("payroll") or die(Resource not available);
c) Closing the connection: The mysql_close() function closes the opened database handle and
release all resources.
Step 2 - Retrieving data from the database
To retrieve data from table, after getting connected, a SELECT SQL statement is issued to the
database to get all records from a table in the database.
a) Sending select query command to the server and store the response: The mysql_query()
function is used for this task
$var = mysql_close("select_query");
$departments = mysql_close("select * from dept");
Here $department shall hold the records returned by the function or null in case no record were
fetched from the table.
b) Fetching records from the resultset: The following functions in PHP can be used to retrieve data
from a MySQL database result set
mysql_fetch_assoc() - Fetch a result row as an associative array
mysql_fetch_row() - Fetch a result row as an enumerated array
mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
$row = mysql_fetch_assoc($departments);
$row = mysql_fetch_row($departments);
$row = mysql_fetch_array($departments);
c) Fetching record values: The row variable is created as an array, from which values can be
accessed either by index or the field name
echo $row[0];
echo $row[dname];
d) Fetching all record values: The fetch functions returns with an array if there is a record in the
result set and returns false if no more records are available. So creating a while loop is very
simple as here:
$result = mysql_query("SELECT * FROM dept");
while ($row = mysql_fetch_assoc($result)){
echo $row[dname] . located at . $row [loc]."<br/>";
Step 4 - Insert, update, and delete records
a) Inserting data into the database: To insert new records into MySQL database, an insert sql
statement issued to the mysql_query() function again.
$sql = "INSERT INTO dept (deptid,dname,loc)
VALUES (null,'Sales','New York')";
$result = mysql_query($sql);
b) Updating a record: The update is almost the same as the insert only need to change the
$sql = "UPDATE dept SET loc=Una WHERE deptid=10";
$result = mysql_query($sql);
c) Deleting a record: Only the sql needs to be changed:
$sql = "DELETE FROM users WHERE name='Tom'";
$result = mysql_query($sql);
An error shall be reported properly