Home > PHP > PHP & mySQL: An intro

PHP & mySQL: An intro

The main benefit of PHP is its compatibility with mySQL. In this tutorial you will learn the basics of PHP and mySQL.

<?php

$connection = mysql_connect(’SEVER’, ‘USER’, ‘PASSWORD’);
$selectdb = mysql_select_db(’DB NAME’);

if(!$connection){
die(’Error connecting to database server’);
}
if(!$selectdb){
die(’Error connecting to selected database’);
}

//This code connects the page to the database ready to make a query. By holding //the connection functions in variables we can create a custom error message.

?>

Next I will teach you about query syntax. A basic query follows this rule:

SELECT name FROM table

The SELECT tells mySQL to return a value from the specified field (in this example the field is called “name”). Alternatively you can use the * wild card. This requests all the information from the table selected in the FROM parameter.
The FROM tells mySQL which table in the database the field can be found.

For example to retrieve a name from a table called users the code would look like this:

$query = mysql_query(”SELECT * FROM users”);
if(!$query){
die(’Error in query’);
}

while($row = mysql_fetch_array($query)){
echo $row['firstname'];
echo “<br />”;
}

First of all we query the database for a set of results. Then we echo out all the results using a WHILE loop. The $row variable contains all the information so we specify what information we want from the query using ['']. This returns the information from that field.

The full code

<?php$connection = mysql_connect(’SEVER’, ‘USER’, ‘PASSWORD’);
$selectdb = mysql_select_db(’DB NAME’);

if(!$connection){
die(’Error connecting to database server’);
}
if(!$selectdb){
die(’Error connecting to selected database’);
}

$query = mysql_query(”SELECT * FROM users”);
if(!$query){
die(’Error in query’);
}

while($row = mysql_fetch_array($query)){
echo $row['firstname'];
echo “<br />”; //Add a line break for formatting
}

mysql_close($connection);

?>

The mysql_close() function will close the connection to the database

So as you can see PHP and mySQL can be a formidable combination. By integrating them into your site you can give users an enhanced experience.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • StumbleUpon
  • Twitter
Categories: PHP Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.