Changes

Jump to: navigation, search

Using PHP with MySQL

2,696 bytes added, 15:40, 7 June 2007
Adding Records to MySQL Database using PHP
?>
</pre>
 
The above script will result in the following output:
 
<tt>
Array ( [name] => James Wilson [email] => [email protected] [account] => 00001111 ) <br>
</tt>
 
== Modifying and Deleting MySQL Records using PHP ==
 
Record can be similarly modified and deleted by constructing appropriate SQL DELETE and UPDATE commands and passing them through to the ''mysql_query()'' function. After the function has been called the ''mysql_affected_rows()'' function can cbe called to identify the number of rows affected by the change. ''mysql_affected_rows()'' accepts a single argument, the handle returned by the ''mysql_connect()'' function.
 
== Using PHP to get Information about a MySQL Database ==
 
PHP provides a number of usefuil functions for obtaining information about a MySQL database. It is possible to obtain a list of fields in a table using the ''mysql_list_fields()'' function. This function accepts three arguments, the database name, the table name and datbase handle returned by ''mysql_connect()''.
 
The number of fields in a table can be obtained using the ''mysql_num_fields()'' function. This function takes the resource identifier returned by ''mysql_list_fields()'' as an argument.
 
Once you have obtained the resource identifier from ''mysql_list_fields()'' you can use ''mysql_field_name()'', ''mysql_field_type()'', and ''''mysql_field_len()'' functions to get information about each field. All of these functions take the handle returned by ''mysql_list_fields()'' as the first argument and offset into the table of the field you wish to inspect. A ''for'' loop can be constructed using the result from ''mysql_num_fields()'' to iterate through all feilds as follows:
 
<pre>
<?php
 
$dbhandle = mysql_connect('localhost', 'phptest', '3579php');
 
if ($dbhandle == false)
{
die ("Unable to connect to MySQL Database<br>");
}
 
$db = mysql_select_db('PHPsampleDB');
 
if ($db == false)
{
die ("Unable to Select MySQL Database<br>");
}
 
$listhandle = mysql_list_fields ('PHPsampleDB', 'customer', $dbhandle);
 
$numfields = mysql_num_fields ($listhandle);
 
for ($i=0; $i<$numfields; $i++)
{
echo 'Name: ' . mysql_field_name($listhandle, $i) . '<br>';
echo 'Type: ' . mysql_field_type($listhandle, $i) . '<br>';
echo 'Length: ' . mysql_field_len($listhandle, $i) . '<br>';
}
 
?>
</pre>
 
When loaded into a browser the above exmaple will generate the following output:
 
<tt>
Name: name Type: string Length: 30<br>
Name: email Type: string Length: 30<br>
Name: account Type: string Length: 20<br>
</tt>

Navigation menu