PHP MySQL Introduction
What is MySQL
MySQL is a database. A database is a data storage area. [ For more on Database and Mysql follow this link ]In a database, there are sections. These sections are called tables. Just like HTML tables, database tables have rows, columns, and cells.
Databases are useful when storing information categorically. If you wanted to store information about a group of people, like employees in a company, a database would let you group the employees into separate tables.
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data.
Below is an example of a table called "Persons":
LastName
|
FirstName
|
Address
|
City
|
Hansen
|
Ola
|
Timoteivn 10
|
Sandnes
|
Svendson
|
Tove
|
Borgvn 23
|
Sandnes
|
Pettersen
|
Kari
|
Storgt 20
|
Stavanger
|
The table above contains three records (one for each person) and four columns (LastName, FirstName, Address, and City).
Queries
A query is a question or a request.
With MySQL, we can query a database for a specific part of it and have a result set returned.
A query like this:
SELECT LastName FROM Persons
|
Gives a result set like this:
LastName
|
Hansen
|
Svendson
|
Pettersen
|
PHP MySQL Connect
Connect to a MySQL Database
Before accessing your database, you must make a connection to it.In PHP this is done with the mysql_connect() function.
The mysql_connect() Function
The syntax below shows a simple way of opening a MySQL connection.Syntax
mysql_connect(server,user,password);
|
Parameter
|
Description
|
server
|
Optional. Specifies the server to connect to (can also include a port number. e.g. "hostname:port" or a path to a local socket for the localhost). Default value is "localhost:3306"
|
user
|
Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process
|
password
|
Optional. Specifies the password to log in with. Default is ""
|
Example
In this example we store the connection in a variable for later use in the script.The "die" part of the code is an error check.
This is how a database connection is normally opened in a PHP script:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
?>
|
Closing a Connection
The connection will be closed as soon as the script ends. To close the connection before, use mysql_close().
You may like:
0 comments:
Post a Comment