Jump to content

Accessing database using class


shynn13

Recommended Posts

Can somebody help me what i'm  doing wrong? The value from database is not visible when using:

<?php

$artikel = new Artikel();

$content= $artikel->printArtikel();

echo $content;

?>

 

<?php
class Artikel {
                // db connection
protected $mydb; 

                // database value
protected $land;	

public function __construct($artikelnummer = false)
{ 	// databaseconnection:
	$this->mydb = new MyDB();

	if($artikelnummer)
	{
		$this->load($artikelnummer); 
	}
	else // load everything from database.
		{
		$sql = "SELECT * FROM artikel";
		$this->mydb->doQuery($sql);
		$this->mydb->close();
	}
}

public function load($artikelnummer)
{
	$sql = "SELECT * FROM artikel";
	$this->mydb->doQuery($sql);

	if($artikel = $this->mydb->fetch())
	{
	    // i got a feeling there is something missing here, like query from database??	
                }
	$this->mydb->close();
}	

public function printArtikel()
{
	// return database value as table.
	$html = "<table border='1'>";
	$html .= "<tr>
		<td>".$this->land."</td> 
	                </tr>";
	$html .= "</table>";
	return $html;
}
}
?>

 

Other class are accessing extern. For example database connection with class MyDB.

please, can somebody correct my script??

 

Link to comment
https://forums.phpfreaks.com/topic/223082-accessing-database-using-class/
Share on other sites

class Artikel
{
    private $db;
    
    public function __construct() {
        $this->db = new MyDB();
    }
    
    public function find($artikelNummer)
    {
        if (!ctype_digit($artikelNummer) || $artikelNummer <= 0) {
            throw new InvalidArgumentException(
                'Artikel nummer is ongeldig! Verwachtte een geheel positief getal verschillend van 0, maar kreeg een ' . gettype($artikelNummer)
            );
        }
        
        $this->db->doQuery('SELECT * FROM artikel WHERE nummer = ' . int($artikelNummer));
        return $this->db->fetch();
    }
    
    public function getAll() {
        $this->db->doQuery('SELECT * FROM artikel');
        return $this->db->fetch();
    }
}

function printCountryTable($country) {
    return <<<TABLE
        <table border="1">
        <tr>
          <td>$country</td>
        </tr>
        </table>
TABLE;
}

$artikel = new Artikel();
printCountryTable($artikel->find(1));

 

How an article and a country are related.. I have no idea! This little example shows you how you effectively can separate your DB interaction and presentation.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.