Why can not I use '%' or '' in LIKE query builder to select all data?
I try in SQL shell can, but in query builder can not
My Model
public function ajax_getTargetMhs($where,$where2) {
$this->db3->SELECT("nim,nama,kodeunit")
->FROM("akademik_ms_mahasiswa")
->LIKE('kodeunit',$where)
->LIKE('periodemasuk',$where2);
$query = $this->db3->get();
if( $query->num_rows() > 0 ) {
return $query->result();
} else {
return array();
}
}
My Controller
public function getTargetMhs($where,$where2) {
$json =$this->Survey_Model->ajax_getTargetMhs($where,$where2);
$arr = array();
foreach ($json as $results) {
$arr['data'][] = array(
$results->nim,
$results->nama,
$results->kodeunit
);
}
//save data mysql data in json encode format
echo json_encode($arr);
}
I can't access like this
'ajax': "<?php echo base_url(); ?>survey/getTargetMhs/"+'SINF/'+'%',
The method like() accepts a third parameter that describes which "side" of the "matching" string to put wildcard characters on. Acceptable values are 'none', 'left', 'right', 'both'.
If you don't pass a "side" value then 'both' is used. Not sure which is the correct choice for you. If you want to construct the whole matching argument yourself then 'none' should work.
Documentation on like() HERE
Related
I have two list-filtering inputs, if used individually they work perfectly but when used together it returns an empty object.
the filters contain one simple search Input field, and one select.
they trigger an API call to the server which when used both looks like this
http://127.0.0.1:8000/api/user?&search=jom&type=admin
the method which this call trigger looks like this
public function index(Request $request) {
$search = $request->input('search');
$type = $request->input('type');
$user = User::select('*');
$this->checkSearch($user, $search); // check for search
$this->filterUserType($user, $type); // filter user type
...
the method checkSearch looks like this
private function checkSearch(&$query, $search) {
if (!isset($query)) {
return $query;
}
if (!is_null($search)) {
$searchTerms = $this->stringToArray($search, ' ');
$query = $query->where(function ($query) use ($searchTerms) {
for ($i = 0, $max = count($searchTerms); $i < $max; $i++) {
$term = str_replace('_', '\_', mb_strtolower('%' . $searchTerms[$i] . '%'));
$query->whereRaw("(Lower(name) LIKE ?)", [$term, $term])
->orWhereRaw("(Lower(bio) LIKE ?)", [$term, $term]);
}
});
}
}
and the filterUserType like this
private function filterUserType(&$query, $type) {
if (!isset($query)) { return $query; }
if (!is_null($type)) {
$query = $query->where( 'type', $type);
}
}
I've tried to check the where on the filterUserType method, to orWhere but this just returns values of both not combined.
I triggered a break on the raw query and it appeared like this
select * from `users` where ((Lower(name) LIKE %jom%) or (Lower(bio) LIKE %jom%)) and `type` = %jom%)
When I switched the methods I got the right results.
Switching from
$this->checkSearch($user, $search); // check for search
$this->filterUserType($user, $type); // filter user type
to
$this->filterUserType($user, $type); // filter user type
$this->checkSearch($user, $search); // check for search
Still don't know why but it worked
I am relatively new to codeigniter. While I was trying to perform a searching operation on my data base using AJAX, The code is returned as successful and the data is retrieved but, This data is JSON encoded and is in the javascript portion of my view so I am unable to use the json_decode function of codeigniter
public function lookup(){
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->MAutocomplete->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->firstname,
); //Add a row to array
}
}
echo json_encode($data); //echo json string
}
the data is accessed in the javascript as data.message.
Please tell me is there anyway i can use this data in the php part of my program
<?php
class MAutocomplete extends CI_Model{
function lookup($keyword){
$this->load->database();
$this->db->select('*');
$this->db->from('Students');
$this->db->like('firstName',$keyword,'after');
$query = $this->db->get();
// echo '<pre>'; print_r($query->result()); exit;
return $query->result();
}
}
I think you need to parse json response in Ajax's success function using JSON.parse().Like this..
$.ajax({
url:'',//your url
dataType:'JSON',
data:'',//your data
success:function(response){
data = JSON.parse(response);
alert(data.message.value);//alerts value
}
});
In controller use count rather than empty.To check the array
if( count($query) >0 )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->firstname,
); //Add a row to array
}
}
You should use to response:
return $this->output
->set_content_type('application/json')
->set_output(json_encode($data));
I am using yii1. I have following code which converts array into json:
public function actionIndex()
{
/* $this->layout='//layouts/datatable';*/
if(Yii::app()->request->isAjaxRequest) {
$model = Company::model()->findAll();
$data = array_map(function ($model) {
return $model->attributes;
}, $model);
$responce = json_encode($data);
var_dump($responce);
return $responce;
}
else {
return $this->render('list');
}
}
It returns json data string(1221) "[{"c_id":"1","c_name":"Marokand", ...
However, i need json data with the following format:
[{c_id: 1, c_name: "Marokand",
Please, help me.
Use echo instead of var_dump().
Instead of return, i used echo. It gave me expected result.
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.
I want to convert a model query to json with json_encode, it doesn't work. But with a ordinary array it does.
$arr = array("one", "two", "three");
$data["json"] = json_encode($arr);
Output
<?php echo "var arr=".$json.";"; ?>
var arr=["one","two","three"];
But when I try to convert a query codeigniter throws an error. What is it with that?
This is the error message:
A PHP Error was encountered Severity:
Warning Message: [json]
(php_json_encode) type is unsupported,
encoded as null
And the converted "query" result = I mean model method is like this:
{"conn_id":null,"result_id":null,"result_array":[],"result_object":[],"current_row":0,"num_rows":9,"row_data":null}
I try to do like this
$posts = $this->Posts_model->SelectAll();
$data["posts"] = json_encode($posts);
By the way, the model and method works just fine when I do it without json_encode.
Something I'm propably doing wrong, but the question is what?
You appear to be trying to encode the CodeIgniter database result object rather than the result array. The database result object acts as a wrapper around the cursor into the result set. You should fetch the result array from the result object and then encode that.
Your model code appears to be something like this :
function SelectAll()
{
$sql = 'SELECT * FROM posts';
// Return the result object
return $this->db->query($sql);
}
It should be more like this :
function SelectAll()
{
$sql = 'SELECT * FROM posts';
$query = $this->db->query($sql);
// Fetch the result array from the result object and return it
return $query->result();
}
This will return an array of objects which you can encode in JSON.
The reason you are getting an error trying to encode the result object is because it has a resource member variable that cannot be encoded in JSON. This resource variable is actually the cursor into the result set.
public function lastActivity()
{
header("Content-Type: application/json");
$this->db->select('*');
$this->db->from('table_name');
$query = $this->db->get();
return json_encode($query->result());
}
As per latest CI standard use the following code in your controller file:
$this->output->set_content_type('application/json')->set_output(json_encode($arr));
Models (Post):
function SelectAll()
{
$this->db->select('*');
$this->db->from('post');
$query = $this->db->get();
return $query;
}
Controllers :
$data['post'] = $this->post->SelectAll()->result_array();
echo json_encode($data);
Result:
{"post":[{"id":"5","name":"name_of_post"}]}
Here is the working solution:
$json_data = $this->home_model->home_getall();
$arr = array();
foreach ($json_data as $results) {
$arr[] = array(
'id' => $results->id,
'text' => $results->name
);
}
//save data mysql data in json encode format
$data['select2data'] = json_encode($arr);