yii cdbdatareader and readObject function - yii

I am trying to construct an object from a stored procedure will yii.
http://www.yiiframework.com/doc/api/1.1/CDbDataReader
I am unsure how to use the function $dataReader->readObject('image', $image);
to construct an object- anyone any ideas if this is the correct way or if this is very slow way of constructing objects
function __construct($image) {
print "In BaseClass constructor\n";
}
public static function getImageFromAliasTitle($alias_title)
{
// $alias_title =Utils::checkEnteredData($alias_title);
$connection = Yii::app()->db;
$command = $connection->createCommand("CALL get_associated_image_detail(:in_image_alias_title, :in_image_visible, :in_image_approved, :in_album_visible, :in_album_approved)");
$command->bindParam(":in_image_alias_title",$alias_title,PDO::PARAM_STR);
$command->bindValue(":in_image_visible",'1',PDO::PARAM_STR);
$command->bindValue(":in_image_approved",'Yes',PDO::PARAM_STR);
$command->bindValue(":in_album_visible",'1',PDO::PARAM_STR);
$command->bindValue(":in_album_approved",'Yes',PDO::PARAM_STR);
try{
$dataReader = $command->query();
if($dataReader->count() >0)
{
$image = $dataReader->read();
}
$dataReader->readObject('image', $image);
// $image = $dataReader->read();
$dataReader->nextResult();
$album = $dataReader->readAll();
$dataReader->nextResult();
$tag = $dataReader->readAll();
$dataReader->nextResult();
$user_image = $dataReader->readAll();
$dataReader->close();
}
catch(Exception $e){
Yii::log('', CLogger::LEVEL_ERROR, 'Message Here...');
}
return $image;
}

What about this:
foreach($row as $dataReader->readAll()){
echo $row["image"];
}
if It does not help then try to print:
print_r($dataReader->readAll());

Related

Yii2 - calling method on afterAction

I am trying to perform afterAction event in the controller, but nothing is happening (the function is not called). This is code for afterAction:
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
$this->_logDownloadActivity();
return $result;
}
And function I am trying to call:
private function _logDownloadActivity()
{
$model = new ActivityLogsUserActivity();
$model->user_id = Yii::$app->user->identity->id;
$model->userActivityType_id = 3;
$model->buildVersion = 3333;
$model->ipAddress = $model->userIP();
$model->insert();
}

PDO return $row from a class method

Hey guys I am learning OOP in php. I come across some issue, when I try to customize PDO in my own class. Basically I have tried to return the row and fetch it outside my class. Unfortunately I would not work. I get this error "Call to a member function fetch() on a non-object". Have a look and give me some tips if You can. Many thanks.
$connection = new MySql(DBUSER, DBPASS);
$row = $connection->query("select * from users", "name");
while($row->fetch(PDO::FETCH_ASSOC)){
echo "<p>". $row["name"] ."</p>";
}
And here is how the MySql class look like:
class MySql{
private $dbc;
private $user;
private $pass;
function __construct($user="root", $pass=""){
$this->user = $user;
$this->pass = $pass;
try{
$this->dbc = new PDO("mysql:host=localhost; dbname=DBNAME;charset=utf8", $user, $pass);
}
catch(PDOException $e){
echo $e->getMessage();
echo "Problem z Połączeniem do MySql sprawdź haslo i uzytkownika";
}
}
public function query($query, $c1=""){
$mysqlquery = $this->dbc->prepare($query);
$mysqlquery->execute();
return $row = $mysqlquery->fetch(PDO::FETCH_ASSOC);
/* I WANT TO PERFORM COMENTED CODE OUTSIDE THE CLASS
while($row = $mysqlquery->fetch(PDO::FETCH_ASSOC)){
if($c1!=""){
echo "<p>". $row[$c1] ."</p>";
}
}
*/
}
If you want to return $mysqlquery to iterate over it, you have to return $mysqlquery, not just one row.
Here is a better version of your class, with dramatically improved error handling and security. But still awful configurability though.
class MySql{
private $dbc;
function __construct($user="root", $pass=""){
$dsn = "mysql:host=localhost; dbname=DBNAME;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$this->dbc = new PDO($dsn, $user, $pass, $opt);
}
public function query($query, $data = array()){
$stm = $this->dbc->prepare($query);
$stm->execute($data);
return $stm;
}
}
$connection = new MySql(DBUSER, DBPASS);
$stm = $connection->query("select * from users WHERE name = ?", array("name"));
while($row = $stm->fetch()){
echo "<p>". $row["name"] ."</p>";
}

Overhead of using Yii::app()->db multiple times?

if I have to do multiple queries in a row, is it better to do this:
$connection = Yii::app()->db;
once... and then keep using $connection, or is there an overhead if I have multiple functions like this:
function mainFunction() {
$dbResult1 = dbresult1();
$dbResult2 = dbresult2();
$dbResult2 = dbresult3();
}
function dbresult1() {
$connection = Yii::app()->db;
// do stuff
return $result;
}
function dbresult2() {
$connection = Yii::app()->db;
// do stuff
return $result;
}
function dbresult3() {
$connection = Yii::app()->db;
// do stuff
return $result;
}
Would it be better to do this:
function mainFunction() {
$connection = Yii::app()->db;
// do stuff with $connection for $dbResult1
// do stuff with $connection for $dbResult2
// do stuff with $connection for $dbResult3
}
?
You can trace the source code to see what happens when you call Yii::app()->db:
Yii::app() returns the static app property of YiiBase. You can see the source code here.
public static function app()
{
return self::$_app;
}
Yii::app()->db here it gets more interesting, because something gets looked up. You can see the source code here.
public function getDb()
{
return $this->getComponent('db');
}
getComponent() is a method of CModule you find the source code here.
public function getComponent($id,$createIfNull=true)
{
if(isset($this->_components[$id]))
return $this->_components[$id];
elseif(isset($this->_componentConfig[$id]) && $createIfNull)
{
$config=$this->_componentConfig[$id];
if(!isset($config['enabled']) || $config['enabled'])
{
Yii::trace("Loading \"$id\" application component",'system.CModule');
unset($config['enabled']);
$component=Yii::createComponent($config);
$component->init();
return $this->_components[$id]=$component;
}
}
}
As you see Yii::app()->db results in a few method calls and an array lookup. If performance is highly critical you might should cache the db instance. Else I would target on writing clean and readable code and won't care about such little tweaks.

Yii not able to save Image files CFileUploaded

I am not able to save the image uploaded from simple Form with this code
public function actionImage()
{
print_r($_FILES);
$dir = Yii::getPathOfAlias('application.uploads');
if(isset($_POST['img']))
{
$model = new FileUpload();
$model->attributes = $_POST['img'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->validate())
{
$model->image->saveAs($dir.'/'.$model->image->getName());
// redirect to success page
}
}
}
To Answer my own question instead of using above code I used this:
public function actionImage()
{
$dir = Yii::getPathOfAlias('application.uploads');
if (isset($_FILES['img']))
{
$image = CUploadedFile::getInstanceByName('img');
$image->saveAs($dir.'/'.$image->getName());
}
}
To Answer my own question instead of using above code I used this:
public function actionImage() {
$dir = Yii::getPathOfAlias('application.uploads');
if (isset($_FILES['img']))
{
$image = CUploadedFile::getInstanceByName('img');
$image->saveAs($dir.'/'.$image->getName());
} }

How do I pass SQL database query from the Model to the Controller and then the View on Code Igniter 2.0.3?

I was trying to pass SQL values from Model to Controller but the value couldn't be passed.
This the code in my model file:
class Has_alert extends CI_Model {
function __construct()
{
parent::__construct();
}
function __get_query() {
$sql = 'alerts_get_alerts';
$query = $this->db->query($sql);
$row = $query->first_row();
$header_data['hasAlert'] = $row->active;
}
}
And this is the code in my controller file:
class Chart extends CI_Controller {
// Default Constructor
public function __construct() {
parent::__construct();
$this->load->helper('html');
$this->load->model('Has_alert', '', TRUE);
$this->Has_alert->__get_query();
//$sql = 'alerts_get_alerts';
//$query = $this->db->query($sql);
//$row = $query->first_row();
//$header_data['hasAlert'] = $row->active;
}
public function index()
{
//Data Arrays
$this->load->helper('html');
$header_data['page_title'] = 'Title';
$header_data['tabid'] = "home";
//Load the headtop.php file and get values from data array
$this->load->view('includes/headertop.php', $header_data);
$this->load->view('homepage');
$this->load->view('includes/newfooter.php');
}
I got this error message on my view file:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: hasAlert
Filename: includes/headertop.php
Line Number: 184
Does anyone know what the problem is? Thank you.
Model
function __get_query() {
$sql = 'alerts_get_alerts';
$query = $this->db->query($sql);
$row = $query->first_row();
return $row->active;
}
Controller
public function index(){
$this->load->model("Has_alert");
//Data Arrays
$this->load->helper('html');
$header_data['page_title'] = 'Title';
$header_data['tabid'] = "home";
$header_data['hasAlert'] = $this->Has_alert->__get_query();
//Load the headtop.php file and get values from data array
$this->load->view('includes/headertop.php', $header_data);
$this->load->view('homepage');
$this->load->view('includes/newfooter.php');
}
I'm assuming that things like "alerts_get_alerts" is pseudocode.