Friday, January 13

PHP Connect to My SQL Database

<?php
$ng_username = "your_user_name";//localhost
$ng_password = "your_user_password";//password
$ng_hostname = "localhost/servername"; //127.0.0.1

//The connection to the database using PHP
$dbhandle = mysql_connect($ng_hostname, $ng_username, $ng_password)
  //or die(mysql_error());//Show Error generated.
  or die("in database connection details : Does not connect Mysql Databased ");
echo "database connection details : Your Database Connected to MySQL succesfully<br>";
?>


//Other way to select a database to work with


<?php
$selected = mysql_select_db("DatabaseName",$dbhandle_varname)or die("details of connect database - can not connect your database");
?>

Second way to external php to MYSQL connect databased- config.php
----------

<?php
$username_ng = "root";//localhost
$password_ng = "ng4free";//password
$hostname_ng = "localhost or ip"; //127.0.0.1

//connection to the database
$dbhandle = mysql_connect($hostname_ng, $username_ng, $password_ng)
  or die("Disconnect your databased in MYSQL/ Unable to connect to MySQL : details");
echo "You are Connected to MySQL Databased<br>";

$selected_databased = mysql_select_db("users",$dbhandle)or die("Databased Details : does not/Could not select users");

?>

Full Example : How to connect to MySQL database using PHP

<?php
$user_username = "Default (root)Your username or root";
$user_password = "Host (Password)genrated password";
$user_hostname = "localhost / server host";

//The above us to connection to the database
$dbhandle = mysql_connect($user_hostname, $user_username, $user_password)
 or die("Error : Unable to connect to MySQL");
echo "PHP to connect MySQL Databased success. <br>";

//The Script is select a database to work with
$selected = mysql_select_db("test",$dbhandle)
  or die("Could not select test");

//IT's is query execute the SQL query(handle) and return records
$result_data = mysql_query("SELECT your_id, modelname,year FROM cars_company");

//Loop through fetch tha data from the database Using PHP Script
while ($row = mysql_fetch_array($result_data)) {
   echo "ID:".$row{'your_id'}." Name:".$row{'modelname'}."Year: ". //Print display the results
   $row{'year'}."<br>";
}
//Dtabased close the connection
mysql_close($dbhandle);//connection close
?>

Now Go To Localhost/phpmyadmin and to create 'cars_company' database on your MySQL server you should run the following script:

CREATE DATABASE `users`;
USE `cars_company`;
CREATE TABLE `cars_company` (
   `your_id` int UNIQUE NOT NULL,
   `modelname` varchar(40),
   `year` varchar(50),
   PRIMARY KEY(your_id)
);

INSERT INTO cars_company VALUES(1,'ngcomapny','2000');
INSERT INTO cars_company VALUES(2,'ng4free','2004');
INSERT INTO cars_company VALUES(3,'ngdemo','2001');

No comments:

Post a Comment

10 Best Chatting Apps In India

  The modern world is all about Internet. There was a time when people use to pay high telephone bills to stay in touch with their friends a...