Messing with PHP and MySQL
Posted by Nessa | Posted in mysql,php | Posted on 16-01-2007
0
This just a simple tutorial on how to connect to MySQL with PHP, as well as using a MySQL query to create simple database.
The first thing you would want to do is create the database so PHP can access it. My preferred method is through phpMyAdmin or cPanel (if your host provides this)…or you can run a simple query via MySQL command line:
CREATE DATABASE `liquor`;
USE `liquor`;
CREATE TABLE `brands` (
`id` int UNIQUE NOT NULL,
`brand` varchar(40),
`type` varchar(50),
PRIMARY KEY(id)
);
INSERT INTO cars VALUES(1,'skyy','vodka');
INSERT INTO cars VALUES(2,'cpt. morgan','rum');
INSERT INTO cars VALUES(3,'ice 101','schnapps');
This code will basically create a database named “liquor” with the table “brands” that lists three of my favorite liquors in order with the type of liquor that they are. From here, you’ll want to create a database user and add it to the database with the appropriate privileges. You can usually do this in your MySQL management interface provided by your hosting company, but if not you can check this site for information on users and privileges.
Now for the PHP code, you declare your database variable and use to mysql_connect function to establish a database connection:
<?php
$db_user = "user_name";
$db_pass = "password";
$db_host = "localhost";
//connection string
$dbconn = mysql_connect($db_host, $db_user, $db_pass)
or die("Cannot connect to database");
echo "Connected to the database!<br>";
?>
Once you’ve verified that you can connect to the database, you now need to tell PHP what table you want to work with. Let’s use the one we just created:
<?php
//select a database to work with
$selected = mysql_select_db("brands",$dbconn)
or die("Could not select liquor");
?>
Now here’s the complex part of the code where we create a loop to pull the data from the three rows we created:
<?php
//execute the SQL query and return records
$result = mysql_query("SELECT id, brand,type FROM brands");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'brand}."
".$row{'type'}."<br>";
}
?>
Of course, this example is just a dummy one that returns the same records we’re querying –so it’s not really useful in real life.
Once you have the information you need from the database, try to make it a habit of closing the connection. Using persistant connections can cause issues on the server and is not recommended for a live production site.
<?php
//close the connection
mysql_close($dbconn);
?>












