Setting up a database with MySQL and PHP

It is easy to set up a connection to a database.

Requirements for this guide:

  1. Must have a server that supports PHP and your database server must be MySQL.
  2. using phpMyAdmin – Version: 3.3.8

Create a database name, username, and password first. After you do this, then the rest is easy.

Create a connection file in php:

<?php
$host=”localhost”;
$username=”database name“;
$password=”password“;
$db_name=”username“;

mysql_connect(“$host”, “$username”, “$password”)or die(“cannot connect to server”);
mysql_select_db(“$db_name”)or die(“cannot select db”);
echo”Successful Connection”;
?>

Save this file as “conn.php” and uploaded to your web site, and then try to access this file from the Web.  If it works, it will say, “Successful Connection.”

Create a table using phpMyAdmin:

  1. In Create table, Name: web_members
  2. Number of fields: 4
  3. click ‘go’
  4. fill in the fields (id, name, lastname, email)
  5. for type(int, varchar, varchar, varchar)
  6. for length/values(4, 65, 65, 65)
  7. and then only for id select AUTO_INCREMENT

Insert data into your table using phpMyAdmin:

  1. select table, web_members
  2. click on insert tab
  3. in the value columns, skip id row but for name, lastname, email (  a, a, a@a.com)
  4. click ‘go’
  5. repeat steps 1. through 4. two more times with letter ‘b’ and then ‘c’

In the same folder, create a data retrieving file in php:

<?php

include(“conn.php”);

$tbl_name=”web_members”;
$sql=”SELECT * FROM $tbl_name”;
$result=mysql_query($sql);

// Start looping rows in mysql database.
while($rows=mysql_fetch_array($result)){
?>
<table width=”400″ border=”1″ cellspacing=”0″ cellpadding=”3″>
<tr>
<td width=”10%”><? echo $rows[‘id’]; ?></td>
<td width=”30%”><? echo $rows[‘name’]; ?></td>
<td width=”30%”><? echo $rows[‘lastname’]; ?></td>
<td width=”30%”><? echo $rows[’email’]; ?></td>
</tr>
</table>
<?
// close while loop
}
// close connection
mysql_close();
?>

Save this file as “webmembers.php” and uploaded to your web site, and then try to access this file from the Web.  If it works, it will show, “Successful Connection” and a table with the data we just entered into our database.

We are done. You should know how to connect to a database and retrieve data from a database using MySQL and php.

Source: http://www.phpeasystep.com

Leave a Reply

Your email address will not be published. Required fields are marked *