Yii2 SELECT * WHERE id = array()? - php

i has Query select use WHERE = array(1,2,...), i tried IN but only data of the end ID and previous ID's data does not appear. Help me, thank for all.
My code:
Controller:
public function actionGetServiceType($q = null, $id = null) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$queryTest = new Query;
$queryTest->select('service_type_id')
->from('link_service_group_all')
->where(['IN', 'service_group_id', $id]);
$query = new Query;
$query->select('id as id, title AS text')
->from('service_type')
->where(['like', 'title', $q])
->andWhere(['IN', 'id' , $queryTest]);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
}
return $out;
}

public function actionGetServiceType($q = null, $id = null) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$queryTest = new Query;
$queryTest->select('service_type_id')
->from('link_service_group_all')
->where(['IN', 'service_group_id', $id]);
$queryTest = array_values($queryTest->createCommand()->queryColumn());
$query = new Query;
$query->select('id as id, title AS text')
->from('service_type')
->where(['like', 'title', $q])
->andWhere(['IN', 'id' , $queryTest]);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
}
return $out;
}
you were missing a line like this
$queryTest = array_values($queryTest->createCommand()->queryColumn());

Related

Update query laravel return false result and nothing error show why?

i'm working with laravel project, and i have an issue that is update query result return false value if i update with the same data, how to solve this? do i have to validate first before run the query and send a notification that the data is the same?
well this is my codes
public function update(Request $request)
{
$kamar_id = $request->input('kamar_id');
$title = $request->input('title');
$content = $request->input('content');
$keyword = $request->input('keyword');
$description = $request->input('description');
$prolog = $request->input('prolog');
$path = $request->input('path');
$sort = $request->input('sort');
$status = $request->input('status');
$type = $request->input('type');
$user_id = $request->input('user_id');
if (empty($request->input('path'))) {
$path = serialize(array('data/def.png'));
}else{
$path = serialize(explode(',', $request->input('path')));
}
$data = array('title' => $title,
'content' => $content,
'keyword' => $keyword,
'description' => $description,
'prolog' => $prolog,
'path' => $path,
'sort' => $sort,
'status' => $status,
'type' => $type,
'user_id' => $user_id);
// echo($kamar_id);
$update = Kamar::where('kamar_id',$kamar_id)->update($data);
if ($update) {
$response['status'] = 1;
}else{
$response['status'] = 0;
}
return response()->json($response);
}
thanks for helping me
Laravel Eloquent Update method returns true if anything updated in database from your query and return false if nothing is updated in database from your query.
refer:
https://laravel.com/docs/5.8/eloquent#updates
!nullTry
$update = Kamar::where('kamar_id','=',$kamar_id)->first();
if (!null($update))
{
$update->title = $title;
$update->content = $content;
$update->keyword = $keyword;
$update->description = $description;
$update->prolog = $prolog;
$update->path = $path;
$update->sort = $sort;
$update->status = $status;
$update->type = $type;
$update->user_id = $user_id;
$update->save();
$response['status'] = 1;
}
else
{
$response['status'] = 0;
}
Try using this
$kamarObj = new Kamar();
$kamarData = $kamarObj->find($kamar_id);
$result = $kamarData->update($data);
You can force updated_at column to be updated (or you can create this column if you don't have). So the query will be always updated.

How to explode array values

I got the array values but I don't know how to explore the values in laravel. I am a new for laravel please help me.
view()->composer('admin.sidebar', function ($view) {
$usertypeid = \Auth::user()->role;
$moduleRs = DB::table('users')
->join('permissions','users.role', '=', 'permissions.role_id')
->select('users.role as usersrole','permissions.role_id as role_id','permissions.module_name as module_name')
->where('users.role', '=', $usertypeid)
->get();
$view->moduleData = $moduleRs;
$data=$moduleRs;
if ( count($data) > 0 )
{
$result = array();
foreach($data as $row){
if(!isset($result[$row->role_id])) {
$result[$row->role_id] = array(
'role_id' => $row->role_id,
'module_name' => array( $row->module_name),
);
}else{
$result[$row->role_id]['module_name'] = array_merge($result[$row->role_id]['module_name'], array($row->module_name) );
}
}
$result = array_values($result);
$view->moduleData = $result;
}
else
{
$view->moduleData=null;
}
});
}
Can explode value? I got the array values as correct manner.
replace:
$view->moduleData = $moduleRs;
with:
$view->with('moduleData', $moduleRs);
and put it at the end of your view composer so that your function will look like :
view()->composer('admin.sidebar', function ($view) {
$moduleRs = DB::table('users')
->join('permissions','users.role', '=', 'permissions.role_id')
->select('users.role as usersrole','permissions.role_id as role_id','permissions.module_name as module_name')
->where('users.role', '=', \Auth::user()->role)
->get();
$moduleData = null;
if ( count($moduleRs) > 0 ) {
$result = [];
foreach($moduleRs as $row){
if(!isset($result[$row->role_id])) {
$result[$row->role_id] = [
'role_id' => $row->role_id,
'module_name' => [$row->module_name],
];
}else{
$result[$row->role_id]['module_name'] = array_merge($result[$row->role_id]['module_name'], [$row->module_name] );
}
}
$result = array_values($result);
$moduleData = $result;
}
$view->with('moduleData', $moduleData);
});

Codeigniter transaction for all queries within a function

I have these following functions.
public function importExcelFile(){
$file = $_FILES['file']['tmp_name'];
$data = extract_excel_data($file);
$i = 0;
foreach($data['values'] as $dataValues) {
$categories = [];
$brands = [];
$models = [];
foreach($dataValues as $value){
if(array_filter($value)) {
/* If a row does not contain brand/category/model for the product then fetch the resp. info. from previous row */
if(empty(trim($value[0]))) {
$categories[] = $prev_cat;
} else {
$categories[] = strtoupper(trim($value[0]));
$prev_cat = strtoupper(trim($value[0]));
}
if(empty(trim($value[1]))) {
$brands[] = $prev_brand;
} else {
$brands[] = strtoupper(trim($value[1]));
$prev_brand = strtoupper(trim($value[1]));
}
if(empty(trim($value[2]))) {
$models[] = $prev_model;
} else {
$models[] = $value[2];
$prev_model = $value[2];
}
}
}
//insert device category
$this->insert_setups('category', $categories);
//insert brand
$this->insert_setups('brand', $brands);
// Check if branch already exists in the database
$check_branch = $this->global_model->getDetailByWhere('branch', array('name'=>$data['branch'][$i].' branch'))->result();
$branch_arr = [];
//insert branch
if(empty($check_branch)) {
$branch_arr = array(
'name' => $data['branch'][$i].' branch',
'location' => $data['branch'][$i],
'status' => 1,
'created_by' => $this->session->userdata('id'),
'created_on' => date('Y-m-d')
);
$this->global_model->insertData('branch', $branch_arr);
}
$branch_id = $this->global_model->getDetailByWhere('branch', array('name'=>$data['branch'][$i].' branch'))->row()->id;
$db_device_categories = [];
$db_brands = [];
// get categoris, brands
$db_device_categories = $this->arrangeArray('category', $where =array());
$db_brands = $this->arrangeArray('brand', $where =array());
//detail_print($db_brands);
// insert new models from database
foreach(array_unique($models) as $model_key=>$model){
$check_model = $this->global_model->getDetailByWhere('model', array('name'=>$model))->result();
$insert = [];
if(empty($check_model)){
$insert = array(
'name' => $model,
'item_type' => 1,
'category_id' => $db_device_categories[$categories[$model_key]],
'brand_id' => $db_brands[$brands[$model_key]],
'created_by' => $this->session->userdata("id"),
'created_on' => date('Y-m-d'),
);
$this->global_model->insertData('model', $insert);
}
}
$db_device_models = [];
// get models from database
$db_device_models = $this->arrangeArray('model', $where = array('item_type'=>1));
$categoriy_id = [];
$brand_id = [];
$model_id = [];
$opening_stock = [];
// arrange the exported array with respective id
foreach($dataValues as $values){
if(array_filter($values)) {
if(empty(trim($values[0]))) {
$category_id = $prev_cat;
} else {
$category_id = strtoupper(trim($values[0]));
$prev_cat = strtoupper(trim($values[0]));
}
if(empty(trim($values[1]))) {
$brand_id = $prev_brand;
} else {
$brand_id = strtoupper(trim($values[1]));
$prev_brand = strtoupper(trim($values[1]));
}
if(empty(trim($values[2]))) {
$model_id = $prev_model;
} else {
$model_id = $values[2];
$prev_model = $values[2];
}
$opening_stock[] = array(
'category_id' => $db_device_categories[$category_id],
'brand_id' => $db_brands[$brand_id],
'model_id' => $db_device_models[$model_id],
'imei' => (string)$values[3],
'cost_price' => isset($values[5]) ? $values[5] : 0,
'selling_price' => isset($values[6]) ? $values[6] : 0
);
}
}
$group_by_model = [];
// group the array by model_id
foreach(array_unique($models) as $model1){
$where = $db_device_models[$model1];
$group_by_model[] = array_filter($opening_stock, function($elements) use ($where){
return $elements["model_id"] == $where;
});
}
if(!$this->purchase_model->insertOpeningStock($group_by_model, $branch_id)){
$this->session->set_flashdata('error', 'Opening stock of devices insertion failed.');
redirect('purchase/uploadExcelFile');
}
$i++;
}
$this->session->set_flashdata('success', 'Opening stock of devices added successfully.');
redirect('purchase/uploadExcelFile');
}
private function arrangeArray($table, $where){
$list = $this->global_model->getDetailByWhere($table, $where)->result_array();
foreach($list as $item){
$name = $item['name'];
$arranged_list[$name] = $item['id'];
}
return !empty($arranged_list) ? $arranged_list : NULL;
}
private function insert_setups($table_name, $setups){
foreach(array_unique($setups) as $value){
$check_setup = $this->global_model->getDetailByWhere($table_name, array('name'=>$value))->result();
if(empty($check_setup)){
$insert = array(
'name' => $value,
'created_by' => $this->session->userdata("id"),
'created_on' => date('Y-m-d'),
);
$this->global_model->insertData($table_name, $insert);
}
}
}
What this function does is, it extracts data from the uploaded excel file and inserts the data to various tables accordingly. Now as you can see, there are multiple queries running in different locations inside the importExcelFile() method. So my question is, how do I use codeigniter transaction in such a way that all the queries inside this function are performed atomically. If any one query fails, all other query's work is rolled back. Also, is this code considered clean ?
P.S. I'm so sorry if my last question was inappropriate here.
this might be helpful to you.
transactions in codeigniter
$this->db->trans_begin();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}

database error with codeigniter

i want to make a edit form
this is my controller :
public function edit_data($id_kategori){
$artikel = $this->mymodel->GetArtikel("where id_kategori = '$id_kategori'");
$data = array(
"id_kategori" => $mhs[0]['id_kategori'],
"nama_lengkap" => $mhs[0]['nama_lengkap'],
"judul" => $mhs[0]['judul'],
"nama_kategori" => $mhs[0]['nama_kategori'],
"isi" => $mhs[0]['isi']
);
$this->load->view('form_edit',$data);
}
public function do_update(){
$id_kategori= $_POST['id_kategori'];
$nama = $_POST['nama_lengkap'];
$judul = $_POST['judul'];
$nama_kategori = $_POST['nama_kategori'];
$isi = $_POST['isi'];
$data_insert = array(
'id_kategori' => $id_kategori,
'nama_lengkap' => $nama,
'judul' => $judul,
'nama_kategori' => $nama_kategori,
'isi' => $isi);
$where = array('id_kategori' => $id_kategori);
$res = $this->mymodel->UpdateData('artikel',$data_update,$where);
if($res>=1){
$this->session->set_flashdata('pesan','Update Data Sukses');
redirect('crud/index');
}
}
and my model :
public function GetArtikel($id_kategori=''){
$data = $this->db->query('SELECT a.id_artikel, a.judul, a.tanggal_buat, a.tanggal_update, b.nama_kategori, c.nama_lengkap, c.id_user FROM artikel as a LEFT JOIN kategori as b on a.id_kategori=b.id_kategori LEFT JOIN user as c on a.id_user=c.id_user' .$id_kategori);
return $data->result_array();
}
public function UpdateData($tabelNama,$data,$where){
$res = $this->db->update($tabelNama,$data,$where);
return $res;
}
but when i run to the browser. error :
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'id_kategori = '1'' at line 1
how to resolve it?
Put a space before you concatenate the WHERE clause:
....on a.id_user=c.id_user' .$id_kategori);
to
....on a.id_user=c.id_user ' .$id_kategori);
In Controller
public function do_update(){
$res = $this->mymodel->UpdateData();
if($res == TRUE)
{
# Success
$this->session->set_flashdata('pesan','Update Data Sukses');
redirect('crud/index');
}
else
{
# Error
echo "Update Failed";
}
}
In Model
public function UpdateData(){
$id_kategori = $_POST['id_kategori'];
$nama = $_POST['nama_lengkap'];
$judul = $_POST['judul'];
$nama_kategori = $_POST['nama_kategori'];
$isi = $_POST['isi'];
$data = array(
'nama_lengkap' => $nama,
'judul' => $judul,
'nama_kategori' => $nama_kategori,
'isi' => $isi
);
$this->db->where('id_kategori', $id_kategori);
if(!$this->db->update('artikel', $data))
{
#Error
return FALSE;
}
else
{
#Success
return TRUE;
}
}

check function return value without execute it again

how to get function return value without execute it again?
i used this but this execute function again
my function:
function article()
{
if($_GET['action'] == "article" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$article = array();
$selectArticle = mysql_query("SELECT * FROM articles WHERE id='$id'");
$rowArticle = mysql_fetch_array($selectArticle);
$id = $rowArticle['id'];
$title = stripcslashes($rowArticle['title']);
$category = stripcslashes($rowArticle['category']);
$image = stripcslashes($rowArticle['image']);
$description = stripcslashes($rowArticle['description']);
$full_description = stripcslashes($rowArticle['full_description']);
$keywords = stripcslashes($rowArticle['keywords']);
$url = "/article/" . $rowArticle['id'] . "/" . str_replace(" ","-",stripcslashes($rowArticle['title']));
$article = array('id' => $id, 'title' => $title, 'category' => $category, 'image' => $image, 'description' => $description, 'full_description' => $full_description, 'keywords' => $keywords, 'url' => $url);
mysql_query("UPDATE articles SET visits=visits+1 WHERE id='$id'");
}
return $article;
}
how to check it
if (article() != null)
{
$article = article();
return $article['title'];
}
This should do what you want
if (null !== ($article = article())) {
return $article['title'];
}
This does a 'simultaneous' assignment AND comparison.
First, this part is evaluated: ($article = article()). It yields a null value or an array which is stored in $article.
Its result (null or array) is then evaluated by the if structure: if (null !== $article) and normal flow resumes.
like so
$article_var = article();
if ($article_var!=null)
{
//do stuff
//return $article['title'] // etc
}
Modify the check a little bit.
$article = article();
return $article != null ? $article['title'] : null;

Categories