Monday, 12 August 2013

how to start PHP / Mysql Connection

here is a simple connection between php and mysql. in 5 steps .


Step 1
create the db 

CREATE DATABASE `mydb`;
USE `mydb`;
CREATE TABLE `employee` (
   `id` int UNIQUE NOT NULL AUTO_INCREMENT,
   `first_name` varchar(40),
   `last_name` varchar(50),
   PRIMARY KEY(id)
);
INSERT INTO cars VALUES('usama','saad');
INSERT INTO cars VALUES('hasan','hamaky');
INSERT INTO cars VALUES('noor','sobhy');


Step 2:


Get Connection with the db


<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost"; 

//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) 
  or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>


Step 3


Get your target schema

<?php
//select a database to work with
$selected = mysql_select_db("mydb",$dbhandle) 
  or die("Could not select mydb");
?>


Step 4:


Start your interaction with the db:

<?php
//execute the SQL query and return records
$result = mysql_query("SELECT id, first_namelast_name FROM employee");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
   echo "ID:".$row{'id'}." Name:".$row{'first_name'}." ".$row{'last_name'}."<br>";
}
?>


Step 5:

Close the connection:

<?php
//close the connection
mysql_close($dbhandle);
?>



Finally


here is the full code:

<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost"; 

//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) 
 or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";

//select a database to work with

$selected = mysql_select_db("examples",$dbhandle) 
  or die("Could not select mysql");

//execute the SQL query and return records
$result = mysql_query("SELECT id, first_namelast_name FROM employee");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
   echo "ID:".$row{'id'}." Name:".$row{'first_name'}." ".$row{'last_name'}."<br>";
}

//close the connection
mysql_close($dbhandle);
?>

Best Regards

No comments:

Post a Comment