2:44 AM

Using PHP to connect to MySQL Database

posted under by FR3@K | Edit This

How to connect a database? I will not expose Phpmyadmin or others software.

You need to have an account to your host with at least 1 database or you need to
have the possibility to connect to another host who have a database.


As ever on PHP, we need to call a function to connect the database, another to
choice the table, another to make a request and another to put/take the result
into a table in the memory.



PHP Code:

<?php
$server='localhost'; /* it's often localhost and always if you have Cpanel,
if you want to connect to another host, put another IP,
you're host says you that*/
$username='myusername'; /* the name of the user of this database,
on Cpanel it's usually username_userofdatabase (shared host)*/
$password='123456789'; /* you're pass for the database
not you're pass from Cpanel*/
$database='mydatabase';  /* the name of you're database,
on Cpanel it's usually username_database (shared host)*/


mysql_connect($server,$username,$password); /* it's a function so ";"
at the end*/
mysql_select_db($database); // it's another function....

Great you are connected, don't forget to close you're connection at the end of
the script (usually the bottom of you're page) :

PHP Code:

<?php mysql_close();?>

You can change the database by setting another one :

PHP Code:

<?php $database2='database2';
mysql_select_db($database2);?>



Now You have to learn another language to communicate with the server SQL. Later
i will put some SQL request to help you.



Make a request :

mysql_query();

Example :

PHP Code:
<?php mysql_query("SELECT name FROM mytable"); // it's a function... ?>

Put it in a table of association and use it :

mysql_fetch_assoc();

Example for one line :

PHP Code:

<?php $request=mysql_query("SELECT name FROM mytable");
$result=mysql_fetch_assoc($request);
echo $result['name'];
// or the same thing :
$result=mysql_fetch_assoc(mysql_query("SELECT name FROM mytable"));
echo $result['name'];

?>

If you have more than one line, you need to put it into a "while" like this :

PHP Code:

<?php $request=mysql_query("SELECT name FROM mytable");
while($result=mysql_fetch_assoc($request)){
echo $result['name'];
}
?>

0 comments

Make A Comment
top