Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Guide] How to get value from the database
#1
Here is a small simple guide on how to get some values from the database.

Well, lets say that you had a database called "MyDatabase" and a database table called "MyTable", lets say your database username is "MyUsername" and that your password was "MyPassword".
Atleast the host should just be "localhost" as it is that for most hosts, unless that your hosting provider tells you something else.

First we need to connect to the database, we do that by the following code
PHP Code:
$con mysql_connect("localhost","MyUsername","MyPassword");
if (!
$con)
  {
  die(
'Could not connect: ' mysql_error());
  } 
The code above first connect to the database with the hostname, username and password, and then it checks if the connection was made successfully, this is done for security reasons.

Then we need to select the database
PHP Code:
mysql_select_db("MyDatabase"$con); 

If everything went well for now, we need to select the informations we want to get out. It could be like listing all things from the table, then it would look like this:
PHP Code:
$result mysql_query("SELECT * FROM MyTable"); 
Or for a special value we could use the WHERE function, like if we wanted to find the informations where name=Mark.
PHP Code:
$result mysql_query("SELECT * FROM MyTable WHERE name='Mark'"); 

After you have selected the informations you want to print out, then you can now print them out by doing a while loop, this loop will run once for every row which is selected from your database table.
PHP Code:
while($row mysql_fetch_array($result))
  {
  echo 
$row['Name'] . " " $row['LastName'];
  echo 
"<br />";
  } 
We use the $row['Name'] to be the value of the column called "Name" from the current database row.
So if you had made the first selection example it would come out with all the names and lastnames which are listed at the database, if you used the selection example with the WHERE function, it would only show the names and lastnames for everyone which have the name Mark.

At last we need to close the MySQL connection and the PHP tag for securty reasons.
PHP Code:
mysql_close($con);
?>
Reply
#2
Nice, you truly surprise me every time you post tuts.
Reply
#3
(08-13-2012, 10:37 AM)Guntile Wrote: Nice, you truly surprise me every time you post tuts.

Thanks, happy to hear.

I am currently working on making a tutorial for making a secure login page, but it takes a while, so might come up with some other tutorials before.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)