Saturday, August 14, 2010

Connecting to a database with php


 ....................................................................................................................
Connecting to a database with php I wrote a very well commented php script showing you how to connect to a database, this is for learning not using, im just giving you and example to run off of. The best way to use this example in a way that you can understand would be to get a free web host that supports php and gives you a certain number of databases. agilityhoster.com is a really good host.
           
First youll need to get your server information:
it will be something like sql.yourhost.com

Second make a database, if you don't know how to do this, use one of their auto installing scripts like wordpress

Third have a username and password for you sql database, usually be something like:
databasename_yourusername
cpanel password

next save this script editing with your information as sql.php then run it and see what it does, you can expand this to print results of all tables and columns in your database.

Well I hope someone learns something from this.


//Guide showing how to get info from a database and print results in html format

//It is all done in three very simple steps:
//1. Connect to the server
//2. Select database name
//3. Making a simple query


//NOTE: This is just an example to show you how to do this, if you don't have relevant
//information you will not be able to connect to a database you need to know
//the server name, database name, all tables and columns you want to extract, if you do
//not know this information please dont post saying how do i get it to work.


//database to connect to
mysql_conncet("server.com", "username", "password");

//select your database
mysql_select_db("db_name")

//defines query and adds results into a variable
$result = mysql_query("select userid, username, password from admin");

//now you have stored the query results into the variable $results
//now we'll loop the results and print into html


while($row = mysql_fetch_row($result))
{
//the dot concatenates strings in php
echo "User ID: " . $row[0] . "
";
echo "Username: " . $row[1] . "
";
echo "Password: " . $row[2] . "
";
}


//coded by adnan
?
>

4 comments:

  1. good one,, although i knew it before, but it was long time ago,, great reminder,, i am gonna start php soon again,

    ReplyDelete
  2. nice thought,
    keep visiting
    regards,

    ReplyDelete
  3. wow...it was a good one.
    Helped a lot .
    your blog is so useful.

    ReplyDelete
  4. hey , do you accept guest posts?
    if yes, i would feel great to write some of the superb codes and posts for your blog.

    ReplyDelete