PHP Modules Tutorials - Herong's Tutorial Examples - v5.18, by Herong Yang
MySqlLoop.php - MySQL Functions Test
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 2009-2015 (c) HerongYang.com. All Rights Reserved.
#
$con = mysqli_connect("localhost", "root", "");
$rs = mysqli_query($con,'DROP DATABASE MyBase');
$rs = mysqli_query($con,'CREATE DATABASE MyBase');
if (!$rs) {
echo "Error: Unable to create the database.\n";
echo mysqli_connect_errno()." - ".mysqli_connect_error()."\n";
exit;
}
$rs = mysqli_query($con,'USE MyBase');
print "Creating a table...\n";
$rs = mysqli_query($con,'CREATE TABLE MyTable (ID INTEGER,'
.' Value INTEGER)');
$n = 100;
$i = 0;
print "Inserting some rows to the table...\n";
while ($i < $n) {
$rs = mysqli_query($con,'INSERT INTO MyTable VALUES ('.$i.', '
.rand(0,$n-1).')');
$i++;
}
print "Query some rows from the table...\n";
$rs = mysqli_query($con,'SELECT * FROM MyTable WHERE ID < 10');
print " ".mysqli_field_name($rs,0)." "
.mysqli_field_name($rs,1)."\n";
while ($row = mysqli_fetch_array($rs)) {
print " ".$row[0].' '.$row[1]."\n";
}
mysqli_free_result($rs);
mysqli_close($con);
function mysqli_field_name($result, $field_offset) {
$properties = mysqli_fetch_field_direct($result, $field_offset);
return is_object($properties) ? $properties->name : null;
}
?>
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
Table of Contents
Introduction and Installation of PHP
Managing PHP Engine and Modules on macOS
Managing PHP Engine and Modules on CentOS
DOM Module - Parsing HTML Documents
GD Module - Manipulating Images and Pictures
►MySQLi Module - Accessing MySQL Server
MySQLi Module Configuration and Database Access
mysqli_connect() and Other MySQL Functions
►MySqlLoop.php - MySQL Functions Test
OpenSSL Module - Cryptography and SSL/TLS Toolkit
PCRE Module - Perl Compatible Regular Expressions
SOAP Module - Creating and Calling Web Services
SOAP Module - Server Functions and Examples