Follow me on Twitter to receive updates, free scripts and ongoing announcements!

Fetching results from a mysql table

Written by Codes Tips on March 18, 2009 – 1:50 pm -

To connect to a mysql database you should use the command mysql_connect .You should first setup the details of the mysql database.

$connect=mysql_connect($server, $db_user, $db_pass)    or die ("Error: could not connect to database");

$server is the server for the mysql database, usually this is localhost, but you should double check.

$db_user is the user which connects to the server

$db_pass the password for the user

If the can’t connect to the server we should display an error message with die() command.

After we connect to the database we can make a sql query on the database that we want.

//we select  all the rows from table TableName where the Field1 has a value of $value
$results = mysql_db_query($database, "SELECT * FROM TableName WHERE Field1=".$value);
 while($resultrow = mysql_fetch_array($results, MYSQL_ASSOC))
{
  echo $resultrow['Field2'];//we show the result of the field Field1
}

After we make the query we can take each row of the result query and do whatever we want.

For closing a mysql connection we can use mysql_close($connect);

Example Code in PHP:

 
$server="localhost";//this is ussually localhost
 
$db_userName="UserName";
 
$db_password="Password";
 
$database="DatabaseName";
 
$connect=mysql_connect($server, $db_userName, $db_password  or die ("Mysql connection error");
 
$results = mysql_db_query($database, "SELECT * FROM TableName WHERE Field1=".$value);
 
while($resultrow = mysql_fetch_array($results, MYSQL_ASSOC))
{
  echo $resultrow['Field2'];//we show the result of the field Field1
}
 
mysql_close($connect);

Tags:
Posted in PHP/MYSQL |

One Comment to “Fetching results from a mysql table”

  1. PHP paging tutorial | Codes Tips Says:

    [...] discuss previously how we can connect to a database and how to make a query, go here for learning how to connect and fetch results from mysql. After we make a query we get each row of the query result and verify if it is on the current page( [...]

Leave a Comment

You must be logged in to post a comment.


Plugintaylor.com - Plugintaylor and Admin Area