I'm brand new at OOP PHP and I would like to get as many of the coding conventions right as fast as possible. I made this tiny guestbook script, and I would like to know if there's anything not done as it should.
Index.php
:
<?php
$username = "root";
$password = "";
$database = "oop";
$host = "localhost";
mysql_connect($host, $username, $password);
mysql_select_db($database);
?>
<html>
<head>
</head>
<body>
<?php
include("views/gaestebog.php");
?>
</body>
</html>
Guestbook.php
, the class:
<?php
class Gaestebog {
public function __contruct() {
}
public function getPosts() {
$query = mysql_query("SELECT * FROM gaestebog");
while ($row = mysql_fetch_array($query)) {
echo '
<tr>
<td>'.$row['navn'].'</td>
</tr>
<tr>
<td>'.$row['besked'].'</td>
</tr>
';
}
}
public function addPost($navn, $besked) {
mysql_query("INSERT INTO gaestebog VALUES('', '$navn', '$besked')");
}
}
?>
and guestbook.php
, the view:
<?php
include("classes/Gaestebog.php");
$gaestebog = new Gaestebog();
if (isset($_POST['opret'])) {
$navn = $_POST['navn'];
$besked = $_POST['besked'];
$gaestebog->addPost($navn, $besked);
}
?>
<table>
<?php
$gaestebog->getPosts();
?>
</table>
<hr />
<form action="" method="post">
<table>
<tr>
<td>Navn:</td>
<td><input type="text" name="navn" value="Patrick" /></td>
</tr>
<tr>
<td>Besked:</td>
<td><input type="text" name="besked" value="Hej med dig !!" /></td>
</tr>
<tr>
<td><input type="submit" name="opret" value="Opret" /></td>
</tr>
</table>
</form>
mysql_query()
is no longer suggested php.net/manual/en/function.mysql-query.php one of the alternatives is to use themysqli
interface with is OOP. – JRSofty Nov 9 '12 at 8:27mysql
go formysqli
orPDO
. Use parameterized query. make a use of database abstraction class instead of using core database functions in your classes. Thats all I can think of now – LoVeSmItH Nov 9 '12 at 8:29