Languages - PHP
How to connect to MySQL tables via PHP.
3 different API's
MySQL Table Connections
||MySQL Improved Extension |
This provides both an object oriented interface and a procedural (simple function call)
||PHP Data Objects |
This makes your code database independent. Using this you can
change from MySQL to another database type without having to change you code.
(We all know that isn't true, but it is a nice thought.)
||This uses function calls, no objects - I have described it
on a separate page
so you can use it if you have to,
but it is deprecated and should not be used for new designs.
The main MySQL pages provide
examples of the 3 API's
query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $result->fetch_assoc();
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $statement->fetch(PDO::FETCH_ASSOC);
$c = mysql_connect("example.com", "user", "password");
$result = mysql_query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = mysql_fetch_assoc($result);
Connecting to the database
These scripts will make a database connection.
The constants simplify moving the database from a development system
to a production system on another computer - only one file has to change.
Typically, the user name and password will be different for security reasons.
the prefix test_ will be removed from the database name.
This code makes the actual connection.
This is a bit different, based on
The at sign (@) in front of new means to
ignore all errors.
This uses object syntax to get the error.
$connection->connect_error will not work with PHP 5.2.9 and below ..
use the procedural method in the previous example instead.
die("Connect failed: " . $database->connect_error . "\n");
At this point, it is possible to query the database and populate a form.
I strongly suggest using a readonly connection for display and
a separate read/write connection to update the tables.
Closing the database connection
After the page is rendered, this will close the connection.
Code similar to the following will include the scripts in the correct order
to connect to the database,
and, after the page has rendered, disconnect from it.
While disconnecting is optional, it is also good programming practice
- always explicitly close what you open.