Monday, February 13, 2006

PHP Class for MySQL queries

In this tutorial I am going to explain how a php class basically works. Some knowledge of PHP is required to really understand how a class works.

1. Creating a new PHP document
2. Writing the PHP code2.1 Creating the class
3. Communicate with the class

Creating a new document
First of all we have to create three new documents, open notepad or any text editor. This could also be dreamweaver or any other web page software.When you have opened notepad don't start typing, first save the file with the name queryClass.php, showQuery.php and connex.php. Don't forget the extension else you will get an txt file instead of an PHP file.

Writing the PHP code
Now the few things you must know are, that "$anyname" stands for a variable, we can store information init. We also can use variables inside of an class "$this->anyname", you could also send a variable back to the page the executed the function in the class. If you don't really understand what I mean check out the examples later.


creating a connection with the mysql server
//Save this in the file connex.php

<?php
$connection = mysql_connect('localhost',
'mysql_login_here',
'mysql_password_here')
or die ("Couldn't connect to mysql server");
$database = mysql_select_db('your datbase');
or die ("Couldn't connect to database");
?>



Creating the Class
//Save this in the file queryClass.php

<?php
Class querySelect {
include('connex.php');
var $id;
var $subject;
var $text;
var $table;

function queryOnId(){
$query = "SELECT * FROM $this->$table WHERE id=$this->id";
$result = mysql_query($query);
or die ("Query error");
if(empty($result)){
echo "Ther where no results";
}else{

$this->row_set = mysql_fetch_assoc($result);
$this->row_set['subject'];
$this->row_set['text'];


mysql_free_result($result);
mysql_close($connection);
$this->done = "true";
}
?>



Showing the query
//Save this in the file showQuery.php

<?php
include('queryClass.php');
$querySelect = new querySelect();
$querySelect->id = $_POST['id'];
$querySelect->queryOnId();
$done = $querySelect->done;
$row_set = $querySelect->row_set;
?>
<html>
<head>
<title>MyQuery</title>
</head>
<body>
<?php
if(isset($done)){
?>

<?php while($row_set){ ?>
<table width="600" border="1" cellpadding="0" cellspacing="0">
<tr>
<td><?php echo "$row_set['subject']";?></td>
</tr>
<tr>
<td><?php echo "$row_set['text']";?></td>
</tr>
</table>
<?php } ?>

</body>

1 comment:

Unknown said...

Hoi Iason,

Je bent op dit moment meer actief in je andere blog over je werkzaamheden bij Lost Boys, maar daar kon ik geen bericht achter laten. Ik wil je graag wijzen op een website die je zou kunnen interesseren: www.werkenbijdemakers.nl . Als je een idee hebt voor een website of een programma om te schrijven, etc. dan kan je dat opsturen en misschien binnenkort betaald realiseren! Ik ben benieuwd naar je reactie.

Namens de makers,
Wijnand Boon