Sunday, February 25, 2007

Extract data from Mysql Database

Ok, so you have some data stored in tables in your Mysql Database. How do you get that data out? I'm going to show you a very basic and easy way to get that data out of the database. Let's name teach thing we are working with. The table is named "my_table", and let's say we need to extract data from the following fields: "ID", "user_name", "password".

How do we do this?

First we make a new variable.Let's name it "$query". we assign to that variable, the PHP function mysql_query(); with the SQL request that extracts the inside the function like so:

mysql_query("SELECT * FROM `my_table`");
Right now, the variable $query contains an array with all of the values in the "my_table" table.
To get that out, and store it into other variables so we can use it we need to make a while loop work. To store all of the data into variables I will make an array of variables.I will continue the example using the commands again:
$query =mysql_query("SELECT * FROM `my_table`");
$i=0;
while($row = mysql_fetch_array($query ))
{
$ID[$i]=$row['ID'];
$user_name[$i]=$row['user_name'];
$password[$i]=$row['password'];
$i++;
}
Right now, the $ID,$user_name and $password are arrays that contain all of the values of the table "my_table".
To check a value you use the echo function:
echo $ID[0];
or
echo $user_name[5];

Enjoy.

2 comments:

Unknown said...

Well, you certainly know some things I don't know. What a mind you have. Thank you for commenting on my blog. I would be glad to exchange links. Hope it is helpful to you. Perhaps I can learn some things from you.

Anonymous said...

It's a long time since you wrote this, but it's been very helpful to me as a beginner to PHP. No over complications just a great simple method of getting data out of mysql into PHP
Thanks
ted