PHP 5 and Mysql Database
PHP 5 and Mysql Database
Create a Table
b)
Create a Database
4)
5)
6)
7)
8)
9)
1:
2:
What is MySQL?
MySQL
MySQL
MySQL
MySQL
MySQL
MySQL
MySQL
MySQL
MySQL
The data in MySQL is stored in tables. A table is a collection of related data, and it consists of columns and
rows.
Databases are useful when storing information categorically. A company may have a database with the
following tables:
Employees
Products
Customers
Orders
PHP + MySQL
PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix
platform)
Queries
A query is a question or a request.
We can query a database for specific information and have a recordset returned.
Look at the following query (using standard SQL):
Syntax
mysqli_connect(host,username,password,dbname);
Parameter
Description
3:
username
password
dbname
Note: There are more available parameters, but the ones listed above are the most important.
In the following example we store the connection in a variable ($con) for later use in the script:
<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Close a Connection
The connection will be closed automatically when the script ends. To close the connection before, use the
mysqli_close() function:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
4:
Create a Database
The CREATE DATABASE statement is used to create a database in MySQL.
We must add the CREATE DATABASE statement to the mysqli_query() function to execute the command.
The following example creates a database named "my_db":
<?php
$con=mysqli_connect("example.com","peter","abc123");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql)) {
echo "Database my_db created successfully";
} else {
echo "Error creating database: " . mysqli_error($con);
}
?>
Create a Table
The CREATE TABLE statement is used to create a table in MySQL.
We must add the CREATE TABLE statement to the mysqli_query() function to execute the command.
5:
6:
The following example creates a table named "Persons", with three columns: "FirstName", "LastName"
and "Age":
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create table
$sql="CREATE TABLE Persons(FirstName CHAR(30),LastName CHAR(30),Age INT)";
// Execute query
if (mysqli_query($con,$sql)) {
echo "Table persons created successfully";
} else {
echo "Error creating table: " . mysqli_error($con);
}
?>
Note: When you create a field of type CHAR, you must specify the maximum length of the field, e.g.
CHAR(50).
The data type specifies what type of data the column can hold. For a complete reference of all the data
types available in MySQL, go to our complete Data Types reference.
Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
Example
In the previous chapter we created a table named "Persons", with three columns; "FirstName",
"LastName" and "Age". We will use the same table in this example. The following example adds two new
records to the "Persons" table:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)
7:
8:
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
When a user clicks the submit button in the HTML form, in the example above, the form data is sent to
"insert.php".
The "insert.php" file connects to a database, and retrieves the values from the form with the PHP $_POST
variables.
The mysqli_real_escape_string() function escapes special characters in a string for security against SQL
injection.
Then, the mysqli_query() function executes the INSERT INTO statement, and a new record will be added
to the "Persons" table.
Here is the "insert.php" page:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
Syntax
SELECT column_name(s)
FROM table_name
9:
10:
Example
The following example selects all the data stored in the "Persons" table (The * character selects all the
data in the table):
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>
The example above stores the data returned by the mysqli_query() function in the $result variable.
Next, we use the mysqli_fetch_array() function to return the first row from the recordset as an array.
Each call to mysqli_fetch_array() returns the next row in the recordset. The while loop loops through all
the records in the recordset. To print the value of each row, we use the PHP $row variable
($row['FirstName'] and $row['LastName']).
The output of the code above will be:
Peter Griffin
Glenn Quagmire
Quagmire
Peter
Griffin
11:
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
To learn more about SQL, please visit our SQL tutorial.
To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.
Example
The following example selects all rows from the "Persons" table where "FirstName='Peter'":
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons
WHERE FirstName='Peter'");
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
?>
The output of the code above will be:
Peter Griffin
12:
13:
Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
To learn more about SQL, please visit our SQL tutorial.
Example
The following example selects all the data stored in the "Persons" table, and sorts the result by the "Age"
column:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons ORDER BY age");
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br>";
}
mysqli_close($con);
?>
The output of the code above will be:
Glenn Quagmire 33
Peter Griffin 35
14:
SELECT column_name(s)
FROM table_name
ORDER BY column1, column2
Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or
records that should be updated. If you omit the WHERE clause, all records will be updated!
To learn more about SQL, please visit our SQL tutorial.
To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.
Example
Earlier in the tutorial we created a table named "Persons". Here is how it looks:
FirstName
LastName
Age
Peter
Griffin
35
Glenn
Quagmire
33
LastName
Age
Peter
Griffin
36
Glenn
Quagmire
33
Syntax
DELETE FROM table_name
WHERE some_column = some_value
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or
records that should be deleted. If you omit the WHERE clause, all records will be deleted!
To learn more about SQL, please visit our SQL tutorial.
To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.
15:
16:
Example
Look at the following "Persons" table:
FirstName
LastName
Age
Peter
Griffin
35
Glenn
Quagmire
33
The following example deletes all the records in the "Persons" table where LastName='Griffin':
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"DELETE FROM Persons WHERE LastName='Griffin'");
mysqli_close($con);
?>
After the deletion, the table will look like this:
FirstName
LastName
Age
Glenn
Quagmire
33
17:
Note that this configuration has to be done on the computer where your web site is located. If you are
running Internet Information Server (IIS) on your own computer, the instructions above will work, but if
your web site is located on a remote server, you have to have physical access to that server, or ask your
web host to to set up a DSN for you to use.
Connecting to an ODBC
The odbc_connect() function is used to connect to an ODBC data source. The function takes four
parameters: the data source name, username, password, and an optional cursor type.
The odbc_exec() function is used to execute an SQL statement.
Example
The following example creates a connection to a DSN called northwind, with no username and no
password. It then creates an SQL and executes it:
$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
Retrieving Records
The odbc_fetch_row() function is used to return records from the result-set. This function returns true if it
is able to return rows, otherwise false.
18:
The function takes two parameters: the ODBC result identifier and an optional row number:
odbc_fetch_row($rs)
$compname=odbc_result($rs,1);
The code line below returns the value of a field called "CompanyName":
$compname=odbc_result($rs,"CompanyName");
odbc_close($conn);
An ODBC Example
The following example shows how to first create a database connection, then a result-set, and then
display the data in an HTML table.
<html>
<body>
<?php
$conn=odbc_connect('northwind','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
19: