Give back more than one mysql result in an php class - php

I'm trying to build my own CMS in classes.
Now I have got a problem when I try to get data from my MySQL database
Instead of one item i'd like to get an collection of all my items
At the end I'd like to get an Object so I can read it out like : $item->id
Here's my code :
static function getContentItems($id, $active, $sort_by, $sort_type, $limit) {
if (isset($id) && !empty($id)) {
$where .= "WHERE id = ".$id;
}
if (isset($active) && !empty($active)) {
$where .= " AND active = ".$active;
}
if (isset($sort_by) && !empty($sort_by)) {
$where .= " ORDER BY ".$sort_by;
if (isset($sort_type) && !empty($sort_type)) {
$where .= " ".$sort_type;
}
}
if (isset($limit) && !empty($limit)) {
$where .= " LIMIT 0,".$limit;
}
if (isset($where) && !empty($where)) {
$query = "SELECT * FROM content ".$where;
} else {
$query = "SELECT * FROM content";
}
$result = mysql_query($query)or die(mysql_error());
$item = new ContentItem();
while ($data = mysql_fetch_array($result)) {
$item->id = $data['id'];
}
return $item;
}
}

dont start your $where string with .
if (isset($id) && !empty($id)) {
$where = "WHERE id = ".$id;
}
and alwez print your $query
Better Solution
if (!empty($id) {
$where = " WHERE id = ".$id;
if (!empty($active)) {
$where .= " AND active = ".$active;
if (!empty($sort_by)) {
$where .= " ORDER BY ".$sort_by;
if (!empty($sort_type)) {
$where .= " ".$sort_type;
}
}
}
}
if (empty($limit)) {
$where .= " LIMIT 0,".$limit;
}
and later
$item = new ContentItem();
$data = array(); $i=0;
while ($data = mysql_fetch_object($result)) {
$search_result[$i] = $data;
$i++;
}
return $search_result;
and any id can be retrieve by $search_result[$i]->id

Why don't you use Arrays?
Like this:
$collection = array();
while ($data = mysql_fetch_array($result)) {
$item = new ContentItem();
$item->id = $data['id'];
$collection[] = $item; //Appends the item to the array
}
return $collection;
You can access your array in this way:
$collection = YourClassName::getContentItems(...);
foreach($collection as $item) {
// do something with each $item
print_r($item);
}

Look into using mysql_fetch_object http://php.net/manual/en/function.mysql-fetch-object.php instead of mysql_fetch_array.. it returns rows the db as an object already

Related

Search function in ajax not working due to failing where statement

I'm doing a table with sort, page and search function.First of all, the code runs well, but after I added where in my sql, the search function doesn't work anymore.
<?php
include_once("connection.php");
session_start();
$db = new dbObj();
$connString = $db->getConnstring();
$params = $_REQUEST;
$action = isset($params['action']) != '' ? $params['action'] : '';
$empCls = new cusinfo($connString);
switch($action)
{
default:
$empCls->getEmployees($params);
return;
}
class cusinfo
{
protected $conn;
protected $data = array();
function __construct($connString)
{
$this->conn = $connString;
}
public function getEmployees($params)
{
$this->data = $this->getRecords($params);
echo json_encode($this->data);
}
function getRecords($params) {
$rp = isset($params['rowCount']) ? $params['rowCount'] : 10;
if (isset($params['current'])) { $page = $params['current']; } else { $page=1; };
$start_from = ($page-1) * $rp;
$sql = $sqlRec = $sqlTot = $where = '';
if( !empty($params['searchPhrase']) )
{
$where .=" WHERE ";
$where .=" ( NO_ID LIKE '".$params['searchPhrase']."%' ";
$where .=" OR TICKET_ID LIKE '".$params['searchPhrase']."%' ";
$where .=" OR CAT_C_B LIKE '".$params['searchPhrase']."%' ";
$where .=" OR ORDER_TYPE LIKE '".$params['searchPhrase']."%' ";
$where .=" OR AGENT_STAFF_NAME LIKE '".$params['searchPhrase']."%' ";
$where .=" OR EFORM_ID LIKE '".$params['searchPhrase']."%' ";
$where .=" OR LATEST_ORDER_STATUS LIKE '".$params['searchPhrase']."%' )";
}
if( !empty($params['sort']) )
{
$where .=" ORDER By ".key($params['sort']) .' '.current($params['sort'])." ";
}
// getting total number records without any search
$role = $_SESSION['sess_userrole'];
$uid = $_SESSION['sess_user_id'];
$tid = $_SESSION['tmid'];
$mid = $_SESSION['mid'];
$sid = $_SESSION['sid'];
if($role=="admin")
{
$sql = "SELECT * FROM `cusinfo` where AGENT_CODE_STAFF_ID IN (SELECT id FROM `users` where tm_groupid = '$tid') ";
$sqlTot .= $sql;
$sqlRec .= $sql;
}
else
{
.
.
.
}
//concatenate search sql if value exist
if(isset($where) && $where != '')
{
$sqlTot .= $where;
$sqlRec .= $where;
}
if ($rp!=-1)
$sqlRec .= " LIMIT ". $start_from .",".$rp;
$qtot = mysqli_query($this->conn, $sqlTot) or die("error to fetch tot customer data");
$queryRecords = mysqli_query($this->conn, $sqlRec) or die("error to fetch customer data");
while( $row = mysqli_fetch_assoc($queryRecords) )
{
$data[] = $row;
}
$json_data = array(
"current" => $page,
"rowCount" => 10,
"total" => intval($qtot->num_rows),
"rows" => $data // total data array
);
return $json_data;
}
}
?>
Thankyou for all of the reply,this question have been solve by myself.It can be solve by just change the where to AND on the code bellow:
if( !empty($params['searchPhrase']) )
{
$where .=" WHERE";//change this line to $where .=" AND";
.
.
.
}

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;
}
}

Displaying MySQL results in two columns (editing existing code)

I have been asked to revise an existing site, it's still using PHP5.3 and an old version of PHPmyDirectory, and the code is a little messy.
I'm trying to revise it to just display the list of cities in two columns. I'm trying to do it as a table, as it seemed easiest, but I could also just pull the results into to side by side divs, as there are never more than 26 cities listed (so first half or first 13 in div one, the rest in div two).
Here's the existing original code (I know its not mysqli, but we'll be redoing this site shortly so there's no sense trying to redo a million pages of code right now):
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
$output = "<p>";
$result_array = array();
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
while ($service2 = fetch_array($result2))
{
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
$output .= "<br/>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
$output .="</p>";
}
}
return $output;
}
This is what is looks like currently: Current Site
Here's what I've tried to do:
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
$result_array = array();
while ($service = fetch_array($result)) {
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
$i=0;
if(!$result2) {
break;
}
else {
while ($service2 = fetch_array($result2)) {
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
$i++;
}
echo "<table>";
for ($j=0; $j<$i; $j=$j+2) {
echo "<tr>";
echo "<td>".$title_array[$j]."</td><td>".$title_array[$j+1]."</td>";
echo "</tr>";
}
echo "</table>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<p><b>".$title." will travel for an additional fee!</b></p>";
}
else {
$output .="";
}
}
return $output;
}
And here's what I'm getting: DEV site
I'm very much a PHP newbie, and my understanding is pretty spotty, but I've tried a bunch of different solutions I've found here, and can't get them to work. I'm sure I'm missing something obvious.
Thanks for any pointers!
if I got it correct you should change your
else {
$output = "<p>";
$result_array = array();
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
while ($service2 = fetch_array($result2))
{
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
$output .= "<br/>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
$output .="</p>";
}
}
with
else {
$output = "<table>";
$result_array = array();
$even_odd=true;
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
$output .= "";
while ($service2 = fetch_array($result2))
{
if ($even_odd) {
$output .= '<tr><td>'."{$service2['title']}".'</td>';
$even_odd=false;
} else {
$output .= '<td>'."{$service2['title']}".'</td></tr>';
$even_odd=true;
}
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
if (!$even_odd)$output .="<td></td></tr>";
$output .="</table>";
}
}
Try this, I couldn't test it of course, since I've got no access to the data being loaded.
echo "<table>";
$result_array = array();
while ($service = fetch_array($result))
{
//this will loop multiple times. 7 times for Tony S. in the example.
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
$i=0;
if(!$result2)
{
break;
}
else
{
while ($service2 = fetch_array($result2))
{
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
$i++;
}
}
}
for ($j=0; $j < count($result_array); $j++)
{
if ($j % 2 == 0)
{
echo "<tr>";
}
echo "<td>".$result_array[$j][0]." (".$result_array[$j][1].")</td>";
if ($j % 2 == 0)
{
echo "</tr>";
}
if ($j % 2 == 1 && $j == count($result_array)-1)
{
echo "<td></td></tr>";
}
}
echo "</table>";
Paste and replace between this lines:
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
.... PASTE IN HERE ....
}
Building on Kim's code, I was able to get it working with some revisions. I also scrapped the table for divs, since it seems less messy to me and it seemed like the table styling was interfering somehow.
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
} else {
$output = "<div>";
//$result_array = array();
$even_odd=true;
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
while ($service2 = fetch_array($result2))
{
if ($even_odd) {
$output .= '<div style="float:left;width:50%;">'."{$service2['title']}".'</div>';
$even_odd=false;
} else {
$output .= '<div style="float:right;width:50%;">'."{$service2['title']}".'</div>';
$even_odd=true;
}
}
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<div style='clear:both;width:90%;float:none;'><p><b>".$title." will travel for an additional fee!</b></p></div>";
} else {
}
}
return $output;
}
Thanks so much Kim and Mouser!

two methods in a class so close in what they do

I have this class that has these two methods that are so closely related to the each other. I do not want to pass the flags so I kept them separate. I was wondering if there is a way to rewrite it so that I do not have to repeat so closely!
class Test extends Controller
{
public static function nonFormattedData($param)
{
$arr = array();
if (is_array($param)) {
$i = 0;
$sql = "
select *
from table1
where
";
if (isset($param['startDate'])) {
$sql .= " date_created between ? AND ?";
$arr[] = $param['startDate'];
$arr[] = $param['endDate'];
$i++;
}
if (isset($param['amount']) && !empty($param['amount'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " balance= ?";
$arr[] = $param['amount'];
$i++;
}
if (isset($param) && !empty($param['amount'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " balance= ?";
$arr[] = $param['amount'];
$i++;
}
if (isset($param['createdBy']) && !empty($param['createdBy'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " column2 like '%Created By: " . $param['createdBy'] . "%'";
}
$sql .= ' group by id.table1 ';
$rs = Query::RunQuery($sql, $arr);
foreach ($rs as $row) {
$records = new Account();
$results[] = $records;
}
return $results;
}
}
public static function formattedData($serArray, $orderBy = "giftcardaccount_id desc", $offset = 0, $limit = 10)
{
$arr = array();
if (is_array($param)) {
$i = 0;
$sql = "
select *
from table1
where
";
if (isset($param['startDate'])) {
$sql .= " date_created between ? AND ?";
$arr[] = $param['startDate'];
$arr[] = $param['endDate'];
$i++;
}
if (isset($param['amount']) && !empty($param['amount'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " balance= ?";
$arr[] = $param['amount'];
$i++;
}
if (isset($param) && !empty($param['amount'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " balance= ?";
$arr[] = $param['amount'];
$i++;
}
if (isset($param['createdBy']) && !empty($param['createdBy'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " column2 like '%Created By: " . $param['createdBy'] . "%'";
}
$sql .= ' group by id.table1 ';
$rs = Query::RunQuery($sql, $arr);
return array("data" => $rs);
}
}
}
Why not have one method, but with an optional formatting options object/array?
public static function getData($params, $formatting = null) {
// continue as normal, adding formatting if it's there
}

SQL Multiple WHERE Clause Problem

I'm attempting the modify this Modx Snippet so that it will accept multiple values being returned from the db instead of the default one.
tvTags, by default, was only meant to be set to one variable. I modified it a bit so that it's exploded into a list of variables. I'd like to query the database for each of these variables and return the tags associated with each. However, I'm having difficulty as I'm fairly new to SQL and PHP.
I plugged in $region and it works, but I'm not really sure how to add in more WHERE clauses for the $countries variable.
Thanks for your help!
if (!function_exists('getTags')) {
function getTags($cIDs, $tvTags, $days) {
global $modx, $parent;
$docTags = array ();
$baspath= $modx->config["base_path"] . "manager/includes";
include_once $baspath . "/tmplvars.format.inc.php";
include_once $baspath . "/tmplvars.commands.inc.php";
if ($days > 0) {
$pub_date = mktime() - $days*24*60*60;
} else {
$pub_date = 0;
}
list($region, $countries) = explode(",", $tvTags);
$tb1 = $modx->getFullTableName("site_tmplvar_contentvalues");
$tb2 = $modx->getFullTableName("site_tmplvars");
$tb_content = $modx->getFullTableName("site_content");
$query = "SELECT stv.name,stc.tmplvarid,stc.contentid,stv.type,stv.display,stv.display_params,stc.value";
$query .= " FROM ".$tb1." stc LEFT JOIN ".$tb2." stv ON stv.id=stc.tmplvarid ";
$query .= " LEFT JOIN $tb_content tb_content ON stc.contentid=tb_content.id ";
$query .= " WHERE stv.name='".$region."' AND stc.contentid IN (".implode($cIDs,",").") ";
$query .= " AND tb_content.pub_date >= '$pub_date' ";
$query .= " AND tb_content.published = 1 ";
$query .= " ORDER BY stc.contentid ASC;";
$rs = $modx->db->query($query);
$tot = $modx->db->getRecordCount($rs);
$resourceArray = array();
for($i=0;$i<$tot;$i++) {
$row = #$modx->fetchRow($rs);
$docTags[$row['contentid']]['tags'] = getTVDisplayFormat($row['name'], $row['value'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
}
if ($tot != count($cIDs)) {
$query = "SELECT name,type,display,display_params,default_text";
$query .= " FROM $tb2";
$query .= " WHERE name='".$region."' LIMIT 1";
$rs = $modx->db->query($query);
$row = #$modx->fetchRow($rs);
$defaultOutput = getTVDisplayFormat($row['name'], $row['default_text'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
foreach ($cIDs as $id) {
if (!isset($docTags[$id]['tags'])) {
$docTags[$id]['tags'] = $defaultOutput;
}
}
}
return $docTags;
}
}
You don't add in more WHERE clauses, you use ANDs and ORs in the already existing where clause. I would say after the line $query .= " WHERE stv.name = '".$region... you put in
foreach ($countries as $country)
{
$query .= "OR stv.name = '{$country}', ";
}
but I don't know how you want the query to work.

Categories