Php - Validations and errors - unique name - php

I don't want to save duplicate name record. I want to display errors back to the user.
But it doesn't work. I don't know what I'm doing wrong.
protected function has_unique_name($value, $current_id="0") {
$sql = "SELECT * FROM photographs ";
$sql .= "WHERE caption='" . self::$database->escape_string($this->caption) . "' ";
$sql .= "AND id != '" . self::$database->escape_string($current_id) . "'";
echo $sql;
$result = self::$database->query($sql);
$products_count = $result->num_rows;
echo $products_count . "<br />" ;
$result->free();
return $products_count === 0;
}
protected function validate() {
$this->errors = [];
$value = $this->caption;
$current_id = isset($this->id) ? $this->id : '0';
if(!$this->has_unique_name($this->caption, $current_id)) {
$errors[] = "The name must be unique.";
}
return $this->errors;
}
public function create() {
$this->validate();
if(!empty($this->errors)) { return false; }
...

Related

My project page information won't load when I'm logged in. PHP

I am still working on this page, but I'm stuck on making everything display when I'm logged in. Basically, what is suppose to happen, is it's suppose to display the HTML table with all project information, regardless of if I'm logged in or not. When I am logged in, the table headers display, but none of the open projects. I've been trying to figure out why this is happening, but I'm pretty much out of ideas at this point...
<?php
include_once TEMPLATE_PATH.'/site/helper/format.php';
$projects = $SOUP->get('projects', array());
$user = $SOUP->get('user', null);
$title = $SOUP->get('title', 'Projects');
$id = $SOUP->get('id', 'projects');
$hasPermission = Session::isLoggedIn();
// $hasPermission = Session::isLoggedIn() || Session::isAdmin();
// KEEP WORKING ON THIS SOLUTION
// FOR SOME REASON THE PROJECTS DON'T DISPLAY THEMSELVES WHEN LOGGED IN
$fork = $SOUP->fork();
$fork->set('title', $title);
$fork->set('id', $id);
if($hasPermission) {
$fork->set('creatable', true);
$fork->set('createLabel', 'New Projects');
}
$fork->startBlockSet('body');
if($hasPermission) {
?>
<script type="text/javascript">
$('#<?= $id ?> .createButton').click(function(){
window.location = '<?= Url::projectNew() ?>';
});
</script>
<?php
// Commenting out the code here allows the table headers to show, but
// still won't display the project info, when logged in.
}
// if(!empty($projects)) {
?>
<!-- FOR SOME REASON THIS ISN'T SHOWING IF YOU ARE LOGGED IN -->
<table class="projects">
<tr>
<th style="padding-left: 5px;">Projects</th>
<th>Status</th>
<th>Deadline</th>
<th>Members</th> <!-- Change this to Entries -->
<th>Category</th>
<!-- This still needs to be echo'd after backend work is done -->
<th>Reward</th>
<!-- This still needs to be echo'd after backend work is done -->
<?php if(!is_null($user)): ?>
<th>Role</th>
<?php endif; ?>
</tr>
<?php
foreach($projects as $p) {
echo '<tr>';
// title and pitch
echo '<td class="name">';
echo '<h6>
'.$p->getTitle().'</h6>';
echo '<p>';
// THIS CODE WILL DISPLAY THE PITCH UNDER TITLE OF PROJECT
// $pitch = strip_tags(formatPitch($p->getPitch()));
//echo substr($pitch,0,70);
//if(strlen($pitch) > 70)
// echo "…";
// echo '</p>';
// echo '</td>';
// status
$status = formatProjectStatus($p->getStatus());
echo '<td class="status">'.$status.'</td>';
// deadline
$deadline = $p->getDeadline();
$deadline = (empty($deadline)) ? '--' : formatTimeTag($deadline);
echo '<td class="deadline">'.$deadline.'</td>';
// members
*** CHANGE THIS TO THE NUMBER OF ENTRIES/CONTRIBUTIONS
$members = count($p->getAllMembers())+1;
echo '<td class="members">
'.$members.'</td>';
// role
if(!is_null($user)) {
$relationship = '';
if(ProjectUser::isCreator($user->getID(), $p->getID())) {
$relationship = 'creator';
}
elseif(ProjectUser::isTrusted($user->getID(), $p->getID())) {
$relationship = 'trusted member';
}
elseif(ProjectUser::isMember($user->getID(), $p->getID())) {
$relationship = 'member';
}
elseif(ProjectUser::isFollower($user->getID(),$p->getID())) {
$relationship = 'follower';
}
echo '<td class="role">'.$relationship.'</td>';
}
echo '</tr>';
}
?>
</table>
<?php
// }
// else {
// echo '<p>(none)</p>';
// }
$fork->endBlockSet();
$fork->render('site/partial/panel');
?>
****The code below this point works in conjunction with the code above here, which is contained in a separate file. So, I'm not sure if the issue is contained within this file, or the one above.
<?php
class ProjectUser extends DbObject
{
protected $id;
protected $userID;
protected $projectID;
protected $relationship;
const DB_TABLE = 'project_user';
const BANNED = 0;
const FOLLOWER = 1;
const MEMBER = 5;
const TRUSTED = 10;
const CREATOR = 101;
// const TRUSTED = 1;
// const UNTRUSTED = 0;
//const ORGANIZER = 10;
public function __construct($args=array())
{
$defaultArgs = array(
'id' => null,
'user_id' => 0,
'project_id' => 0,
'relationship' => 0
);
$args += $defaultArgs;
$this->id = $args['id'];
$this->userID = $args['user_id'];
$this->projectID = $args['project_id'];
$this->relationship = $args['relationship'];
}
public static function load($id)
{
$db = Db::instance();
$obj = $db->fetch($id, __CLASS__, self::DB_TABLE);
return $obj;
}
public function save()
{
$db = Db::instance();
// map database fields to class properties; omit id and dateCreated
$db_properties = array(
' user_id' => $this->userID,
'project_id' => $this->projectID,
'relationship' => $this->relationship
);
$db->store($this, __CLASS__, self::DB_TABLE, $db_properties);
}
public function delete() {
$query = "DELETE from ".self::DB_TABLE;
$query .= " WHERE user_id = ".$this->userID;
$query .= " AND project_id = ".$this->projectID;
$db = Db::instance();
$db->execute($query);
ObjectCache::remove(get_class($this),$this->id);
}
public static function find($userID=null, $projectID=null) {
if( ($userID === null) ||
($projectID === null) ) {
return null;
}
$query = "SELECT id FROM ".self::DB_TABLE;
$query .= " WHERE user_id = ".$userID;
$query .= " AND project_id = ".$projectID;
$db = Db::instance();
$result = $db->lookup($query);
if(!mysql_num_rows($result))
return null;
elseif($row = mysql_fetch_assoc($result))
return (self::load($row['id']));
}
// used on profile page
public static function getProjectsByUserID($userID=null,
$limit=null) {
if($userID === null) return null;
$loggedInUserID = Session::getUserID();
$query = " SELECT pu.project_id AS id FROM ".self::DB_TABLE." pu";
$query .= " INNER JOIN ".Project::DB_TABLE." p ON";
$query .= " pu.project_id = p.id";
$query .= " WHERE pu.user_id = ".$userID;
$query .= " AND pu.relationship != ".self::BANNED;
// only show private projects if logged-in user is also a member
if(!empty($loggedInUserID)) {
$query .= " AND (p.private = 0";
$query .= " OR pu.project_id IN (";
$query .= " SELECT project_id FROM ".self::DB_TABLE;
$query .= " WHERE user_id = ".$loggedInUserID;
$query .= " AND relationship != ".self::BANNED;
$query .= " ))";
} else {
$query .= " AND p.private = 0";
}
$query .= " ORDER BY p.title ASC";
if(!empty($limit))
$query .= " LIMIT ".$limit;
$db = Db::instance();
$result = $db->lookup($query);
if(!mysql_num_rows($result)) return array();
$projects = array();
while($row = mysql_fetch_assoc($result))
$projects[$row['id']] = Project::load($row['id']);
return $projects;
}
public static function getAllMembers($projectID=null) {
if($projectID === null) return null;
$query = "SELECT user_id AS id FROM ".self::DB_TABLE." pu";
$query .= " INNER JOIN ".User::DB_TABLE." u ON ";
$query .= " pu.user_id = u.id";
$query .= " WHERE pu.project_id = ".$projectID;
$query .= " AND (pu.relationship = ".self::MEMBER;
$query .= " OR pu.relationship = ".self::TRUSTED.')';
$query .= " ORDER BY u.username ASC";
//echo $query.'<br />';
$db = Db::instance();
$result = $db->lookup($query);
if(!mysql_num_rows($result)) return array();
$users = array();
while($row = mysql_fetch_assoc($result))
$users[$row['id']] = User::load($row['id']);
return $users;
}
public static function getTrusted($projectID=null) {
return(self::getByProjectID($projectID, self::TRUSTED));
}
public static function getMembers($projectID=null) {
return(self::getByProjectID($projectID, self::MEMBER));
}
public static function getFollowers($projectID=null) {
return(self::getByProjectID($projectID, self::FOLLOWER));
}
public static function getBanned($projectID=null) {
return(self::getByProjectID($projectID, self::BANNED));
}
public static function getBannableUsernames($projectID=null,
$term=null) {
if($projectID === null) return null;
$query = "SELECT username FROM ".User::DB_TABLE;
$query .= " WHERE id NOT IN (";
$query .= " SELECT user_id FROM ".self::DB_TABLE;
$query .= " WHERE project_id = ".$projectID;
$query .= " AND relationship = ".self::BANNED; // can't be banned
$query .= " OR relationship = ".self::CREATOR; // can't be
creator
$query .= " )";
if(!empty($term))
$query .= " AND username LIKE '%".$term."%'";
$query .= " ORDER BY username ASC";
$db = Db::instance();
$result = $db->lookup($query);
if(!mysql_num_rows($result)) return array();
$usernames = array();
while($row = mysql_fetch_assoc($result))
$usernames[] = $row['username'];
return $usernames;
}
public static function getTrustedUsernames($projectID=null,
$term=null) {
if($projectID === null) return null;
$query = "SELECT u.username AS username FROM ".User::DB_TABLE."
u";
$query .= " INNER JOIN ".self::DB_TABLE." pu";
$query .= " ON u.id = pu.user_id";
$query .= " WHERE pu.project_id = ".$projectID;
$query .= " AND (pu.relationship = ".self::TRUSTED;
$query .= " OR pu.relationship = ".self::CREATOR.")";
if(!empty($term))
$query .= " AND u.username LIKE '%".$term."%'";
$query .= " ORDER BY u.username ASC";
$db = Db::instance();
$result = $db->lookup($query);
if(!mysql_num_rows($result))
return array();
$usernames = array();
while($row = mysql_fetch_assoc($result))
$usernames[] = $row['username'];
return $usernames;
}
public static function getUnaffiliatedUsernames($projectID=null,
$term=null) {
if($projectID === null) return null;
$query = "SELECT username FROM ".User::DB_TABLE;
$query .= " WHERE id NOT IN (";
$query .= " SELECT user_id FROM ".self::DB_TABLE;
$query .= " WHERE project_id = ".$projectID;
$query .= " )";
if(!empty($term))
$query .= " AND username LIKE '%".$term."%'";
$query .= " ORDER BY username ASC";
$db = Db::instance();
$result = $db->lookup($query);
if(!mysql_num_rows($result))
return array();
$usernames = array();
while($row = mysql_fetch_assoc($result))
$usernames[] = $row['username'];
return $usernames;
}
public static function getByProjectID($projectID=null,
$relationship=null) {
if($projectID == null) return null;
$query = "SELECT user_id AS id FROM ".self::DB_TABLE." pu";
$query .= " INNER JOIN ".User::DB_TABLE." u ON ";
$query .= " pu.user_id = u.id";
$query .= " WHERE pu.project_id = ".$projectID;
if($relationship !== null) {
$query .= " AND pu.relationship = ".$relationship;
}
$query .= " ORDER BY u.username ASC";
//echo $query.'<br />';
$db = Db::instance();
$result = $db->lookup($query);
if(!mysql_num_rows($result)) return array();
$users = array();
while($row = mysql_fetch_assoc($result))
$users[$row['id']] = User::load($row['id']);
return $users;
}
public static function isCreator($userID=null, $projectID=null) {
return (self::hasRelationship($userID,$projectID,self::CREATOR));
}
public static function isTrusted($userID=null, $projectID=null) {
return (self::hasRelationship($userID,$projectID,self::TRUSTED));
}
public static function isMember($userID=null, $projectID=null) {
return (self::hasRelationship($userID,$projectID,self::MEMBER));
}
public static function isFollower($userID=null, $projectID=null)
{
return (self::hasRelationship($userID,$projectID,self::FOLLOWER));
}
public static function isBanned($userID=null, $projectID=null)
{
return (self::hasRelationship($userID,$projectID,self::BANNED));
}
public static function isAffiliated($userID=null, $projectID=null) {
return (self::hasRelationship($userID,$projectID));
}
// avoid calling this... use one of the aliased functions above
// instead
public static function hasRelationship($userID=null,
$projectID=null, $relationship=null) {
if( ($userID === null) || ($projectID === null) ) return null;
$query = "SELECT * FROM ".self::DB_TABLE;
$query .= " WHERE user_id = ".$userID;
$query .= " AND project_id = ".$projectID;
if($relationship !== null)
$query .= " AND relationship = ".$relationship;
//echo $query;
$db = Db::instance();
$result = $db->lookup($query);
if(!mysql_num_rows($result))
return false;
else
return true;
}
// --- only getters and setters below here --- //
public function getID()
{
return ($this->id);
}
public function setID($newID)
{
$this->id = $newID;
$this->modified = true;
}
public function getUserID()
{
return ($this->userID);
}
public function setUserID($newUserID)
{
$this->userID = $newUserID;
$this->modified = true;
}
public function getProjectID()
{
return ($this->projectID);
}
public function setProjectID($newProjectID)
{
$this->projectID = $newProjectID;
$this->modified = true;
}
public function getRelationship()
{
return ($this->relationship);
}
public function setRelationship($newRelationship)
{
$this->relationship = $newRelationship;
$this->modified = true;
}
}

How to print the result of a Phalcon query result?

There is a Phalcon query :
function lireParCritere($critere) {
$sSQL = "
SELECT c.salle_code,c.salle_lib,c.salle_comment
FROM salle as c WHERE 1 = 1 ";
if(isset($critere["salle_code"]) && $critere["salle_code"] != "") {
$sSQL .= "AND c.salle_code = ' " . $critere["salle_code"] . "' ";
}
$query = new Query($sSQL,$this->getDI());
$ret = $query->execute();
return $ret;
}
How to print the result of this query ?
\Phalcon\Mvc\Model\Query uses PHQL, not SQL.
public function lireParCritere($critere)
{
$model = '\Namespaced\Path\To\Salle';
$sSQL = "
SELECT c.salle_code,c.salle_lib,c.salle_comment
FROM $model as c WHERE 1 = 1 ";
if(isset($critere["salle_code"]) && $critere["salle_code"] != "") {
$sSQL .= "AND c.salle_code = ' " . $critere["salle_code"] . "' ";
}
$query = new \Phalcon\Mvc\Model\Query($sSQL, $this->getDI());
$ret = $query->execute();
return $ret;
}
public function test()
{
foreach ($this->lireParCritere([]) as $row) {
/** #var \Phalcon\Mvc\Model\Row $row */
assert($row->salle_code === $row->readAttribute('salle_code'));
}
}

php mysql return wrong boolean result

I have the following query :
'SELECT Active FROM tbUsers WHERE Id=55'
The Id is unique and I need just to know the status of the user if he's active yes or no. The Column Active is set as boolean in Mysql
When I tried to return the result like the following (using another php function) :
$result = $this->selectRow($db,"tbClass","Active","Id='$Id'");
if($result) { return "ok" ; } else { return "nok" ;)
it returns 'ok' on both cases.
Any idea what's wrong with it ?
Here is the other function :
public function selectRow($db,$tableName,$field,$where) {
if($where == "") {
$query = "SELECT $field FROM $tableName";
}
else
{ $query = "SELECT $field FROM $tableName WHERE $where"; }
$result=$db->Qry($query);
if ($result) {
$no_of_rows = $db->TotRows($result);
if($no_of_rows == 1) {
return $result;
}
if($no_of_rows == 0) {
return '';
}
if($no_of_rows < 0) {
die('Invalid query: ' . $sender ."(".$query ."): ".mysql_errno().": ". mysql_error());
return '';
}
}
else {
die('Invalid query: ' . $sender .": " .$query.": ". mysql_errno().": ". mysql_error());
return '';
}
}
Qry Function is the following :
function Qry($sql) {
if($result = mysqli_query($this->con,$sql) ) {
return $result;
}
else
{
$err = "Error: ".$sql. " :: ". mysqli_error;
die("$err");
}
}
I think you need to change this condition .
$result=$db->Qry($query);
always return you query object
Just remove this condition and
You need to count number of affected row
<?php
public function selectRow($db, $tableName, $field, $where) {
if ($where == "") {
$query = "SELECT $field FROM $tableName";
} else {
$query = "SELECT $field FROM $tableName WHERE $where";
}
$result = $db->Qry($query);
$no_of_rows = $db->TotRows($result);
if ($no_of_rows == 1) {
return $result;
}
if ($no_of_rows == 0) {
return FALSE;
}
if ($no_of_rows < 0) {
die('Invalid query: ' . $sender . "(" . $query . "): " . mysql_errno() . ": " . mysql_error());
return FALSE;
}
}
Alright, so $result is a mysqli_result object.
You might want to fetch the first row of that result and return the desired column.
Replace
return $result;
with
return $result->fetch_assoc()[$field];

Mysqli Class Always returns NULL for results with one var passed through

Every time I call a query with my class for select * from table where blank=blank it always comes up "NULL" on a var_dump for the results at the end of the class. I'm still stuck on this and don't know why it's doing it, but it sends no responses for sure, because I'm getting nothing back.
mysqli.class.php
<?php
class DATABASE
{
//set up variables only for this class
private $db_host;
private $db_user;
private $db_pass;
private $db_name;
private $connection;
private $paramaters = array();
private $results = array();
private $numrows;
//call connection on call of class
public function __construct($db_host, $db_user, $db_pass, $db_name)
{
$this->host = $db_host;
$this->user = $db_user;
$this->pass = $db_pass;
$this->name = $db_name;
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name) or die('There was a problem connecting to the database! Error #: '. $this->mysqli->connect_errno);
}
//close mysqli connection on class close
public function __destruct()
{
$this->mysqli->close();
}
//query
public function select($fields, $table, $where, $whereVal, $type, $orderByVal, $ASDESC, $limitVal, $sets, $setVal)
{
switch($type)
{
case "regular":
if ($where == null)
{
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = "";
} else {
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = " WHERE " . $where . " = ?";
}
break;
case "orderByLimit":
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = " ORDER BY " . $orderByVal . " " . $ASDESC . " LIMIT " . $limitVal;
break;
case "update":
if ($where == null)
{
$queryPre = "UPDATE " . $table;
//need for loop for multiple sets, check for is_array and do multiple if so.
$querySuff = " SET " . $sets . " = " . $setVal;
} else {
$queryPre = "UPDATE " . $table;
//need for loop for multiple sets, check for is_array and do multiple if so.
$querySuff = " SET " . $sets . " = " . $setVal . " WHERE " . $where . " = ?";
}
break;
case "insert":
if ($sets == null)
{
$queryPre = "INSERT INTO " . $table;
$querySuff = " VALUES(" . setVal . ")";
} else {
$queryPre = "INSERT INTO " . $table . " (" . $sets . ")";
$querySuff = " VALUES(" . setVal . ")";
}
case "delete":
if ($where == null)
{
$queryPre = "DELETE FROM " . $table;
$querySuff = "";
} else {
$queryPre = "DELETE FROM " . $table;
$querySuff = " WHERE " . $where . " = ?";
}
}
//$sql = $queryPre . "" . $querySuff;
//var_dump($sql);
//exit;
$stmt = $this->mysqli->prepare($queryPre . "" . $querySuff) or die('There was a problem preparing the Query! Error#: '. $this->mysqli->errno);
if ($whereVal == null)
{
$stmt = $this->bindVars($stmt,$setVal);
} else {
$stmt = $this->bindVars($stmt,$whereVal);
}
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field())
{
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch())
{
$x = array();
foreach($row as $key => $val)
{
$x[$key] = $val;
}
$results[] = $x;
}
$stmt->close();
//var_dump($results);
if ($results == "" || $results == NULL)
{
return null;
} else {
return $results;
}
}
private function bindVars($stmt,$params)
{
if ($params != null)
{
$types = '';
//initial sting with types
if (is_array($params))
{
foreach($params as $param)
{
//for each element, determine type and add
if(is_int($param))
{
$types .= 'i'; //integer
} elseif (is_float($param))
{
$types .= 'd'; //double
} elseif (is_string($param))
{
$types .= 's'; //string
} else {
$types .= 'b'; //blob and unknown
}
}
} else {
if (is_int($params))
{
$types = 'i';
} elseif (is_float($params))
{
$types = 'd';
} elseif (is_string($params))
{
$types = 's';
} else {
$types = 'b';
}
}
$bind_names[] = $types;
if (is_array($params))
{
//go through incoming params and added em to array
for ($i=0; $i<count($params);$i++)
{
//give them an arbitrary name
$bind_name = 'bind' . $i;
//add the parameter to the variable variable
$$bind_name = $params[$i];
//now associate the variable as an element in an array
$bind_names[] = &$$bind_name;
}
} else {
$int0 = 0;
$bind_name = 'bind' . $int0;
$$bind_name = $params;
$bind_names[] = &$$bind_name;
}
call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
return $stmt; //return the bound statement
}
}
?>
example to call and check fields - process_availability.php:
<?php
//require necessary files
require('../config/dbconfig.php');
include('../classes/mysqli.class.php');
//initiate connection
$mysqli = new DATABASE($db_host,$db_user,$db_pass,$db_name);
//take type of check
$checktype = $_POST['type'];
//check the user name
if ($checktype == "username") {
//change post to variable
$username = $_POST['username'];
//check if user name is empty
if ($username == "") {
$validuser = array("empty", "false");
echo implode(',', $validuser);
exit;
}
//if user name is more characters than 30
if (strlen($username) > 30) {
$validuser = array("max", "false");
echo implode(',', $validuser);
exit;
}
//search for same user name in database
$resultsU = $mysqli->select('*','users','username',$username,'regular',null,null,null,null,null);
//var_dump($resultsU);
if (is_array($resultsU))
{
var_dump($resultsU);
foreach($resultsU as $rowU)
{
//return results
if($rowU['username'] == "" || $rowU['username'] == NULL)
{
//user name is blank
$validuser = array("yes", "true");
echo implode(',', $validuser);
exit;
}
else {
//username is not blank, so it's taken
$validuser = array("no", "false");
echo implode(',', $validuser);
exit;
}
}
}
}
And just to show what I'm actually doing with the information, here is a PART of the java (just handles username mostly, there is a ton more for email, ect not included):
fiddle
And, of coarse, the link to the page: page link
I've been fixing other things on here, and on a technicality it works. I get a response if there IS something in the database that matches the username i type, but if there is no match, for some reason it doesn't respond at all.....
Specifically...right at the bottom of the 2nd to last function in the class:
$stmt->close();
//var_dump($results);
if ($results == "" || $results == NULL)
{
return null;
} else {
return $results;
}
When you are returning no results to the client, you need to indicate to the client that this is what you have done, and the code shown above simply outputs nothing in this case. While it is easily possible to handle this empty response correctly on the client side a better solution would be to do one of the following:
If you need the data from the result, json_encode() the results before sending them back to the client. This would mean that if the were no results you would return an empty array, but it would still be valid JSON and crucially you can easily check whether the result array is empty on the client side using result.length.
If you don't actually need the result data and all you need is to determine whether there were any results, you can simply return a 1 or a 0. This kind of boolean response takes minimal bandwidth and minimal processing, and the best thing about it is all you need to do is evaluate it as a boolean on the client side - i.e. if (result) { /* do stuff */ }

how do I make this function a class?

i've been creating functions for too long without taking my code to 'classes'.
I learn well through example and I just wanted to convert this simple function into a class so I can compare something I know with something I don't...
Take the following function:
function affiliateName($affiliateID) {
$sql = 'SELECT * FROM affiliates WHERE uID="' . $affiliateID . '" ';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
$affiliateName = $row['firstName'] . ' ' . $row['lastName'];
return $affiliateName;
}
And how would I make that a class?
<?php
class AffiliateModel
{
public function first($id)
{
$sql = 'SELECT *, CONCAT(firstName, ' ', lastName) AS qualifiedName FROM affiliates WHERE uID="' . $id . '" LIMIT 1';
$res = mysql_query($sql);
return mysql_fetch_object($res);
}
}
$model = new AffiliateModel();
$a = $model->first($id);
echo $a->qualifiedName;
?>
Hope it helps
<?php
class affiliate{
// fields or properties
public $name = '';
public $id = 0;
// constructor
public function affiliate($id = 0){
$this->set_ID($id);
}
// methods
public function set_ID($id){
return $this->id = $id;
}
public function get_Name(){
if($this->name != ""){
$sql = 'SELECT * FROM affiliates WHERE uID="' . $this->id . '" ';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
return $this->name = $row['firstName'] . ' ' . $row['lastName'];
}else{
return $this->name;
}
}
}
// Example:
$currentAffiliate = new affiliate(153);
echo $currentAffiliate->name;
?>
I prefer the following design as it is the simplest to use:
class affiliates {
static function load($id) {
return new self(intval($id));
}
private function __construct($id) {
$query = "SELECT * FROM affiliates WHERE id = " . intval($id);
$result = mysql_query($query);
// TODO: make sure query worked
foreach(mysql_fetch_assoc($result) as $field => $value)
$this->$field = $value;
}
// composite fields - made by combining and/or re-formatting other fields
function qualifiedName() {
return $this->firstName . ' ' . $this->lastName;
}
function properName() {
return $this->lastName . ', ' . $this->firstName;
}
}
$a = affiliates::load(22);
// all db fields are available as properties:
echo $a->id; // 22
echo $a->firstName; // Fred
echo $a->lastName; // Smith
// composite fields are methods
echo $a->qualifiedName(); // Fred Smith
echo $a->properName(); // Smith, Fred
// to get a single field from a particular person
echo affiliates::load(72)->qualifiedName();

Categories