This section provides a tutorial example on how to use MySQL functions to connect to a MySQL server, and run SQL statements to create a table, insert rows and fetch rows with the MySQL server.
To show you how some of those MySQL functions should be used, I wrote this simple script, MySqlLoop.php:
<?php # MySqlLoop.php
# Copyright (c) 2002 by Dr. Herong Yang
#
$con = mysql_connect('localhost');
$rs = mysql_query('DROP DATABASE MyBase');
$rs = mysql_query('CREATE DATABASE MyBase');
$rs = mysql_query('USE MyBase');
print "Creating a table...\n";
$rs = mysql_query('CREATE TABLE MyTable (ID INTEGER,'
.' Value INTEGER)');
$n = 100;
$i = 0;
print "Inserting some rows to the table...\n";
while ($i < $n) {
$rs = mysql_query('INSERT INTO MyTable VALUES ('.$i.', '
.rand(0,$n-1).')');
$i++;
}
print "Query some rows from the table...\n";
$rs = mysql_query('SELECT * FROM MyTable WHERE ID < 10');
print " ".mysql_field_name($rs,0)." "
.mysql_field_name($rs,1)."\n";
while ($row = mysql_fetch_array($rs)) {
print " ".$row[0].' '.$row[1]."\n";
}
mysql_free_result($rs);
mysql_close($con);
?>
Note that if the connection resource is not specified in a query call, the last connection
resource will be used. If you run this script, you will get something like:
Creating a table...
Inserting some rows to the table...
Query some rows from the table...
ID Value
0 14
1 91
2 84
3 16
4 88
5 51
6 12
7 19
8 39
9 5