In yii how to json_encoded multiple records - json

i am creating project in yii+extjs. I am having poll table with pollid and pollQuestion. Option table is having pollid and options. Now during publishing question i am retrieving question from poll table and options of that question from option table. and sending this data in json_encoded format. i had desgined function as-
public function actionCreate()
{
$model=new poll();
$model->pollId=4;
$record1=poll::model()->findByPk($model->pollId);
//$data = $record1->getAttributes();
$data= $record1->getAttributes(array('pollId','pollQuestion'));
foreach ($record1->polloptions as $option)
{
$data = array_merge($data, $option->with('pollId')- >getAttributes());
}
//echo $data;
echo CJSON::encode($data);
}
Option table is having multiple options for same question. But by above method it is displaying only last option inserted in option table instead of displaying all options of same question. So how to display all options of same question.Please help me....

May be you could try:
public function actionCreate()
{
$model=new poll();
$model->pollId=4;
$record1=poll::model()->findByPk($model->pollId);
//$data = $record1->getAttributes();
$data= $record1->getAttributes(array('pollId','pollQuestion'));
foreach ($record1->polloptions as $option)
{
$optionArray = $option->getAttributes()
//if the 2 arrays havn't the same indexes
//this way u keep the key indexes
$data = $data + $optionArray;
//if the 2 arrays could have the same indexes
$data = array_push($data, $optionArray);
}
//echo $data;
echo CJSON::encode($data);
}

Related

Is it possible to combine whereHas with 'or' queries?

I'm trying to implement a filter system where, among other attributes and relationships, items are categorized. However, the challenge appears when combining OR queries with other filters using the regular and clause. The result grabs rows which I do not want and adds the or when the condition for that fails, thus polluting the final results with unwanted data.
<?php
class ProductSearch {
public $builder;
private $smartBuild; // this is the property I'm using to disable the alternation when other search parameters are present to avoid polluting their result
function __construct( Builder $builder) {
$this->builder = $builder;
}
public function applyFilterToQuery(array $filters) {
$pollutants = ['subcategory', 'subcategory2', 'category'];
$this->smartBuild = empty(array_diff( array_keys($filters), $pollutants)); // [ui=>9, mm=>4], [mm]
foreach ($filters as $filterName => $value) {
// dd($filters, $filterName );
if (method_exists($this, $filterName) && !empty($value) )
$this->$filterName( $value);
}
return $this;
}
public function location( $value) {
$this->builder = $this->builder
->whereHas('store2', function($store) use ($value) {
$store->where('state', $value);
});
}
public function subcategory( $value) {
$name = Subcategories::where('id', $value)->pluck('name');
$this->builder = $this->builder->where('subcat_id', $value);
if ($name->isNotEmpty() && $this->smartBuild) {
$names = preg_split('/\W\s+/', $name[0]);
if (!$names) $names = $name;
foreach ($names as $value)
$this->builder = $this->builder->orWhere('name', 'like', "%$value%");
}
}
}
You may observe from the above that making a request for categories searches products matching the category name. But on attempting to combine that alternate match with legitimate AND queries (in location for instance, the result tends to include matching locations OR matching names.
The desired result is ((matching name OR matching category) AND matching location). Is this possible?
I had similar situation like this few days ago about User and Posts.
Needed a list of posts which user has commented or participated in and which user owns.
So I did following on User model
//Get user created post or if user has participated in the post
$queryString->where(function ($query) use ($user_id) {
return $query->whereHas('participants', function ($q) use ($user_id) {
$q->where('user_id', $user_id);
})->orWhere('id', $user_id);
});
Hope this helps.

How to send values from variables and arrays from controller to the model

I want to change the script below.
where the script below is using the query "like" and "array" to find data.
I want to send these 2 variables to the model and send them back to the controller for processing.
My Controller:
if($lewati == 0){
$sql = "SELECT * FROM tb_fotografer WHERE spesifikasi_foto LIKE '%$kata[$i]%'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
// $jml_id_filter = count($id_filter);
// $id_filter[$jml_id_filter] = $row['id'];
$filter_ok++;
}
}
My Model:
function tampil_data_spesifik($kata,$i)
{
return $this->db->query('select tb_fotografer WHERE spesifikasi_foto LIKE '%$kata[$i]%'');
}
From codeigniter's official documentation, it's a better practice to do all db queries in your model and you don't need to manually type any database connection scripts.
Your controller handles incoming requests, often times from routes. For codeigniter version 3, your controller method should be
public function method(){
$lewati = 0;
$array_data = array(3, 5, 9, 4);
$another_thing = $array_data[1] //get first item
if($lewati === 0){
$result = $this->model_name->method_in_model($lewati, $another_thing); //your model will accept two params
}
echo json_encode($result);
}
Then you can update your model to something like this
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_name extends CI_Model {
public function method_in_model($lewati, $another_thing){
$this->db->where('column_name', $lewati);
$this->db->like('spesifikasi_foto LIKE', $another_thing);
$result = $this->db->get('YOUR_TABLE_NAME');
if(empty($result->row_array())){
return true;
}else{
return false;
}
}
}
Let me know if it solved your problem already
in your controller method
$this->load->model('name_of_the_model_class');
$data = $this->name_of_the_model->function_name($variable1,$variable2);
in your model class method
//do whatever your process and return the output
return $output;

Trying to delete only one row in table - Laravel

I am trying to update some users info. Here is my code :
public function update(Request $request, $id)
{
$user = Auth::user();
$user_id = Auth::user()->id;
$arrRequest = $request->all();
$contact = Contact::findOrFail($id)->where('user_id', $user_id);
$validator = Validator::make($arrRequest, Contact::$rules);
$content = null;
if ($validator->fails()) {
$status = 400;
$content = $validator->errors();
} else {
$contact->update($arrRequest)->save();
$status = 200;
}
return response($content, $status);
}
The main problem is that the request is applied to all rows in the table though I'm specifying the $id of the row for the request to be applied to. I'm struggling to see where is my mistake. The second problem (that just popped up) is that when I perform the request I'm now getting a message that says : Call to a member function save() on integer. But it was working just fine earlier (except it was updating all rows..) ! And Im retrieving an object ($contact) and not just an integer...
Thanks !
You are using findOrFail() method, which returns a Model or Collection.
After that you actually convert $contact into a Builder object by appending the where() method on the findOrFail() result. findOrFail() expects either an $id or array of $ids and will return a Model or Collection, not a Builder.
If you just want to make sure that the requested id is owned by the user, you can either check that after fetching the object, or use something other than findOrFail().
$contact = Contact::findOrFail($id);
if ($contact->user_id != $user->id) {
abort(403);
}
or
$contact = Contact::where('id', $id)
->where('user_id', $user->id)
->first();
if (! $contact) {
abort(404);
}
Although I would not recommend the last one, just the $id should be enough to fetch the item you want.
The second error is caused by calling save() after update(), update() will return a boolean.
I've finally managed to make it work.. some weirds things happening though.
Here is my solution :
public function update(Request $request, $id)
{
$user = Auth::user();
$user_id = Auth::user()->id;
$arrRequest = $request->all();
$contact = Contact::where('user_id', $user_id)->find($id);
$validator = Validator::make($arrRequest, Contact::$rules);
$content = null;
if ($validator->fails()) {
$status = 400;
$content = $validator->errors();
} else {
$contact->update($arrRequest);
$contact->save();
$status = 201;
}
return response($content, $status);
}
Thanks to Robert I can understand some parts of it. I guess if I make update() first then save() (not in a row), my save method is applying to the object and not the returned boolean? and thats why it works? still learning ahah !

show tables get only the last name of table

I'm trying to show the name of table in my database. I write this code :
function affiche_liste()
{
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
$tableList = $data[0];
}
return $tableList;
}
It give to me only the last table ?
For a simple query without parameters and the SQL hard coded you can use a generic function passing the connection and SQL to the function.
The following function () returns an array containing all rows in the result set.
function queryAll($db,$query){
$sth = $db->query($query);
$result = $sth->fetchAll(PDO::FETCH_NUM);
return $result;
}
For a simple query without parameters and the SQL hard coded you can use a generic function passing the connection and SQL to the function.
The following function () returns an array containing all rows in the result set.
function queryAll($db,$query){
$sth = $db->query($query);
$result = $sth->fetchAll(PDO::FETCH_NUM);
return $result;
}
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SHOW TABLES";
$tables = queryAll($db,$query);
print_r($tables);
Each time you are looping through the results, your are overwriting the variable tableList. Instead, you need to append to an array of results.
function affiche_liste()
{
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
$tableList = array();
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
array_push($tableList, $data[0]);
}
return $tableList;
}
try this
`
function affiche_liste()
{$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
$tableList[] = $data[0];
}
return $tableList;
}
`
i hope it'll work...
here your array is overwitting every time...that's the reason you were getting the last table name....so you need to append to the existing array...

Output query to csv, codeigniter

I currently have a report that give me the users ID number and their email address, But I would like to make this in a CSV file instead of tables and rows like I currently have.
Here is my controller
function View_Email_E()
{
$data = array();
if($query = $this->report_model->View_Email_English())
{
$data['records'] = $query;
}
$data['main_content'] = 'view_all_email_english';
$this->load->view('includes/template', $data);
}
Here is my model
function View_Email_English()
{
$query = $this->db->where(array('Dial_Up' => '0', 'Language' => 'English', 'Membership_Status' => 'Active'));
$query = $this->db->like('Email', '#');
$query = $this->db->get('Membership');
return $query->result();
}
For some reason my view is not being shown in code mode, but it is an auto generated table using these this snippet of code. Each row returns ID and Email from the database.
<?php if(isset($records)) : foreach($records as $row) : ?>
How can I make a CSV file with just ID and email fields?
Thanks
I think you can use the csv_from_result function in dbutil to do it. Try something like this:
$csvContent = $this->dbutil->csv_from_result($query);
if ( ! write_file('./path/to/file.csv', $csvContent)) {
echo 'Unable to write the file';
} else {
echo 'File written!';
}
http://codeigniter.com/user_guide/database/utilities.html#csv
Add
$this->db->select(array('ID','Email'));
To your View_Email_English function.