Connect to MYSQL database using PHP
mysql_connect(”localhost”, “USER”, “PASS”) or die(mysql_error());
echo “Connected to MySQL”;
mysql_select_db(”DATABASE”) or die(mysql_error());
echo “Connected to Database”;
This is a simple mysql db connection script for the PHP Programmer. All you have to do is replace the USER, PASS and DATABASE with your settings. You may also need to change the localhost with your own setting also. These scripts are intended for educational purposes. Feel free to use them as you need.
OOP Programming is becoming more and more popular among web owners and programmers. Here is an example for getting data from the db using OOP PHP Programming.
Create a table named our_table and create a field for ID. Now enter a coupe id’s in this new table. When you have your db set create the following files.
Name a file include.php and add this:
include ‘function.php’;
require_once(’DB.php’);$host = ‘localhost’;
$user = ‘your user’;
$pass = ‘your pass’;
$database = ‘your db’;$dsn = “mysql://$user:$pass@$host/$database”;
$db = DB::connect($dsn, false);function GetMainContent()
{
global $db;$result = $db->query(’SELECT * FROM our_table ORDER BY id ASC’);
$selfArray = array();
while ($row = $result->fetchRow(DB_FETCHMODE_ASSOC))
{
$myContent = new ContentBag($row["id"]);
array_push($selfArray, $myContent);
}
return $selfArray;
$db->disconnect();}
Now create a file named function.php and add this:
class ContentBag
{public $id;
function __construct($Id=null)
{
if (!empty($Id))
{
$this->id = $Id;
}}
}
Now in your view file named index.php add this:
include (”includes.php”);
$get_id = GetMainContent();
echo “\n”;
foreach ($get_id as $text)
{
echo “ID: ” . $text->lid . ”
\n”;
}