Or... What You need on every page that accesses the MySQL database
All the Examples on this page can be found in the php sample site
The Bare Bones
To access a MySQL database, you must:
- Connect to a database server
- Connect and open a database connection
- Perform a query on that database
To Connect to a Database Server:
$dbconnection = mysql_connect( server address, username, userpassword);
If it was able to connect:
The function mysql_connect returns a "resource ID" (or pointer) to the database server if the connection was able to be made. this ID is stored in the variable $dbconnection.
If it was NOT able to connect to a server:
If the connection was not available, then $dbconnection variable would contain FALSE.
Why is this important?
The resource ID may be used to tell future queries and updates to the database which database server connection to use. It is optional in applications with only 1 database server, but is a good practice to use.
Open and Connect to a Database on That Server
$db = mysql_select_db("databasename here", optional db server id here ); // db server id is the resource id from the mysql_connect() statement above
If it was able to open and access the database:
Variable $db will contain a "resource ID" (or pointer) pointing to that database
If it was NOT able to connect
Variable $db will be FALSE.
Why is this important?
A database server may have hundreds of separate databases on that single server. this tells the database server WHICH database you wish to connect to. Even your username/password may have access to more than 1 database on a given database server.
Example of connects to Database Server and Database
Results in browser:
Query the Database
$result = mysql_query("put your database SQL statement here", optional db server id here);
mysql_query is the primary way of getting information out of your database and putting information back into your database!
What is returned?
What is returned and stored in the variable $result depends on the type of query that mysql_query() performs
for INSERT, UPDATE, DELETE queries, mysql_query() will return the number of rows that were affected by the SQL statement, or it will return FALSE if the SQL statement could not be performed
If the mysql_query() contains a SELECT query, then $result will contain the set of records that the select statement found or it will return FALSE if the query could not be performed.
For other SQL statements, such as CREATE TABLE, DROP TABLE, GRANT, etc., the mysql_query() function will return either TRUE or FALSE based on whether the SQL statement was successful or not.
OK, so I have queried the database, selected some data, NOW WHAT?????
Well, let's go read about displaying in the browser
next lesson - SELECT statements
|