Can not pass id to url - php

I have the following button which should delete the item which has been chosen
$content .= "<td> " . "<a href=/index.php?p=3&id=$id>delete</a>";
However this always sends me to:
http://localhost/index.php?p=3&id=
When p=3 it should call the following function:
case 3:
$items = new dbconnection();
$content = $items->deleteItem($_GET['id']);
/
public $id;
public function deleteItems($id) {
$conn = dbconnection::startconnection();
$this->id = $id;
$sql = "DELETE FROM items where id = '$this->id'";
$stmt = $conn->prepare($sql);
$stmt->execute();
$content ="<p>" . "<a href=index.php>Go back</a>" . "</p>";
return $content;
}
public function __construct($id = 1) {
}
Why is the ID not getting send to the URL?

Related

Php - Validations and errors - unique name

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

why are my php object member variables null after instantiating them?

I'm trying to make an api in php. In this part I query my database and load the data into chuckquote objects then add those objects to an array to be encoded in json and received whenever the app sends a get request.
When I echo the query results every thing comes out fine but if i echo the id right after it gets instantiated its something completely different and when I encode the array everything is NULL and there is a 5th blank row that now contains the dates. How do I fix this or at least what am i doing wrong here ?
if($method == "GET")
{
$sql = "SELECT * FROM chuckquotes";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
//echo " " . $row["ID"] . " " . $row["quote"] . " " . $row["author"] . " " . $row["datentime"] . " " ;
$crow = new chuckquote;
echo $crow->$id = $row["ID"];
$crow->$quote = $row["quote"];
$crow->$author = $row["author"];
$crow->$date = $row["datentime"];
$Jsonarray[] = $crow;
}
echo json_encode($Jsonarray);
}
else
{
echo "0 results";
}
$conn->close();
}
Class
class chuckquote
{
public $id;
public $quote;
public $author;
public $date;
}
OUTPUT:
[{"id":null,"quote":null,"author":null,"date":null,"":"2019-02-17 06:47:13"},{"id":null,"quote":null,"author":null,"date":null,"":"2019-02-17 06:47:13"},{"id":null,"quote":null,"author":null,"date":null,"":"2019-02-17 06:47:13"},{"id":null,"quote":null,"author":null,"date":null,"":"2019-02-17 06:47:13"}]
Remove the $ sign from the property name. From
echo $crow->$id = $row["ID"];
$crow->$quote = $row["quote"];
$crow->$author = $row["author"];
$crow->$date = $row["datentime"];
to
$crow->id = $row["ID"];
$crow->quote = $row["quote"];
$crow->author = $row["author"];
$crow->date = $row["datentime"];
In php, you don't need to use $ sign while accessing a class property.
Although it's best practice to create a constructor for this assignment. Example class with constructor.
class chuckquote
{
public $id;
public $quote;
public $author;
public $date;
/**
* chuckquote constructor.
* #param $id
* #param $quote
* #param $author
* #param $date
*/
public function __construct($id, $quote, $author, $date)
{
$this->id = $id;
$this->quote = $quote;
$this->author = $author;
$this->date = $date;
}
}
And then you can assign the values when instantiate the class.
$crow = new chuckquote($row["ID"], $row["quote"], $row["author"], $row["datentime"]);

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

(not all) Data can't reach database

I want to send data to my database (group_id, user_id and group_name) but only the first two are getting into the database. When I var_dump $groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname); it gives me the correct group_name. What am I doing wrong?
When I replace '" . $db->conn->real_escape_string($this->Invitation_group_name) . "' with a random word it is working well..
PHP
$groupinvitation = new GroupInvitation();
if (isset($_POST["Accept"])) {
try {
$group_id = mysql_real_escape_string($_POST["group_id"]);
$groupinfo = $group->GetGroupInfoByGroupId($group_id);
$groupname = $groupinfo['group_name'];
$requestnumber = mysql_real_escape_string($_POST['acceptID']);
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
$feedback = "Awesome, You just added a friend!";
} catch(Exception $e) {
$feedback = $e -> getMessage();
}
}
DECLARATIONS:
class GroupInvitation
{
private $m_sGroup_invitation_group_name;
public function __set($p_sProperty, $p_vValue)
{
switch($p_sProperty)
{
case "Invitation_group_name":
$this->m_sGroup_invitation_group_name = $p_vValue;
break;
}
}
public function __get($p_sProperty)
{
switch($p_sProperty)
{
case "Invitation_group_name":
return $this->m_sGroup_invitation_group_name ;
break;
}
}
FUNCTION:
public function AddAsGroupMember($number, $group_id)
{
$db = new Db();
$insert = "INSERT INTO tblgroup_member(
group_id,
user_id,
group_name
) VALUES (
'" . $db->conn->real_escape_string($group_id) . "',
'" . $db->conn->real_escape_string($number) . "',
'" . $db->conn->real_escape_string($this->Invitation_group_name) . "'
)";
$db->conn->query($insert);
}
Try changing
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
to
$groupinvitation->Invitation_group_name = mysql_real_escape_string($groupname);
$groupinvitation->AddAsGroupMember($number, $group_id);
$groupinvitation-> AcceptGroupRequest($requestnumber);
You could be setting the property after the insert.

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