PHP Tutorial

From Hashmysql
Jump to: navigation, search

Here's my first attempt at a tutorial. This is a basic how to make sure your Apache/PHP/MySQL setup is working fine. First...

Some Assumptions:

  • You're using Linux.
  • You have created a user for MySQL using the GRANT Syntax
  • You have tested said user from the command line
  • You have installed Apache and PHP and configured your apache server to parse .php files properly.

Some Definitions:

  • MySQL Username : mytest
  • MySQL Password : mypass
  • MySQL Test DB : mydb


  • If you're using openbsd, using localhost as the hostname may not work, as the apache/php is chrooted. You need to specify Make sure your GRANT tables are setup correctly.


You can create a test table and insert some records using the tutorial at Basic SQL Statements (the Simple Example that you will find there will set up the database that this tutorial assumes).

Checking to see if PHP has MySQL support built in and ready.

First thing you want to check is whether your installation of PHP has MySQL support already, this can be done in many different ways, but we'll focus on the simplest.

  1. Create a info.php, with the contents of it saying:
  2. <?php 

    Look for a section on MySQL (press CTRL -F and search, if you do not find anything, you need to go back and build php with MySQL).

    An example query that outputs all the rows of a table

    Now that you have PHP with MySQL, lets get to the actual php code.

        $myuser = 'mytest';
        $mypass = 'mypass';
        $mydb = 'mydb';
        $link = mysql_connect('localhost',$myuser,$mypass);
        // If there was an error report the error.
        if(!$link) {
         die('Could not connect to the database: ' . mysql_error());
        echo "Able to connect, now pulling data .. <br>";
        $db = mysql_select_db('test',$link);
        // Report any error with DB selection here.
        if(!$db) {
         die ('Could not use the test db because: ' . mysql_error());
        // Now Select all rows from the table and display the results to the DB.
        $sql = "SELECT id,name FROM mytable";
        $rs = mysql_query($sql); // Run the Query 
        $numrows = mysql_num_rows($rs);  // Find out the number of rows returned from the Query
        echo "I Got $numrows rows. <br>";
        // Print out the contents of the rows line by line. 
        // you can switch assoc, with array if you don't know the names of the fields.    
        while($row=mysql_fetch_assoc($rs)) {
         echo "The id is : " . $row['id'] . "...";
         echo "The name is : ". $row['name']  . "<br>";


In PHP variables have the $ symbol in front of them. You don't have to define the type. If when you first assign a value it you give it a string as in:

$myuser = 'mytest';

then it becomes a string. mysql_select_db returns a boolean (depending on success or failure so $db above will become a boolean as in:

$db = mysql_select_db('test',$link);

External Links