Categories
PHP Tutorials

PHP Code Example – How to connect MySQL database

The steps to connect MySQL database with PHP with simple PHP code example.

The steps to connect MySQL database with PHP.  This program will work for database connection in PHP with MySQL in XAMPP or using WAMP server. A simplest example where a script of PHP connect to MySQL database and also this is an example of PHP program on database connection.

In this example the server information / URL, user and password all taken in variables so that you can use and change them in one portion.

My intention was to keep this example unsertanable to the beginners in PHP MySQL. So I have intentionally made this example very simple. In this example you will get how to search a MySQL table using PHP

Simplest example code on PHP to connect MySQL database to get data

  1. Connect the server
  2. Select the DB
  3. Write theSQL query
  4. Execute the query & get the resultset / query output in a variable $result.
  5. If resultset contains greater than 1 record the process each record of the recordset by a while loop
<?php

$MYSQL_HOST = "localhost";
$MYSQL_USER = "bikram";
$MYSQL_PASS = "bikram";

$MYSQL_DB_NAME = "eworkshop";

// connect the server
$server = mysql_connect($MYSQL_HOST, $MYSQL_USER, $MYSQL_PASS) or die("MySQL server connection error : ".mysql_error());
echo "server connected<br />";

//connect the DB
 mysql_select_db( $MYSQL_DB_NAME , $server) or die("".mysql_error());
echo "db connected<br />";

// execute query
$query = "select vehicle_name from vehicle_table";
$result = mysql_query($query) or die( mysql_error());

if(mysql_num_rows($result) > 0)
{
echo "<table><tr><th>vehicle name</th></tr>";

while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "<tr><td>".$row["vehicle_name"]."</td></tr>";
}
echo "</table>";
}
?>

If you are a beginner to programming .. you can learn PHP training courses in Kolkata, if you reside in Kolkata India. If you reside outside of Kolkata then you should learn PHP online mode. Mr Bikram Choudhury, the also teach PHP in Kolkata and online, so you can learn PHP Online from a live tutor like me., if you want.