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>”;
?>
$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>”;
}
?>
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>”;
}
?>
Once this function is called on a particular page, you don’t need to call it again and again every time you run a MySQL function in PHP, unless due to some reason you had to close the database.
Related posts
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:
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:
No comments:
Post a Comment