PHP – Connect to MySQL database

$server = 'localhost';
$un = 'your-database-username';
$db = 'your-database-passname';
$pw = 'your-database-password';
$db_connect = MySQL_connect($server,$un,$pw);
$db_select = mysql_select_db($db,$db_connect);
if (!$db_connect){die('Could not connect: ' . mysql_error());}
else{if (!$db_select){die('Could not select the database: ' . mysql_error());}}

The code above will connect to the database. The code below will get records from the database.

mysql_query() gets all the records from the database and assigns it to the $result variable.

Then, we loop through the $result variable assign each field value in each row to variables, and then print it to the page (echo).

$result = mysql_query("SELECT * FROM database-table-name ORDER BY ID DESC");
while($row = mysql_fetch_array($result))
      $db_ID = $row['ID'];
      $db_FIRST_NAME = $row['FIRST_NAME'];
      $db_LAST_NAME = $row['LAST_NAME'];
      $db_EMAIL = $row['EMAIL'];
      $db_PHONE = $row['PHONE'];
      echo $db_ID.'<br>';
      echo $db_FIRST_NAME.'<br>';
      echo $db_LAST_NAME.'<br>';
      echo '<td>'.$db_EMAIL.'<br>';
      echo '<td>'.$db_PHONE.'<br>';

Thank you for reading!

It's only fair to share...Tweet about this on Twitter
Share on Facebook
Email this to someone