Wednesday, March 18, 2009

How to connect to MySQL Database, SQL Query and Displaying Query Results using PHP scripts

After creating your database and tables in MySQL (PhpMyAdmin). You are now ready to connect to your database using the PHP script below.


////////////////////////////////////////////////
//
// We use the pre-defined function
mysql_connect("server","username","password"),
//
// since we are developing our website in localhost (your own machine), by default, we use
// localhost as our server, root as our username and no password.
//
// Note: You can always create a new database user with password
// protection in PhpMyAdmin. Thus, making it
// mysql_connect("localhost","yourUsername","yourPassword")
//
// and you can use any names for your variables during the PHP scripting. Just a suggestion,
// you should name your variables according to its use.
//
////////////////////////////////////////////////

$link = mysql_connect("server","username","password") or die("Cannot Connect to DB");

///////////////////////////////////////////////
//
// we declared and initialized a variable ($link) to hold the connection,
// after a successful MySQL connection, we are now going to select our database
// using mysql_select_db("yourDBName","yourMySQLConnection")
//
///////////////////////////////////////////////

mysql_select_db("yourDBName",$link);

///////////////////////////////////////////////
//
// after selecting your database, you are now ready to query.
// For SQL queries reference, click HERE.
//
///////////////////////////////////////////////

$sql = "SELECT * FROM yourTableName";
$result = mysql_query($sql);

while($show = mysql_fetch_array($result)){
echo $show['someFieldNameInYourTable'];
}

///////////////////////////////////////////////
//
// $sql holds the sql query string,
// $result holds the exact query using the function mysql_query("yourSQLQuery"),
// and mysql_fetch_array("resultOfYourSQLQuery") is responsible for getting the data from
// your query and displaying it using echo
//
///////////////////////////////////////////////
?>

There you have it. You can use this LINK for your PHP reference.

0 comments: