Basics of PHP - Part 5
Our final chapter looks at calling a row from our mysql database. To begin lets look at our code in full so far. For an explanations on how the code works, see part 1 through 4.
<?php
$hostname = "localhost";
$database = "db_ryanpartington.com";
$username = "ryan";
$password = "$ecr3t";
$mysqlconnection = mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database, $mysqlconnection);
?>
We've all our varialbes for a successful database connection, lets query some data.
<?php
$customquery1 = mysql_query("SELECT * FROM tbl_articles WHERE id = 150", $mysqlconnection) or die(mysql_error());
$prepare1 = mysql_fetch_assoc($customquery1);
echo $prepare1['article_title'];
?>
The code broken down
<?php - Opening the php tag
$customquery1 = mysql_query("SELECT * FROM tbl_articles WHERE id = 150", $mysqlconnection) or die(mysql_error()); - Defining a variable using the 'mysql_query()' function. The first part is a text string selecting all columns from the tbl_articles table within our database and then filtering the row where column id has a value of 150. We then use a predefined variable $mysqlconnection to connect to the database. If this connection fails stop processing php code (die) and echo out the error message.
$prepare1 = mysql_fetch_assoc($customquery1); - Define a variable called $prepare1 which will use the 'mysql_fetch_assoc()' function to fetch a result row as an associative array. Don't worry about this too much at the moment.
echo $prepare1['article_title']; - Echos out to the webpage the value within the 'article_title' column of the table. We call also use 'var_dump($prepare1);' to echo all the values stored within the array. Again, lets not worry too much about that now.
?> - Close PHP tag
Lets take a look at what our table may look like within the mysql database
| id | article_title |
| 150 | How to create a webpage |
With the above code the webpage would simply display 'How to create a webpage'
All the code together:-
<?php
$hostname = "localhost";
$database = "db_ryanpartington.com";
$username = "ryan";
$password = "$ecr3t";
$mysqlconnection = mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database, $mysqlconnection);
$customquery1 = mysql_query("SELECT * FROM tbl_articles WHERE id = 150", $mysqlconnection) or die(mysql_error());
$prepare1 = mysql_fetch_assoc($customquery1);
echo $prepare1['article_title'];
?>
Cheers
Ryan Partington


