Codeigniter: Display multiple columns from database as one - php

I wanted to display multiple column values from my database.
Using the query from model
$this->db->select('*');
$this->db->from('projectskillslist ps');
$this->db->join('empskillslist s', 's.skillsID = ps.skillsID', 'left');
$this->db->join('projects p', 'p.projectID = ps.projectID', 'left');
$this->db->where('ps.projectID = 1');
$query = $this->db->get();
$result = $query->result_array();
if ($query->num_rows() > 0) {
return $result;
}
return false;
And in my controller
$data['pSkills'] = $this->emp_model->view_projskills();
The query returns perfectly as expected:
Now in my view,
I wanted to call
Title: Project 1
SkillName: JAVA, PHP
So far, I have done this:
foreach ($pSkills as $data) {
echo $data['title'];
echo $data['skillName'];
}
And the result I am getting is
Title: Project 1
Skills: PHP
Title: Project 2
Skills: JAVA
It is a silly question indeed, I have already looked up and search for the same problem but I still no luck. I hope you can help me. Thank you so much!!

Try this, but first order the result set by Project ID and Skill ID.
$this->db->order_by('projectID, skillID');
view
$lastProjectID = 0;
$p_skills = '';
$p_title = '';
foreach ($pSkills as $data) {
if ($data['projectID'] !== $lastProjectID) {
// if there's a title, printIt()
if ($p_title !== '') {
printIt($p_title, $p_skills);
}
// set new title and skill list
$p_title = $data['title'];
$p_skills = $data['skillName'];
// remember last project
$lastProjectID = $data['projectID'];
} else {
// append skill name to skills
$p_skills .= ", " . $data['skillName'];
}
}
// end of foreach, if there's a title, printIt()
if ($p_title !== '') {
printIt($p_title, $p_skills);
}
function printIt($title, $skills) {
echo "Title: $title<br>";
echo "SkillName: $skills<br>";
}

Follow these step if it would can help..
Step 1: You have to concatenate projectID where GROUP_CONCAT will help.
Step 2. Perform your SQL query like below
SELECT projectID, skillName, GROUP_CONCAT(projectID) AS projid FROM
projectskillslist GROUP BY projid
Step 3: To display it in a view , you can use PHP's explode() and iterate over that, like this if it would help..
foreach ($pSkills as $row) {
echo $row->title;
echo explode(',', $row->skillName);
/*
or add below line of code if it doesn't works
*/
//echo str_replace(',', '<br />', $row->skillName);
}

Related

->result() not showing all data/rows

I have a question
Let say we have this 2 tables in our database
first table : category_lists
second table: data_category
so if list_data_id is equal to 1 meaning that it has 2 data if you look at data_category table which is 6 and 7
Now what I want is to query from category_list table so that 6 and 7 will echo Car Wreckers and Cash For Cars.
This is what my code looks like:
below is my controller:
public function index($listing_name)
{
$this->load->view('layouts/head_layout_seo');
$this->load->view('layouts/head_layout');
$data['main_view'] = 'listings/main_view';
$data['listing_data'] = $this->Listing_model->get_detail_listing($listing_name);
$list_id = $data['listing_data']->list_data_id; // this is what I get list_data_id is equal to 1
$data['category_ads'] = $this->Ads_model->get_ads($list_id); // this is what you need to look
$this->load->view('layouts/main', $data);
$this->load->view('layouts/footer_layout');
}
below is my model:
public function get_ads($list_id)
{
$this->db->where('list_data_id', $list_id);
$query = $this->db->get('data_category');
$query = $query->result();
//return $query;
if (count($query) > 0) {
for ($i=0; $i < count($query); $i++) {
foreach ($query as $value) {
$this->db->where('category_lists_id', $value->category_lists_id);
$querys = $this->db->get('category_lists');
//print_r($query);
return $querys->result();
}
}
}
}
below is my view:
foreach ($category_ads as $value) {
<p><?php echo $value->categories; ?></p> }
with the code above I get only 1 data which is Car Wreckers as you can see from the table, it supposes to show 2 data Car Wreckers and Cash For Cars
Can anyone help me with this?
Thank You
Try this, in your model so no need to call DB two times and no need to loop
public function get_ads($list_id)
{
$this->db->select('cl.category_lists_id,cl.categories');
$this->db->from('category_lists cl');
$this->db->join('data_category dc','cl.category_lists_id = dc.category_lists_id');
$this->db->where('dc.list_data_id',$list_id);
$query = $this->db->get();
if($query->num_rows() > 0){
return $query->result();
}else{
return array();
}
}

Getting Message: Invalid argument supplied for foreach() when there is no records in the table

I have two tables with records. In the first table, I am displaying personal information and in the second table, I am adding the activities details.
Now I am trying to display the record using joins. So below code, I am using in the model
public function getMemberActivity($gotMemberId){
$getDetails = array('members.member_id'=>$gotMemberId,'member_activity.activity_status'=>1,'members.is_Approved'=>1);
$result = $this->db->where($getDetails)
->from('members')
->join('member_activity', 'members.member_id = member_activity.member_id','LEFT')
->get()
->result();
//echo $this->db->last_query();
//print_r($result);
if($result)
{
return $result;
}
else
{
return 0;
}
}
Controller
Note: I am getting multiple member id here because I have above some more logic. that's the reason I am using for each.
$ActivityData=[];
foreach ($data['getAllMember'] as $key => $m_id) {
$ActivityData[] = $this->Access_model->getMemberActivity($m_id->member_id);
}
$data['MemberActivity'] = $ActivityData;
Now If I found the records related the member id in the secondary table then I am getting the output but if not found a record in the second table then I am getting the error Message: Invalid argument supplied for foreach()
If I remove 'member_activity.activity_status'=>1 from the where clause then my join query is working. I mean I am getting the member records.
->join('member_activity', 'members.member_id = member_activity.member_id','LEFT')
View
$SActivity=$MemberActivity;
//print_r($SActivity);
if($SActivity){
foreach ($SActivity as $sec_1) {
foreach ($sec_1 as $sec_activities) {
//list here
}
}
}
else{echo"no data availalbe";}
So my expected output is, I have to display the records if found in the second table if not found then also display the member table records.
Would you help me out in this?
Move your where condition 'member_activity.activity_status'=>1 in JOIN as below,
$public function getMemberActivity($gotMemberId){
$getDetails = array('members.member_id'=>$gotMemberId,'members.is_Approved'=>1);
$result = $this->db->where($getDetails)
->from('members')
->join('member_activity', 'members.member_id = member_activity.member_id AND member_activity.activity_status = 1','LEFT')
->get()
->result();
//echo $this->db->last_query();
//print_r($result);
if($result)
{
return $result;
}
else
{
return 0;
}
}
Hope this will be help you.
Final query like this:
SELECT members.*,member_activity.* FROM members LEFT JOIN member_activity ON members.member_id = member_activity.member_id AND member_activity.activity_status = 1
WHERE 'members.member_id' = $gotMemberId AND 'members.is_Approved' = 1;
The problem is with your model function getMemberActivity. If there is no record then you returns 0 and when you foreach you will get error because its not an array. So you can simply return $result since codeigniter return default array.
public function getMemberActivity($gotMemberId)
{
$getDetails = array('members.member_id' => $gotMemberId, 'members.is_Approved' => 1);
$result = $this->db->where($getDetails)
->from('members')
->join('member_activity', 'members.member_id = member_activity.member_id AND member_activity.activity_status = 1', 'LEFT')
->get()
->result();
return $result;
}
Second option is you can check !empty before your foreach.
I hope this will help you, try
foreach ($SActivity as $sec_1) {
if (!empty($sec_1)):
foreach ($sec_1 as $sec_activities) {
//list here
print_r($sec_activities);
}
endif;
}

ext js store/model example .net -converting php/mysql to .netwebservier/sql

Afternoon all,
I am working through a tutorial from MASTERING EXT JS and am stuck on retrieving data from db.
The book has been using examples using PHP and MYSQL... which I do not know. I use a .net web server and SQL, so I'm trying to convert this example from the tutorial, to how I would do it on my .net webserver.
the result in JSON format should be something like this
{
"data"[
{
"id":1",
"text" : "menu1",
"items": [
{"id": 2",
"text: "submenu2
},
{
"id":"3",
"text":"submenu3"
}
the php code they give me is this
php file 1
$permissions = retrievePermissions($userName); $modules =
retrieveModules($permissions); $result = retrieveMenuOptions($modules,
$permissions);
php file 2
function retrievePermissions($userName){
require('../db/db.php');
$sqlQuery = "SELECT p.menu_id menuId FROM User u ";
$sqlQuery .= "INNER JOIN permissions p ON u.groups_id = p.groups_id ";
$sqlQuery .= "INNER JOIN menu m ON p.menu_id = m.id ";
$sqlQuery .= "WHERE u.username = '$userName' ";
$permissions = [];
if ($resultDb = $mysqli->query($sqlQuery)) {
while($user = $resultDb->fetch_assoc()) {
$permissions[] = $user['menuId'];
}
}
$resultDb->free();
$mysqli->close();
return $permissions; }
function retrieveModules($permissions){
require('../db/db.php');
$inClause = '(' . join(',',$permissions) . ')';
$sqlQuery = "SELECT id, text, iconCls FROM menu WHERE menu_id IS NULL AND id in $inClause";
$modules = [];
if ($resultDb = $mysqli->query($sqlQuery)) {
while($module = $resultDb->fetch_assoc()) {
$modules[] = $module;
}
}
$resultDb->free();
$mysqli->close();
return $modules; }
function retrieveMenuOptions($modules, $permissions){
require('../db/db.php');
$inClause = '(' . join(',',$permissions) . ')';
$result = [];
foreach ($modules as $module) {
$sqlQuery = "SELECT * FROM menu WHERE menu_id = '";
$sqlQuery .= $module['id'] ."' AND id in $inClause";
// check if have a child node
if ($resultDb = $mysqli->query($sqlQuery)) {
// determine number of rows result set
$count = $resultDb->num_rows;
if ($count > 0){
$module['items'] = array();
while ($item = $resultDb->fetch_assoc()) {
$module['items'][] = $item;
}
}
$result[] = $module;
}
}
$resultDb->close();
$mysqli->close();
return $result;
I'm trying to figure out how to return the same json format using my .net webservice/SQL instead of php/MySQL.
It seems like it does 3 separate functions. And the result array is used as a parameter for the next query.
The basics seem easy... like for retreivePermissions... it is a simple SELECT WHERE statement.
retrieveModules seems to be an INNER JOIN with the first results.
But the last one... retrieveMenuOptions, it pulls in both results as parameters, and It returns results.
That is what I don't understand... how can I pull the results from SQL in the same JSON result format.
Am I making sense?
I have an example that uses a .NET Web API controller. Not exactly a web service, but you'll get the idea. Check it out here: http://jorgeramon.me/2015/ext-js-grid-search-with-net-and-mysql-backend/

push array data in every index of an array using codeigniter php

I have two tables sport_tbl, match_tbl. In sport_tbl, i defined sport_name such as cricket. In match_tbl, I have match_name,match_date,sport_id.
I want to show match_date of every sport_name (ex. i am showing match_date list for cricket sport and i want to show every date has match_name list).
I want to show one distinct match_date.
Image
my controller code:-
$url = 'cricket' // for example first sport_name
$data['getSportMatch'] = $this->user_model->getSportMatch($url);
my model code:-
public function getSportMatch($sport)
{
$query = $this->db->get_where('match_tbl',array('sport_name' => $sport));
if($query->num_rows > 0)
{
foreach($query->result() as $item){
$data[] = $item;
}
return $data;
}
}
my code in view:-
<div><?php foreach($getSport as $item): ?><h4><?= $item->sport_name; ?></h4><div><?= foreach($getSportMatch as $item): ?>
match_date)) ?>here i want to show list match_name of every match_date
My table structure images
1) sport_tbl
2) match_tbl
3) another match_tbl
you can solve this in model easily. if i did not understand wrong . you need 2 function in model.
1. will get sport names
2. will get matches of given sport name
//model functions
function get_sports(){
$data = array();
$sports = $this->db->select('sport_name')->from('sport_tbl')->get()->result();
if($sports)
{
foreach($sports as $sport){
$data[$sport->sport_name] = $this->get_matches($sport->sport_name);
}
return $data;
}
}
function get_matches($sport_name){
$matches = $this->db->select('*')->from('match_tbl')->where('sport_name',$sport_name)->get()->result();
return $matches;
}
so in view data will be something like this
$data => array(
'cricket'=> array(0 => array(
'match_id' => 11,
'sport_id' = 2 .....
)))
Try this coding ...
public function getSportMatch($sport)
{
$query = $this->db->query("SELECT * FROM sport_tbl as st INNER JOIN match_tbl as mt ON st.sport_id = mt.sport_id WHERE st.sport_name ='".$sport."'");
if($query->num_rows > 0)
{
$query_result = $query->result_array();
$final_result = array();
foreach($query_result as $result ) {
$date = $result['match_date'];
$final_result[$date][] = $result;
}
return $final_result;
}
}
View Coding :-
if(isset($final_result)) {
foreach($final_result as $result) {
echo $result['match_date']; // First display match date
if(isset($result['match_date'])) {
foreach($result['match_date'] as $match) {
echo $match['match_name']; // Second listout the match name
}
}
}
}

Passing Results from SQL to Google Maps API in CodeIgniter

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!

Categories