Jump to content

Question about 'proper way' to use objects, methods, classes


Darkelve

Recommended Posts

Currently I'm learning about objects and classes. I followed a tutorial about making a DB abstraction class (a mySQL select) and then I tried to adapt it and wrote a method to Insert a new name. However, then I had a problem: what if the value already exists in the DB?

 

So I thought maybe I could write a method for that too, and hopefully this would be re-usable for other purposes.

 

So I'm posting the code here and I hope someone could take a look at it, since I do not want to start any bad practices and start a habit of writing sloppy code. Would the code below be considered 'good code'?

 


<?php
// This file is called database.php

class database {

public $mysql;
function __construct() {
$this->mysql = new mysqli('localhost', 'root', 'password', 'db') or trigger_error('Database connection failed');
}

/* Function to check whether value: $queriedName already exists inside table: $table and column: $column  */
function findMatch($table, $column, $queriedName) {			
	if ($result = $this->mysql->query("SELECT * FROM $table WHERE $column='$queriedName'")) 
		{
			if (!$numberOfRows=$result->num_rows) {
			return false;
			}

			else {
			return true;
			}			
		}		
}

/* Function to select all records from table: $table */
function selectAll($table) {	
if ($result = $this->mysql->query("SELECT * FROM $table") ) {
		while($row=$result->fetch_object()) {
		$nameFields[]=$row->names;
		}	
		return $nameFields;
	}
}

/* Function to insert a name: $newName into table: $table. Uses method finMatch to avoid doubles */
function insertName($table, $newName) {		
	if ($this->findMatch($table, 'names', $newName)) {
	$result="Person already exists!";
	return $result;
	}

	else {
	$result = $this->mysql->query("INSERT INTO $table(names) VALUES ('$newName')");
	return $result;
	}

// 
}
}

?>

 

Main page:

 

// This file is called index.php
require('database.php');
$newName='Mary Jane';
$result=$myDb->insertname('mytable', $newName);
echo $result;

 

 

try {    $gateway = new UserStoreGateway();    $user = $gateway->createRow($_POST);    $user->save();} catch(DbServiceUnavailableException $e) {} catch(UserAlreadyExistsException $e) {}

 

 

This might be more re-usable then a simple Database object that would act as a grand Façade for everything Database.

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.