How to get result based on 2 query in CI - php

sorry for the confusing title as I really did not know what to type. I'm new to CI and now I'm trying to convert my code to CI and stuck here.
here is my original code:
$query_domain = $konek->prepare("SELECT * FROM `domain` WHERE `id` = :id");
$query_domain->bindParam(":id", $id);
$query_domain->execute();
$data_domain = $query_domain->fetch();
$query_owner = $konek->query("SELECT * FROM `people` WHERE `id` = $data_domain->ownerid");
$data_owner = $query_owner->fetch();
So basically it request a domain where the domain id is X
and then it request data of the owner based on an owner id that is in domain table.
I'm not really sure what to put in controller or model
but here is my current model:
public function get_domain($id){
$this->db->get_where('domain', array('id' => $id));
}
public function get_domain_owner($ownerid){
$this->db->get_where('client', array('id' => $ownerid));
}

In your (Client) model:
public function get_owner_with_domain($domain)
{
$query = $this->db->select('c.*')->
from('client c')->
join('domain d', 'd.ownerid = c.id')->
where('d.name',$domain)->get();
if ($query) {
return $query->row_array();
// Or, ideally return a client if you have a Client model
// return $query->row(0,'Client');
} else {
// log error?
return false;
}
}
In your controller:
public function client($domain) // or whatever your function might be called
{
$this->load->model('Client');
$client = $this->Client->get_owner_with_domain($domain)
// Do something with the client
// var_dump($client);
$view_data['client'] = $client;
$this->load->view('client_info',$view_data);
}
Further reading:
CodeIgniter ActiveRecord reference
CodeIgniter Results reference

You can do simply by using a single query
SELECT people.* FROM people, domain WHERE people.id = domain.ownerId AND domain.id = :id

Related

Passing data between 2 models in 1 controller function laravel

I need to get the lecture id in my student table and from then only can i get the lecture's data using that id. The problem is, the $lectureID is null when i try to apply it on the lecture model, but when i check on the console, it does get the data. Thanks in advance.
Controller
public function getLecture($id)
{
$lectureID = student::select('lecture_id_FK')->where('student_id',$id)->first();
$lectureDATA = lecture::where('lecture_id',$lectureID)->first();
return $lectureDATA;
}
you can try two ways
public function getLecture($id)
{
## way 1
$lectureID = student::where('student_id',$id)->value('lecture_id_FK');
$lectureDATA = lecture::where('lecture_id',$lectureID)->first();
## way 2
$lectureID = student::where('student_id',$id)->first();
$lectureDATA = lecture::where('lecture_id',$lectureID->lecture_id_FK)->first();
return $lectureDATA;
}
before check what inside $lectureID:
public function getLecture($id)
{
$lectureID = student::select('lecture_id_FK')->where('student_id',$id)->first();
dd($lectureID);//I believe inside will be object with lecture_id_FK
//then just
$lectureDATA = lecture::where('lecture_id',$lectureID->lecture_id_FK)->first();
return $lectureDATA;
}
Recommended way to do it:
In Student model class ( recommend use capital S )
class student
{
public function lecture(){
return $this->hasOne('App\lecture','lecture_id_FK','lecture_id');
}
}
then just load studen with lecture like this
$student = studend::with('lecture')->find($id);
$lecture = $student->lecture;

laravel perform two query in one function

Simply i have a two table
GALLARIES AND MEDIA
In a GALLARIES table id,title,venueId i have saved gallary folder name for the particular venue.
In MEDIA Table I have id,imagepath,is_thumb(0 or 1),gallery_Id
What i want to do is when i set is_thumb_image(1) then i have call two function
1 st for unset image all with gallery_id and after i call second function for set is_thumb_image for particular image.
Is it possible to call one function only and perform both functionalty.
Here is my Controller code.
$albumId = $request->album_id; //table galleries id - album name
if($request->is_thumb_image == "true") {
$media1->UnsetThumbImage($albumId); // first unset thumb_image
$media->setThumbImage($media->id); // call for set thumb_image
} else {
$request->is_banner_image = false;
}
Here is my model functions
public function setThumbImage($mediaId) {
try {
DB::table('media')
->where('id', $mediaId)
->update(['is_thumb_image' => 1]);
$this->is_thumb_image = 1;
} catch (\Exception $ex) {
echo $ex->getMessage();
dd($ex->getTraceAsString());
}
}
public function UnsetThumbImage($albumid) {
DB::table('media')
->where('gallery_id', $albumid)
->update(['is_thumb_image' => 0]);
$this->is_thumb_image = 1;
}
How can i do it calling only one function.
You can use CASE with MySQL to update on various conditions. You'd need to use a raw query to do this with Laravel I believe.
Something like:
UPDATE media
SET is_thumb_image = CASE
WHEN id = $mediaId THEN 1
WHEN gallery_id = $albumId THEN 0
END
For that you need to:
specify which column is it gonna be. But best practice is to do this in different methods, as they have different jobs, and column action.
$this->setThumbImage('id', $id);
$this->setThumbImage('gallery_id', $id);
Pass what you need to according to your requirement.
public function setThumbImage($id, $field) {
DB::table('media')
->where("$field", $id)
->update(['is_thumb_image' => 0]);
$this->is_thumb_image = 1;
}

How to retrieve specific value from zendframework 2.0 database

Hello i have a question about the zend framework. I have a database with a column having values yes and no. I wish to be able to retrieve from that column only yes values.
This is my code but no success:
public function getListi(array $filterBy = array())
{
$id = 'yes';
$select = $this->sql->select();
$select->from(self::TABLE);
$select->columns(['security_maintenance']);
$select->where(array(
'security_maintenance' => $id
));
$statement = $this->sql->prepareStatementForSqlObject($select);
return $statement->execute();
}
view :
<div class="value-self"><?php
foreach ($domainii as $row) {
echo $row['security_maintenance'];
}
?></div>
controller:
public function indexAction()
{
return new ViewModel(array(
'domainii' => $this->getDomainModel()->getListi(),
));
}
The column is called security_maintenance. the above does not work but when i query by id it works but that does not help me as querying by id will not help me get yes values from the security_maintenance column.
Hello i got it working after doing some research into some zend documentation. This is my code:
public function getListii(array $filterBy = array())
{
$select = $this->sql->select();
$select->from(self::TABLE);
$select->columns(['security_maintenance']);
$select->where->like('security_maintenance', 'yes%');
$statement = $this->sql->prepareStatementForSqlObject($select);
return $statement->execute();
}
You need to specify the columns you want to select.
try adding the below code
$select->columns(['security_maintenance']);

Cannot get data from mysql query to controller

Hello I am using codeigniter framework for a project, I have a controller which is calling the data from a model function. Here is the controller.
public function getThirdPartyRR($token){
if ($this->input->is_ajax_request()){
// $data = json_decode(file_get_contents('php://input'), true);
// Following is loaded automatically in the constructor.
//$this->load->model('user_profile');
$userid = $this->myajax->getUserByAuth($token);
if ($userid){
$this->load->model("riskrating_page");
/* If we have an impersonated user in the session, let's use him/her. */
if (isset($_SESSION['userImpersonated'])) {
if ($_SESSION['userImpersonated'] > 0) {
$userid = $_SESSION['userImpersonated'];
}
}
// $resultList value could be null also.
$result = $this->riskrating_page->getThirdPartydata($userid);
/* Little bit of magic :). */
$thirdpartylist = json_decode(json_encode($result), true);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($thirdpartylist));
} else {
return $this->output->set_status_header('401', 'Could not identify the user!');
}
} else {
return $this->output->set_status_header('400', 'Request not understood as an Ajax request!');
}
}
And here is the query function in the model where I get the data from.
function getThirdPartydata($id){
$query = 'SELECT b.text_value as Company, a.third_party_rr_value
FROM user_thirdparty_rr a
inner join text_param_values b
on a.third_party_rr_type = b.text_code and
b.for_object = \'user_thirdparty_rr\'
WHERE a.Owner = '.$id. ' and
a.UPDATE_DT is null;';
}
But when I debug it using netbeans, its shows that in my controller in the $result function I get null meaning I couldnt grab any data from mysql.
Here is the search result from mysql.
You only write your query not fetch any data from your query result
function getThirdPartydata($id){
$query = "SELECT b.text_value as Company, a.third_party_rr_value
FROM user_thirdparty_rr a
inner join text_param_values b
on a.third_party_rr_type = b.text_code and
b.for_object = 'user_thirdparty_rr'
WHERE a.Owner = '$id' and
a.UPDATE_DT is null";
$this->db->query($query);// execute your query
return $query->result_array();// fetch data
}

mysql queries does not work in zend framework

class Application_Model_DbTable_Email extends Zend_Db_Table_Abstract
{
protected $_name = 'memberdetail';
function getUserid($email)
{
$subquery = $this->select()
->from('memberdetail', array('memberid'))
->where('email = ?', $email);
$select = $this->select()
->from('usertable', array('userid'))
->join('memberdetail', 'usertable.userid = memberdetail.memberid')
->where('usertable.userid = ?', $subquery);
$row = $select->query()->fetch();
if (!$row) {
echo "User id not found";
} else {
return $userid = $row['userid'];
}
}
}
Hi, I am trying to return the userid from the above queries. However, the queries does not seemed to be executed as I always get refreshed whenever I call this function.
P.S this set of queries were given to me by another member.
it looks like this is being over thought. According to the info provided usertable.userid = memberdetail.memberid with this being the case your function is simple.
/** this function assumes one and only one email will match a memberid
* this function can be improved by validating $email as existing in DB
* prior to querying DB, should be done at form level but could be accomplished here
* with Zend_Validate_Db_RecordExists()
*/
public function getUserIdFromEmail($email) {
$select = $this->select();
$select->where('email = ?',$email);
$row = $this->fetchRow($select);//fetch a single row
if (!is_null($row) {//fetchRow returns null if no row matched
return $row->memeberid;//return memberid as string/integer = usertable.userid
} else {
//handle error
}
}
It would have been useful to tell people you are using Zend framework.
You need to establish a connection to the database for $this as described in steps 1 and 2 in this link:
http://framework.zend.com/manual/en/zend.db.select.html/
You can try this, if it helps:
function getUserid($email){
$select = $this->select()
->setIntegrityCheck(false)
->from(array('m' => 'memberdetail'), array('b.userid'))
->join(array('b' => 'usertable'), 'b.userid = m.memberid')
->where('m.email = ?', $email);
$row = $this->getAdapter()->fetchAll($select);
if (!$row) {
throw new Exception("User id not found");
} else {
return $row->toArray();
}
}

Categories