Job2 Street

Thursday, December 4, 2014

How to connect to MySQL database with PHP

How to connect to MySQL database with PHP


You can create really cool database applications usind PHP and MySQL. In fact if you are using WordPress you are already using PHP and MySQL. You need to first connect to your MySQL database server before you can manipulate tables created in a particular database. In order to connect, you need the following information:
  • MySQL server host link
  • User name
  • User password
  • Database name
If you are hosting your website through a web hosting company, they may have you use “localhost” as your MySQL server host link. Mostly, you use “localhost” when you have installed the server on your own machine. In many cases, you may also have something like “mysql.yourdomain.com”. The rest of the things are easily understandable.
Different people may have different ways of connecting to MySQL database with PHP, but here is a straightforward way:
<?php
$host=”mysql.yourdomain.com”;
$user_name=”peter”;
$pwd=”F$5tBGtr”;
$database_name=”our_clients”;
$db=mysql_connect($host, $user_name, $pwd);
if (mysql_error() > “”) print mysql_error() . “<br>”;
mysql_select_db($database_name, $db);
if (mysql_error() > “”) print mysql_error() . “<br>”;
?>
This way you can easily connect to your MySQL database with PHP. You can easily have this code in a function and then call that function:
<?php
function connect2database()
{
        $host=”mysql.yourdomain.com”;
        $user_name=”peter”;
        $pwd=”F$5tBGtr”;
        $database_name=”our_clients”;
        $db=mysql_connect($host, $user_name, $pwd);
        if (mysql_error() > “”) print mysql_error() . “<br>”;
        mysql_select_db($database_name, $db);
        if (mysql_error() > “”) print mysql_error() . “<br>”;
}
?>
http://www.howtoplaza.com/how-to-connect-to-mysql-database-with-php

Alternatively, you can run a MySQL query, which will create the table. The format is:
CREATE TABLE tablename (Fields)
The fields are defined as follows:
fieldname type(length) extra info,
The fields are separated by comma.
For example, if you wish to create a table called Members with 3 fields in it - FirstName, LastName and Age, you should execute the following query:
CREATE TABLE Members(FirstName varchar(15),LastName varchar(15),Age int);

No comments:

Post a Comment

K-Play

kPlaylist - get your music online

The player will show in this paragraph

2 3

IkimFM

speaker music speaker