Passing Results from SQL to Google Maps API in CodeIgniter - php

I'm hoping to use Google Maps on my site.
My addresses are stored in a DB. I’m pulling up a page where the information is all dynamic. For example: mysite.com/site/business/5 (where 5 is the id of the business).
Let’s say I do a query like this:
function addressForMap($id) {
$this->db->select('b.id, b.busaddress, b.buscity, b.buszip');
$this->db->from('business as b');
$this->db->where('b.id', $id);
$this->db->limit(1);
// add a limit
$this->db->limit(1);
// get the results.. cha-ching
$q = $this->db->get();
// any results?
if($q->num_rows() !== 1)
{
return FALSE;
}
return $q->row();
}
How can I output the info to the Google Maps API correctly so that it displays the map appropriately?
The API interface takes the results like this: $marker['address'] = 'Crescent Park, Palo Alto';.
Here's what I have in the controller:
$marker = array();
$address = $this->Business_model->addressForMap($id); //Get result row
$marker['address'] = $address->busaddress .' '.$address->buscity .', '. $address->buszip;

The MODEL
function addressForMap($id)
{
$this->db->select('b.id, b.busaddress, b.buscity, b.buszip');
$this->db->from('business as b');
$this->db->where('b.id', $id);
// add a limit
$this->db->limit(1);
// get the results.. cha-ching
$q = $this->db->get();
// any results?
if($q->num_rows() !== 1)
{
return FALSE;
}
return $q->row();
}
The CONTROLLER
function your_controller_method($id)
{
$data = $this->Business_model->addressForMap($id);
// did we get any results?
if($data === FALSE)
{
show_error();
return;
}
$marker['address'] = $data->busaddress.' '.$data->buscity.', '.$data->buszip;
}
Make sure you validate that $id is an actual numerical id. It's a good thing to do before actually performing the query.. IMO.
EDIT #2: See changed code above
EDIT #1: From your comment and changes
You've got this:
return $this->db->get();
when, based on the rest of your code, it should be this:
$query = $this->db->get();
When you return the query object, the variable $address gets assigned the CI result object. so, in your controller, you would actually have to do something like this:
$address = $this->Business_model->addressForMap($id);
$row = $address->row();
$marker['address'] = $row->busaddress .' '.$row->buscity .', '. $row->buszip;
Still... I would suggest changing return to $query = and you could keep your controller as it is.

Here's the Final correct code:
For the Controller:
$address = $this->Business_model->addressForMap($id); //Get result row
$config['apikey'] = 'google-api-key';
$config['center_address'] = $address->busaddress .', '. $address->buscity;
$this->googlemaps->initialize($config);
$marker = array();
// $marker['address'] = $address->busaddress .' '.$address->buscity .', '. $address->buszip;
$marker['address'] = $address->busaddress .', '. $address->buscity;
$this->googlemaps->add_marker($marker);
$data['map'] = $this->googlemaps->create_map();
$data['address'] = $address->busaddress .', '.$address->buscity;
For the Model:
function addressForMap($id) {
$this->db->select('b.id, b.busaddress, b.buscity, b.buszip');
$this->db->from('business as b');
$this->db->where('b.id', $id);
$this->db->limit(1);
// add a limit
$this->db->limit(1);
// get the results.. cha-ching
$q = $this->db->get();
// any results?
if($q->num_rows() !== 1)
{
return FALSE;
}
return $q->row();
}

Thanks for using my library. It looks I posted the solution on my blog at near enough exactly the same time as you did on here :-P
Glad to hear you got it sorted though!

Related

Codeigniter Select and Count MySQL Records

Using Codeigniter 3, I would like to display all the records from a table in a MySQL database. I'd also like to include the number of records selected.
For example;
Showing x number of records;
record 1
record 2
record 3
etc
Currently I have the following (which works);
// select all records
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
// count all records
public function countRecords() {
$this->db->select('count(*) as count');
$this->db->from('records');
$query = $this->db->get();
return $query->row();
}
My question is do I need two separate queries in order to achieve this (select and count)?
Is there a more efficient way of achieving what I want?
You can do something like this :
public function selectRecords()
{
$query = $this->db->get('records');
if ($query->num_rows() > 0 )
{
$records = $query->result_array();
$data['count'] = count($records);
$data['all_records'] = $records;
return $data;
}
}
Pass it to the view from your controller :
$data = $this->model_name->selectRecords();
/*print_r($data) to see the output*/
$this->load->view('your_view',$data);
In view :
<?php echo $count .' number of records';?>
you can do only:
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
and
$records = $this->selectRecords();
$count = count($records);
In The first function itself you can get the count using $query->num_rows() function
public function selectRecords() {
$return = array();
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
$return['count'] = $query->num_rows();
$return['records'] = $query->result_array();
return $return;
}
try this
it will help you to provide pagination for records
public function selectRecords($params = array(), $count = false) {
$offset = isset($params['offset']) ? $params['offset'] : '';
$limit = isset($params['limit']) ? $params['limit'] : '';
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
if ($count) {
return $this->db->get()->num_rows();
}
if (empty($offset) && !empty($limit)) {
$this->db->limit($limit);
}
if (!empty($offset) && !empty($limit)) {
$this->db->limit($limit, $offset);
}
$result = $this->db->get()->result();
return $result;
}

Json returns a duplicate value using codeigniter

I am trying to fetch a data for each chkey with a related value as a group in codeigniter. When there are a 2 or more chkey then code is work properly.
But when there is a only 1 chkey then it shows value of that chkey but it is shows extra chkey:null,value:null in json.
Related json for chkey is 1 is as follows'
[{"unit_id":"8","CHGRAPHUpdatetime":{"time":"2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00"},"channelGraph":[{"chkey":"ch1","list":"2,-30,12,20"},{"chkey":"null","list":"null"}]}]
Expected is,
[{"unit_id":"8","CHGRAPHUpdatetime":{"time":"2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00"},"channelGraph":[{"chkey":"ch1","list":"2,-30,12,20"}]}]
Could you please help me to resolve this issue.
model code-
public function chGraph($unitid){
$this->db->select("unit_id");
$this->db->from("device_unit");
$this->db->where('unit_id', $unitid);
$query = $this->db->get();
$unit = $query->result_array();
$j = 0;
foreach($unit as $row) {
$unit[$j]['CHGRAPHUpdatetime'] = $this->UnitCHGRAPHUpdatetime($row['unit_id']);
$unit[$j++]['channelGraph'] = $this->UnitCHGRAPHDetails1($row['unit_id']);
}
return $unit;
}
public function UnitCHGRAPHDetails1($unit_id)
{
$this->db->select('distinct(chkey)','chvalue');
$this->db->from('channel_info');
$query = $this->db->get();
$channelgraphData = $query->result_array();
$m = 0;
foreach($channelgraphData as $row) {
$chvalueQuery = 'SELECT chkey, GROUP_CONCAT(chvalue)as list FROM channel_info where chkey= "'. $row['chkey'] .'" and unit_id='. $unit_id .'';
$response = $this->db->query($chvalueQuery)->row();
$channelgraphData[$m++] = $response;
}
return $channelgraphData;
}
controller code-
public function chGraph()
{
$unitid = $this->uri->segment('3');
$GraphDetails = $this->device_model->chGraph($unitid);
echo json_encode($GraphDetails);
}
You could add a GROUP BY at the end of the statement to eliminate the null results :
$chvalueQuery = 'SELECT chkey, GROUP_CONCAT(chvalue)as list FROM channel_info where chkey= "'. $row['chkey'] .'" and unit_id='. $unit_id .' GROUP BY chkey';

save uri segment in session to send it back to the model. Codeigniter

I just don't want to have such a duplicate function in a model, however I need to use that function again with a little change in it.
The little change is:
In the $first->get->model, I need to pass a segment url such as 'where id = $this->uri->segment(3)',
However, in the $second->get->model, I don't have that segment url anymore but have already save it to a session.
For example: (Please have a look to this code)
function get_regidsterLogin($limit, $offset) //There is no problem with $limit and $offset
{
$this->load->database();
$this->db->select(' ds.userid,
ds.register_time,
gl.logintime
');
$this->db->from('data_stats ds');
$this->db->join('game_login gl', 'gl.data_id = ds.dataid', 'inner');
//Here is what I want to change with session that I will send from view or maybe controller
$this->db->where('DATE(register_time)', $this->uri->segment(3));
$this->db->limit($limit, $offset);
$query = $this->db->get();
if($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
Is there a simple smart way to do this?
Thanks in advance.
You could either add a third argument and specify it every time or you could just test the segment in your function and if it is not there then use the session data:
if($this->uri->segment(3) === TRUE{
$uri = $this->uri->segment(3);
} else {
$uri = $this->session->userdata('user_id') // or whatever your session variable is
}
So a full example would look something like:
(I shortened up the above statement to a ternary expression for the example)
function get_regidsterLogin($limit, $offset) //There is no problem with $limit and $offset
{
$uri = ($this->uri-sement(3) == true ? $this->uri-sement(3) : $this->session->userdata(id));
$this->load->database();
$this->db->select(' ds.userid,
ds.register_time,
gl.logintime
');
$this->db->from('data_stats ds');
$this->db->join('game_login gl', 'gl.data_id = ds.dataid', 'inner');
//Here is what I want to change with session that I will send from view or maybe controller
$this->db->where('DATE(register_time)', $uri);
$this->db->limit($limit, $offset);
$query = $this->db->get();
if($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data[] = $row;
}
return $data;
}
}

Making simple allowed array in PHP? (CodeIgniter)

I have some simple function to collect allowed array, but something is not ok, can somebody help me? Here is my code
public function getAllbyLink($table, $what, $url)
{
$link=mysql_real_escape_string($url);
$query = $this->db->query("SELECT * FROM ".$table." WHERE ".$what." = '{$link}' LIMIT 0 , 1");
if ($query->num_rows() > 0)
{
return $query->result();
}
else redirect('');
}
Please read something about MVC pattern, question is clearly pointed on how to write a Model.
consider using this function
public function getTable($table, $where = array(), $select = '*', $order_by = '', $limit = '', $offset = '') {
if ($order_by !== '' && $order_by != 'RANDOM') $this->db->order_by($order_by);
if ($order_by == 'RANDOM') $this->db->order_by('id', 'RANDOM');
if ($limit !== '') $this->db->limit($limit, $offset);
$this->db->select($select);
$q = $this->db->get_where($table, $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
for your purpose call the function like this:
getTable($talbe, array('what' => $link));
//returns FALSE if no data are selected,
//or returns object with data,
if you wish return array instead replace $q->result() with $q->array_result()
Please note that active record auto escapes.
After comments:
comment-1, you can simplify that function easily just delete what you do not need, for example
public function getTable2($table, $where = array(), $limit = '', $offset = '') {
if ($limit !== '') $this->db->limit($limit, $offset);
$q = $this->db->get_where($table, $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
comment-2,when there is no data use this if-else statement
if (!$my_data = getTable2('table', array('where' => $link))) {
//there is some DATA to work with
echo "<pre>";
var_dump($my_data);
echo "</pre>";
} else {
//no DATA do redirect or tell user that there is no DATA
redirect(); //redirect to default_controller
}
comment-3, no comment;
comment-4, It also allows for safer queries, since the values are escaped automatically by the system. from this source. And another SO question about active record providing exact answer you are seeking.
My understanding of your code is:
Read all rows from table
Check if linkurl is in the list
If so, return a random row for that value
Else, redirect.
In this case, try this:
public function getAllbyLink($table,$url,$what)
{
$query = $this->db->query("
SELECT *
FROM `".$table."`
WHERE `".$what."` = '".mysql_real_escape_string($linkurl)."'
ORDER BY RAND()
LIMIT 1
");
if( !$query) return redirect('');
$result = $query->result();
if( !$result) return redirect('');
return $result;
}

This query show me with this active record

I am having trouble getting two tables and passing them to controller:
IN A MODEL:
function get_all_entries() {
$query = $this->db->get('entry');
return $query->result();
$this->db->select('entry_id , count(comment_id) as total_comment');
$this->db->group_by('entry_id');
$comment = $this->db->get('comment');
return $comment->result();
}
IN A CONTROLLER:
$data['query'] = $this->blog_model->get_all_entries();
$this->load->view('blog/index',$data);
How do I return $query and $comment variables to controller? I think I am doing it wrong.
Use this because you are not allowed to return twice in the same method
function get_all_entries()
{
$query = $this->db->get('entry');
$data[] = $query->result();
$this->db->select('entry_id , count(comment_id) as total_comment');
$this->db->group_by('entry_id');
$comment = $this->db->get('comment');
$data[] = $comment->result();
return $data;
}
EDITS:
In controller
function index(){
$this->load->model('mymodel');
$result = $this->mymodel->get_all_entries();
$entries = $result[0] ;
$comments = $result[1] ;
$data['entries'] = $entries;
$data['comments '] = $comments;
}
Your issue is that you're returning $query->result() in first place, return function halts the current function, so the next steps are not being processed.
Best way would be to create two methods for either $query get and $comment get.
An alternative to your issue would be
function get_all_entries() {
$query = $this->db->get('entry');
$this->db->select('entry_id , count(comment_id) as total_comment');
$this->db->group_by('entry_id');
$comment = $this->db->get('comment');
return array($query->result(),$comment->result());
}
Then in your controller
list($data['query'],$data['comment']) = $this->blog_model->get_all_entries();
$this->load->view('blog/index',$data);

Categories