Darkelve Posted October 11, 2010 Share Posted October 11, 2010 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; Quote Link to comment https://forums.phpfreaks.com/topic/215598-question-about-proper-way-to-use-objects-methods-classes/ Share on other sites More sharing options...
ignace Posted October 11, 2010 Share Posted October 11, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/215598-question-about-proper-way-to-use-objects-methods-classes/#findComment-1121173 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.