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'));
}
}
Related
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; }
...
This is bizarre. I am working on a new website using WAMP on my pc and I copy and pasted the database functions I created from another site I worked on.
Below is the function. On this new site I'm getting an error (Notice: Undefined offset: 0) whenever there is nothing that matches in the database. But, on the other site (which is hosted externally) I never get that error (never have and I just tested it specifically to make sure).
Obviously, I could just put the "return $rows[0]" in an if statement to prevent this. But, I would like to know what is causing the problem in case I need to make some changes to the old site! I'm kind of worried!
There's also another difference. On the new site I get an error when the $order is NULL, saying that $s3 is undefined. Again, I can fix it easily by just defining it along with $s1 and $s2 at the beginning. But, it works fine on my other site and has for a long time. What on earth is the difference??
function get_row5($table, $field, $where1, $value1, $where2=NULL, $value2=NULL, $where3=NULL, $value3=NULL, $where4=NULL, $value4=NULL, $where5=NULL, $value5=NULL, $order=NULL) {
$rows = array();
global $conn;
connect();
$s1 = "SELECT $field FROM $table WHERE $where1" . '=' . "'$value1'";
$s2 = "";
if ($where2 != NULL) {
if ($value2 == NULL) {
$s2 = " and $where2 is NULL";
} else {
$s2 = " and $where2" . ' = ' . "'$value2'";
}
}
if ($where3 != NULL) {
if ($value3 == NULL) {
$s2 .= " and $where3 is NULL";
} else {
$s2 .= " and $where3" . ' = ' . "'$value3'";
}
}
if ($where4 != NULL) {
if ($value4 == NULL) {
$s2 .= " and $where4 is NULL";
} else {
$s2 .= " and $where4" . ' = ' . "'$value4'";
}
}
if ($where5 != NULL) {
if ($value5 == NULL) {
$s2 .= " and $where5 is NULL";
} else {
$s2 .= " and $where5" . ' = ' . "'$value5'";
}
}
if ($order != NULL) {
$s3 = " ORDER BY $order LIMIT 1";
}
$sql = $s1 . $s2 . $s3;
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
mysqli_free_result($result);
$conn->close();
return $rows[0];
}
You are geting this error because there is no row return from query you can overcome with following code
function get_row5($table, $field, $where1, $value1, $where2=NULL, $value2=NULL, $where3=NULL, $value3=NULL, $where4=NULL, $value4=NULL, $where5=NULL, $value5=NULL, $order=NULL) {
$rows = array();
global $conn;
connect();
$s1 = "SELECT $field FROM $table WHERE $where1" . '=' . "'$value1'";
$s2 = "";
$s3 = "";
if ($where2 != NULL) {
if ($value2 == NULL) {
$s2 = " and $where2 is NULL";
} else {
$s2 = " and $where2" . ' = ' . "'$value2'";
}
}
if ($where3 != NULL) {
if ($value3 == NULL) {
$s2 .= " and $where3 is NULL";
} else {
$s2 .= " and $where3" . ' = ' . "'$value3'";
}
}
if ($where4 != NULL) {
if ($value4 == NULL) {
$s2 .= " and $where4 is NULL";
} else {
$s2 .= " and $where4" . ' = ' . "'$value4'";
}
}
if ($where5 != NULL) {
if ($value5 == NULL) {
$s2 .= " and $where5 is NULL";
} else {
$s2 .= " and $where5" . ' = ' . "'$value5'";
}
}
if ($order != NULL) {
$s3 = " ORDER BY $order LIMIT 1";
}
$sql = $s1 . $s2 . $s3;
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
mysqli_free_result($result);
$conn->close();
if(count($rows))
return $rows[0];
else
return $rows; //<---empty row
}
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;
}
}
I'm using SensioLabsInsight to profile any vulnerabilities in my code.
I've received several errors for possible sql injection, and it recommends using parameter binding with PDO. This is fine since I'm already using PDO for my db driver.
Right now my model is passed a $data array and then checks for specific values in the array in order to add to the sql query if present, like so:
public function getDownloads($data = array()) {
$sql = "
SELECT *
FROM {$this->db->prefix}download d
LEFT JOIN {$this->db->prefix}download_description dd
ON (d.download_id = dd.download_id)
WHERE dd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
if (!empty($data['filter_name'])) {
$sql .= " AND dd.name LIKE '" . $this->db->escape($data['filter_name']) . "%'";
}
$sort_data = array(
'dd.name',
'd.remaining'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY dd.name";
}
if (isset($data['order']) && ($data['order'] == 'DESC')) {
$sql .= " DESC";
} else {
$sql .= " ASC";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->rows;
}
The error referenced from the SensioLabsInsight analysis references only the $data['sort'] clause as being a possible injection point.
My question is, do I need to test for $data array presence when creating a prepare statement, or will it simply return null if the array value is empty.
My proposed new query with parameter binding would look like so:
public function getDownloads($data = array()) {
$sql = "
SELECT *
FROM {$this->db->prefix}download d
LEFT JOIN {$this->db->prefix}download_description dd
ON (d.download_id = dd.download_id)
WHERE dd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
if (!empty($data['filter_name'])) {
$sql .= " AND dd.name LIKE :filter_name%";
}
$sort_data = array(
'dd.name',
'd.remaining'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY :sort";
} else {
$sql .= " ORDER BY dd.name";
}
if (isset($data['order']) && ($data['order'] == 'DESC')) {
$sql .= " DESC";
} else {
$sql .= " ASC";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT :start, :limit";
}
$this->db->prepare($sql);
$this->db->bindParam(':filter_name', $data['filter_name']);
$this->db->bindParam(':sort', $data['sort']);
$this->db->bindParam(':start', $data['start'], PDO::PARAM_INT);
$this->db->bindParam(':limit', $data['limit'], PDO::PARAM_INT);
$query = $this->db->execute();
return $query->rows;
}
Will this work as is, or do the parameter bindings need to be moved within the if/else conditionals?
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
}