Specifying which data to display based on ID using Yii - php

I have a web application that contains a link towards the "album" section of my application. My problem right now is that it's showing the albums created for ALL users (and this goes the same for all members within the application). I want that whenever a user who is logged in selects the "phots" link, he/she is directed into the album page where they can only see the pictures that THEY uploaded.
To begin, this is the schema wherein the photos are being uploaded into.:
CREATE TABLE IF NOT EXISTS `content` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`node_type_id` int(11) DEFAULT NULL,
`party_id` int(11) DEFAULT NULL,
`category` text,
`title` text,
`content` text CHARACTER SET utf8 COLLATE utf8_unicode_ci,
`date_created` datetime DEFAULT NULL,
`date_modified` datetime DEFAULT NULL,
`start_date` datetime DEFAULT NULL,
`end_date` datetime DEFAULT NULL,
`status` int(11) DEFAULT NULL,
`content_id` int(11) NOT NULL,
`country` text NOT NULL,
`view_count` int(11) NOT NULL,
`attribute1` varchar(200) DEFAULT NULL,
`attribute2` varchar(50) DEFAULT NULL,
`liked` text,
`approved` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
Then this is where the album is being viewed:
<div class="photodiv">
<?php
foreach ($albumArr as $album)
{
Yii::app()->user->id;
$image = Image::model()->findByAttributes(array('content_id'=>$album->id, 'attribute1'=>'1'));
$photos = Image::model()->findAllByAttributes(array('content_id'=>$album->id));
echo '<div class="albumdiv">';
echo '<div class="picdiv">';
if (!empty($image))
{
echo '<img src="'.Yii::app()->baseUrl.'/images/albums/'.$album->content.'/'.$image->id.$image->content.'" height="100px" width="100px" />';
}
echo '</div>';
echo '<br/>';
echo '<center><h4>'.$album->content.'</h4></center>';
echo count($photos) == 1 ? '<center><h5>'.count($photos).' photo</h5></center>' : '<center><h5>'.count($photos).' photos</h5></center>';
echo '</div>';
}
?>
</div>
If you are wondering how this was generated, the controller contained the following:
public function actionIndex()
{
$usertag = isset($_GET['usertag']) ? addslashes($_GET['usertag']) : FALSE;
$users = new CActiveDataProvider('SystemUser', array(
'id' => '',
'criteria' => array(
'alias'=>'u',
'join'=>'JOIN persons p ON u.party_id = p.party_id JOIN lookup_codes lc ON p.country = lc.id',
'condition' => $usertag ? 'status != "Approved" AND company_name LIKE "%'.$usertag.'%" OR status = "'.$usertag.'"' : 'status != "Approved"',
//'order'=> 'date_created DESC'
'order'=> 'status'
),
'pagination' => array(
'pageSize' => 100
)
));
$data = array(
'dataProvider' => $users
);
$this->render('index', $data);
}
And index rendered the _view which I showed 2 scripts ago.
My problem is I'm not quite sure how to display only the specific creator of the album. In this case, 'party_id' is the ID that identifies who the creator is.

Ok If i understood you correctly then I am making some assumptions prior to answer your question.
1. Normally user table is used to login a user and store credentials like username,password, rememberme, and other attributes, but in your case i assume you are using person table for logging in a user.
2. In userIdentity.php you are using person model for verification purpose.
Then you need to do like this.
First create a function in your UserIdentity.php file
public function getId()
{
return $this->_id;
}
it will return the id of the person.
Now in your view file you can use this code to get id of logged in user
$id=Yii::app()->user->getId()
Now you can use it in your criteria like
$image = Image::model()->findByAttributes(array('content_id'=>$album->id,'party_id'=>$id, 'attribute1'=>'1'));
$photos = Image::model()->findAllByAttributes(array('content_id'=>$album->id,'party_id'=>$id,));
This will give you the results on for the logged in user.
Edit:
For your next question
If you are able to display a link and pass some user id in that link then you can do like this.
1. Where you are showing the link for a user pass this link id of that user like
CHtml::link('ViewAlbum',array('controller/userAlbum',array('id'=>userId)))
2. Create action for specific user
public function actionUserAlbum($id)
{
album=Album::model()->findAllByAttributes(array(
'id_of_creator_of_album'=>$id;
));
$this->render('someView',array('id'=>$id))
}
then use us this id in your view to get photos related to that album

Related

Cortex hasMany not creating entries in m2m table

Hi I coudln't get Cortex hasMany to hasMany relation working so I made a simple test. I created two classes, CortexTestA and CortexTestB in my models namespace
namespace models;
use DB\Cortex;
class CortexTestA extends Cortex {
protected $fieldConf = array(
'name' => array(
'type' => 'VARCHAR256',
'nullable' => false
),
'cortextestb' => array(
'has-many' => array('models\CortexTestB', 'cortextesta', 'cortextest_a_b')
)
);
// constructor etc. follows
This is the field conf for CortexTestB:
'cortextesta' => array(
'has-many' => array('models\CortexTestA', 'cortextestb', 'cortextest_a_b')
)
Next I ran the setup command
\Models\CortexTestA::setup();
\Models\CortexTestB::setup();
But already something strange happens, both tables now have obsolete fields:
CREATE TABLE IF NOT EXISTS `cortextesta` (
`id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`cortextestb` int(11) DEFAULT NULL
)
CREATE TABLE IF NOT EXISTS `cortextestb` (
`id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`cortextesta` int(11) DEFAULT NULL
)
The m2m table does get created correctly though:
CREATE TABLE IF NOT EXISTS `cortextest_a_b` (
`id` int(11) NOT NULL,
`cortextesta` int(11) DEFAULT NULL,
`cortextestb` int(11) DEFAULT NULL
)
But now when I run this
$cta = new \models\CortexTestA();
$cta->name = "SomethingA";
$cta->save();
// Results in: INSERT INTO `cortextesta` (`id`, `name`, `cortextestb`) VALUES
// (1, 'SomthingA', NULL);
and then this:
$cta = new \models\CortexTestA();
$cta->load(array('id = ?', 1));
$ctb = new \models\CortexTestB();
$ctb->name = "SomethingB";
$ctb->cortextesta[] = $cta;
$ctb->save();
the relationship table cortextest_a_b remains empty.
What am I doing wrong?
When the relation is still empty, the property getter currently returns NULL. That's why the array modification unfortunately doesn't work. You can easily workaround that like this:
if (!$ctb->cortextesta)
$ctb->cortextesta = array($cta);
else
$ctb->cortextesta[] = $cta;
$ctb->save();
I'll see if I can optimized this a bit. The issue about the obsolete fields is indeed a bug. I'll patch that soon. thanks.

Associations are not loaded when selecting fields

I am having some trouble trying to fetch associated models when selecting fields. My version of CakePHP is 3.0beta2.
Three MYSQL tables that are relevant to this question:
users:
`id` int(11) NOT NULL,
`username` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`role` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
... (more information)
-
presets:
`id` int(11) NOT NULL,
`name` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(11) NOT NULL,
... (more information)
-
favorites:
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`preset_id` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
My associations are defined as shown below:
// From FavoritesTable.php
public function initialize(array $config) {
$this->belongsTo('Users');
$this->belongsTo('Presets');
}
// From PresetsTable.php
public function initialize(array $config) {
$this->belongsTo('Users');
$this->hasMany('Favorites');
}
// From UsersTable.php
public function initialize(array $config) {
$this->hasMany('Presets');
$this->hasMany('Favorites');
}
What I'm trying to achieve is:
Load all the user information for the currently logged in user
Load all the favorites that this user has
Create a new field that transforms the created field (a timestamp) into a date
For each favorite, load the associated preset data
This is the code that I use to do that:
// From UsersController.php
public function favorites() {
$userId = $this->Auth->user('id');
$user = $this->Users->find('all')
->where(['id' => $userId])
->contain([
'Favorites' => function($q) {
return $q
->select(['id', 'preset_id', 'user_id', 'created', 'date' => 'DATE(created)'])
->order(['Favorites.created' => 'DESC']);
},
'Favorites.Presets',
])
->first();
$this->set('user', $user);
}
The problem is: when I use the select method as in the code above, the Favorites.Presets association is not loaded, so $user['favorites'][0]['preset'] is always null.
But if I comment out the select method (thus selecting all fields and not retrieving DATE(created), the association is loaded and I can access the information from the presets table.
Could this be a bug or am I doing something wrong?
Thanks for the help!
I think you need to call ->autoFields(true) after select(). This is required if you expect all other fields to be selected. This could probably be seen as a bug, try opening a ticket in github.

Assigning the value of a table row ID with another ID using an SQL statement

So in my database i have two tables. Jokes and Comments. I want the ability to assign the post_id of the comment, to the joke_id of the joke, so it will assign and retrieve the comments relating to that joke. My problem is that i suck at writing SQL statements and haven't the foggiest on how to join two tables to make this happen.
My jokes table looks like this:
CREATE TABLE IF NOT EXISTS `jokes` (
`joke_id` int(11) NOT NULL AUTO_INCREMENT,
`joke` varchar(1024) NOT NULL,
`category_id` int(11) NOT NULL,
`vote` int(255) NOT NULL,
`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`joke_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
and my comments table looks like this:
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`comment` text NOT NULL,
`joke_id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
and for the moment, I am grabbing the data by assigned the $post_id = "1", but i want to change it to something like $post_id = $joke_id (with the joke id being in the same function, but i have no idea how to do it).
I'm using a MVC with codeigniter if thats any help.
Inside my controller, i have a php file called comments which has a function called insertComment, which looks like this:
public function insertComment(){
//extracts the data from the ajax
extract($_POST);
if($_POST['act'] == 'add-com'){
//assigned the db rows with the actual data which was inputted
$data = array(
'name' => htmlentities($name),
'comment' => htmlentities($comment),
//id_post should correlate to the joke_id
'id_post' => $id_post = "1"
);
$this->comments_m->insertComment($data);
}
and my insertComment function, inside the models of comment_m function looks like this:
function insertComment (){
extract($_POST);
if($_POST['act'] == 'add-com'){
$data = array(
'name' => htmlentities($name),
'comment' => htmlentities($comment),
'id_post' => $id_post = "1"
);
if(strlen($data['name']) <= '1'){
$data['name'] = 'Guest';
}
$this->db->insert('comments', $data);
}
}
To finalise, it would be a great help if someone could help with an SQL statement which joins the two tables together, which the joke_id having the same value as the comment's post_id which will make it unique to that joke.
Thank you
The SQL to join these two tables is -
SELECT `jokes`.*, `comments`.*
FROM `jokes`
LEFT OUTER JOIN `comments`
ON `jokes`.`joke_id` = `comments`.`joke_id`
This will return all of the comments for each joke. You can then filter or limit by adding the WHERE clause(s) -
WHERE `jokes`.`joke_id` = 1

How can configure two tables for admin module?

I have a custom module. I am using this module to upload images through admin. I have 6 more form fields in my module. I am currently using one table to store values of these form fields. However as like in magento, i am planning to store image values in another table. My table structure is given below.
Table : Banner
Fields : banner_id( primary_key , int(11) )
banner_name( varchar (250) )
banner_count( small_int (6) )
status( small_int (6) )
store_id( varchar (250) )
Table : banner_images
Fields : bi_id( primary_key , int (11) )
banner_id( int (11) ) //this should be the 'banner_id' of banner which holds this imge
bi_name( varchar (255) ) //stores image_name
My current edit file look like this:
<?php
class Karaokeshop_Banner_Block_Adminhtml_Banner_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
public function __construct()
{
parent::__construct();
$this->_objectId = 'id';
$this->_blockGroup = 'banner';
$this->_controller = 'adminhtml_banner';
$this->_updateButton('save', 'label', Mage::helper('banner')->__('Save Banner'));
$this->_updateButton('delete', 'label', Mage::helper('banner')->__('Delete Banner'));
}
public function getHeaderText()
{
if( Mage::registry('banner_data') && Mage::registry('banner_data')->getId() )
{
return Mage::helper('banner')->__("Edit Banner");
}
else
{
return Mage::helper('banner')->__('Add Banner');
}
}
}
My sql file look like this :
?php
$installer = $this;
$installer->startSetup();
$installer->run("
DROP TABLE IF EXISTS {$this->getTable('banner')};
CREATE TABLE {$this->getTable('banner')} (
`banner_id` int(11) unsigned NOT NULL auto_increment,
`banner_name` varchar(255) NOT NULL default '',
`banner_count` smallint(6) NOT NULL default '0',
`status` smallint(6) NOT NULL default '0',
`store_id` varchar(255) NOT NULL default '',
`img` varchar(255) NOT NULL default '',
PRIMARY KEY (`banner_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
");
$installer->endSetup();
How can I achieve this? Please provide links, if there is any tutorials for this. Thanks in advance

Trying to post info to database via wordpress but just showing up as '0'

I have a wordpress theme and i'm trying to add an additional field into the themes backend (it's for a gallery slider that has a description and caption text box, I'm trying to add a "quote" box).
As I'm a novice with databases, I've found the relevant files and copied all references to "description" and changed the word to "quote". I also added a "Quote" column into my table.
Everything appears to work fine, however when I type in text to the input field in the backend and click save, it changes the text to "0"
Does anyone know why this might be, what have I done wrong?
I think this is the code that posts to the DB....like I say though I'm a noob with DB's
add_action('wp_ajax_list_slider_items', 'list_slider_items');
function list_slider_items()
{
global $wpdb;
$result = $wpdb->get_results("SELECT IMAGEID, TYPE, CONTENT, THUMB, CAPTION, DESCRIPTION, QUOTE, WIDTH, HEIGHT FROM {$wpdb->prefix}backgrounds WHERE GALLERYID='".$_POST['GALLERYID']."' ORDER BY SLIDERORDER");
$i=0;
foreach($result as $row)
{
echo getSliderItemImage($row->IMAGEID, $row->TYPE, $row->CONTENT, stripslashes($row->CAPTION), stripslashes($row->DESCRIPTION), stripslashes($row->QUOTE), $row->THUMB, $row->WIDTH, $row->HEIGHT);
$i++;
}
die();
}
add_action('wp_ajax_save_slider_items', 'save_slider_items');
function save_slider_items()
{
global $wpdb;
for($i=0; $i<count($_POST['imageID']); $i++)
{
$wpdb->update($wpdb->prefix.'backgrounds', array('CAPTION'=>$_POST['CAPTION'][$i], 'DESCRIPTION'=>$_POST['DESCRIPTION'][$i], 'QUOTE'=>$_POST['QUOTE'][$i], 'SLIDERORDER'=>($i+1)), array('IMAGEID'=>$_POST['imageID'][$i]), array('%s', '%s', '%d'), array('%d'));
}
die();
}
And this looks liek the code that created the table:
function create_backgrounds_table(){
global $wpdb;
$prf = $wpdb->prefix;
$create_query = <<<EOT
CREATE TABLE `{$prf}backgrounds` (
`IMAGEID` int(11) NOT NULL auto_increment,
`GALLERYID` bigint(20) unsigned NOT NULL,
`SLIDERORDER` int(11) unsigned NOT NULL,
`EXT` varchar(255) NOT NULL,
`CAPTION` text,
`DESCRIPTION` mediumtext NOT NULL,
`QUOTE` mediumtext NOT NULL,
`TYPE` varchar(20) default NULL,
`CONTENT` text,
`THUMB` text,
`WIDTH` int(11) default NULL,
`HEIGHT` int(11) NOT NULL,
PRIMARY KEY (`IMAGEID`),
KEY `GALLERYID` (`GALLERYID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
EOT;
$create = $wpdb->get_results($create_query);
}

Categories