Okay ill be honest im a little bit lost here, Im creating a component for joomla 2.5 and have two tables in the database, "managers" and another called "Branches". Im trying to join managers with branches.
I wish i could be more precise with my problem but i honestly dont understand it, heres my model file that calls to the database:
<?php
defined( '_JEXEC' ) or die;
jimport('joomla.application.component.model');
class LocateModelBranches extends JModel
{
public function getItem()
{
$branch_id = JRequest::getInt('id');
$row = JTable::getInstance('branches', 'LocateTable');
$row->load($branch_id);
return $row;
}
public function getBranches()
{
$branch_id = JRequest::getInt('id');
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__branches');
$query->join('LEFT', '#__managers AS a USING(manager_id)');
$query->where("published = 1");
$db->setQuery($query);
$rows = $db->loadObjectList();
return $rows;
}
}
then my view.json.php file:
<?php
defined( '_JEXEC' ) or die;
jimport( 'joomla.application.component.view');
class LocateViewBranches extends JView
{
public function display($tpl = null)
{
$branch = $this->get('Branches');
$response = array();
foreach ($branch as $row) {
$response[] = array(
'lat' => $row->branch_latitude,
'lng' => $row->branch_longitude,
'data' => array(
'name' => $row->branch_name,
'address' => $row->branch_address,
'fax' => $row->branch_fax,
'email' => $row->branch_email,
'city' => $row->branch_city,
'telephone' => $row->branch_telephone,
'id' => $row->branch_id,
'lati' => $row->branch_latitude,
'lngi' => $row->branch_longitude,
'manager_id' => $row->manager_id,
),
);
}
echo json_encode($response);
}
}
then i get a response of:
[]
if i remove "$query->join('LEFT', '#__managers AS a USING(manager_id)');" my response then is (which is what i want along with the managers details :
[{"lat":"-33.9249","lng":"18.4241","data":{"name":"test 2","address":"greenpoint, Cape Town","fax":"044 382 0605","email":"test","city":"blah","telephone":"044 382 0605","id":"2","lati":"-33.9249","lngi":"18.4241"}},{"lat":"-34.0438","lng":"23.0759","data":{"name":"jam factory","address":"15 meeu street knysna","fax":"00000000","email":"00000000","city":"am factory","telephone":"0000000","id":"14","lati":"-34.0438","lngi":"23.0759"}}]
Im sure its just a problem with my view.json.php
also if i change from json_encode to print_r and keep "$query->join('LEFT', '#__managers AS a USING(manager_id)');" i get a response of:
Array
(
)
1
so surely its just the way im outputting the data
Easy as:
public function getBranches()
{
$branch_id = JRequest::getInt('id');
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->select('*, a.manager_name,manager_mobile');
$query->from('#__branches AS t')
->join('LEFT', '#__managers AS a USING(manager_id)')
->where('t.published = 1');
$db->setQuery($query);
$rows = $db->loadObjectList();
return $rows;
}
Thanks For everyone's input. :)
Related
I had been slowly learning PHP OOP, I decided it was time to start inserting into my table, however it doesn't seem to be inserting. I compared my code with working versions and I can't see what the problem might be, I attempted a var_dump(), the query returned as I expected, I tested my database class by creating an new user, it was successfully created so I assume it isn't that, I tested the SQL query and it was able to insert, I'm at a loss for it might be now
form
<?php
session_start();
require ("classes/Review.php");
require ("classes/Database.php");
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$reviewing = new ReviewValidation();
$review = $reviewTitle = "";
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$reviewTitle = $post['reviewTitle'];
$review = $post['review'];
$errors = array();
$fields = array(
'title' => array(
'validate' => 'title',
'message' => 'Title must be at least fife characters',
'value' => $reviewTitle,
),
'review' => array(
'validate' => 'review',
'message' => 'Your review must be at least three hundred characters',
'value' => $review,
)
);
foreach($fields as $key => $value)
{
$validation_result = $reviewing->{$value['validate']}($value['value']);
if(!$validation_result)
{
$errors[] = ['name' => $key, 'error' => $value['message']];
}
}
if(empty($errors))
{
try
{
$db = new Database;
$success = ["message" => "Review subbbmitted"];
$process = $db->prepare('INSERT INTO reviews (reviewTitle)
VALUES
(:reviewTitle');
$process->bindValue(':reviewTitle', $reviewTitle);
$process->execute();
}
catch(Exception $e)
{
$errors[] = ['response' => 'fail'];
}
}
}
header('Content-Type: application/json');
if (empty($errors))
{
echo json_encode($success);
}
else
{
echo json_encode(["errors" => $errors]);
}
class
<?php
class ReviewValidation
{
private
$db,
$review,
$reviewTitle;
private static
$reviewLength = 50,
$rewviewtitleLength = 5;
public static function title($reviewTitle)
{
return(strlen($reviewTitle) >= self::$rewviewtitleLength);
}
public static function review($review)
{
return(strlen($review) >= self::$reviewLength);
}
}
Looks like you may be missing the closing ) in the insert query:
$process = $db->prepare('INSERT INTO reviews (reviewTitle)
VALUES
(:reviewTitle)');
If you add in a closing parenthesis after :reviewTitle, before the single quote your syntax will be correct (shown above).
I also noticed that your calls to the static methods in the ReviewValidation class are using the object operator (->). To access static methods you need to utilize the scope resolution operator.
So your $validation_result line should look like:
$validation_result = ReviewValidation::{$value['validate']}($value['value']);
I think because of this, the validation may have been passing, which is why you where getting the no default value issue.
This is my MongoDB query
db.getCollection('fe_report').aggregate([{
$match:
{ date: { $gte: ISODate("2017-07-01T00:00:00.000Z"),
$lte: ISODate("2017-07-19T00:00:00.000Z")} } },
{
$group:
{
_id :"$employee_id_fk",
no_of_kms : {$sum: "$no_of_kms"},
no_of_orders: {$sum: "$no_of_orders"},
}
}
]
)
i need to execute this query from PHP
config/mongo.php
$config['mongo_server'] = null;
$config['mongo_dbname'] = 'mydb';
libraries/Mongo.php
class CI_Mongo extends Mongo
{
var $db;
function CI_Mongo()
{
// Fetch CodeIgniter instance
$ci = get_instance();
// Load Mongo configuration file
$ci->load->config('mongo');
// Fetch Mongo server and database configuration
$server = $ci->config->item('mongo_server');
$dbname = $ci->config->item('mongo_dbname');
// Initialise Mongo
if ($server)
{
parent::__construct($server);
}
else
{
parent::__construct();
}
$this->db = $this->$dbname;
}
}
And a sample controller
controllers/posts.php
class Posts extends Controller
{
function Posts()
{
parent::Controller();
}
function index()
{
$posts = $this->mongo->db->posts->find();
foreach ($posts as $id => $post)
{
var_dump($id);
var_dump($post);
}
}
function create()
{
$post = array('title' => 'Test post');
$this->mongo->db->posts->insert($post);
var_dump($post);
}
}
try this it work for u
You can use the aggregate function for grouping the fields by ID and computing sum for any columns (only for integer type)
$from = $from.".000Z"; // if you need to filter by date range
$to = $to.".000Z"; // from date and to date("2017-07-22 00:00:00.000Z")
$where = array( array(
'$match' => array(
'date' => array(
'$gte' => new MongoDate(strtotime($from)),
'$lte' =>new MongoDate(strtotime($to)))
)
),
array(
'$group' => array(
'_id' => '$employee_id_fk', // grouping by ID
'no_of_kms' => array(
'$sum' => '$no_of_kms' ' // summing up the KM's fields for the grouped columns
),
'no_of_orders' => array(
'$sum' => '$no_of_orders
)
)
)
);
$data = $this->maggregate('fe_report',$where); // passing it to the maggregate function
// maggregate function()
public function maggregate($table, $where){
$mdb = new MongoClient("localhost"); // establishing mongodb connection
$connect = $m->selectDB("examples")->selectCollection($table);
$result = $connect->aggregate($where);
connect->close();
return $result;
}
I am having trouble with updating the content of two tables. The tables are about users, first table is used for login purposes, so it contains username, email and pass, while the second one is used for user details. Both are connected with the ID of the user row. I am having trouble updating these contents. Here is my code, I am new to CI, so basically don't have a clue what goes wrong.
controller:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Student extends CI_Controller {
public function index()
{
$this->load->model('student_model');
$data['all_students'] = $this->student_model->get_student_list();
$this->load->view('admin_panel', $data);
}
public function view_student()
{
$this->load->model('student_model');
$data['one_student'] = $this->student_model->get_one_student();
$this->load->view('view_student', $data);
}
public function edit_student()
{
$this->load->model('student_model');
$data['one_student'] = $this->student_model->get_one_student();
$this->load->view('edit_student', $data);
}
public function update_student()
{
$this->load->model('student_model');
$data['update_student'] = $this->student_model->update_student();
$this->load->view('admin_panel', $data);
}
}
View
<?php $this->load->view('worker_templates/wheader');
$this->output->enable_profiler(TRUE);
$this->load->helper('form');
echo "<br/><br/><br/><br/><br/>";
echo form_open('student/update_student');
foreach ($one_student as $key => $value)
{
echo "<div class='col-md-6'>";
echo form_label('Name ', 'worker_name');
echo form_input('Name', $value['worker_name']);
echo form_label('Role ', 'role');
echo form_input('Role', $value['role']);
echo form_label('Email ', 'worker_email');
echo form_input('Email', $value['worker_email']);
echo "<br/><br/>";
echo form_label('Phone ', 'phone');
echo form_input('Phone', $value['phone']);
...
This is very long, So I'm not copying it all to bore you.
Model:
public function get_one_student() //used to show a student, also to display data of one student for update
{
$this->db->select('*');
$this->db->from('workers');
$this->db->join('worker_details', 'worker_details.student_id = workers.worker_id');
$this->db->where('worker_id', $_GET['id']);
$q = $this->db->get();
return $q->result_array();
}
public function update_student()
{
$data = array(
'worker_name' => $this->input->post('worker_name'),
'worker_email' => $this->input->post('worker_email'),
'role' => $this->input->post('role'));
$this->db->update('workers', $data); //first table
$data2 = array(
'phone' => $this->input->post('phone'),
'date_of_birth' => $this->input->post('date_of_birth'),
'sex' => $this->input->post('sex'),
'university' => $this->input->post('university'),
'speciality' => $this->input->post('speciality'),
... //again, very long, not including it all
);
$this->db->update('worker_details', $data2);//second table
}
You need to correct your update_student() function in model. please post worker_id in hidden from your html form and correct function as below.
public function update_student()
{
$data = array(
'worker_name' => $this->input->post('worker_name'),
'worker_email' => $this->input->post('worker_email'),
'role' => $this->input->post('role'));
$this->db->where('worker_id', $this->input->post('worker_id'));
$this->db->update('workers', $data); //first table
$data2 = array(
'phone' => $this->input->post('phone'),
'date_of_birth' => $this->input->post('date_of_birth'),
'sex' => $this->input->post('sex'),
'university' => $this->input->post('university'),
'speciality' => $this->input->post('speciality'),
... //again, very long, not including it all
);
$this->db->where('worker_id', $this->input->post('worker_id'));
$this->db->update('worker_details', $data2);//second table
}
Im currently making a google maps component for Joomla 2.5 using Gmaps3, im at the point where it populates the map with markers, but my foreach loop is only returning one object.
Code below:
My View.json.php:
<?php
defined( '_JEXEC' ) or die;
jimport( 'joomla.application.component.view');
class LocateViewBranches extends JView
{
public function display($tpl = null)
{
$branch = $this->get('Branches');
foreach ($branch as $row) {
$response = array(
'lat' => $row->branch_latitude,
'lng' => $row->branch_longitude,
'data' => array(),
);
$response['data'][] = array(
'city' => $row->branch_city,
);
}
echo json_encode($response);
}
}
and then in my Model;
<?php
defined( '_JEXEC' ) or die;
jimport('joomla.application.component.model');
class LocateModelBranches extends JModel
{
public function getBranches()
{
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__branches');
$query->where("published = 1");
$db->setQuery($query);
$rows = $db->loadObjectList();
return $rows;
}
}
Please shout if you guys need more code, but i think those are the two key files.
Thanks in advance
I've tidied up your display function. It will echo a multidimensional array in json format:
public function display($tpl = null)
{
$responses = array(); // assign each row to this array
$branch = $this->get('Branches');
foreach ($branch as $row)
{
// append row data to $responses array
$responses[] = array(
'lat' => $row->branch_latitude,
'lng' => $row->branch_longitude,
'data' => array(
'city' => $row->branch_city
),
);
}
echo json_encode($responses);
}
I haven't tested it but it should be what you need.
I have created a Facebook App that i need people to only enter their data to once.
It's all working and the database is being populated, but i need to make sure people don't keep coming back and re-entering their data endlessly.
What's the best way to check if the user has already submitted their data ?
The signed_request could still have been submitted and their data not entered so i need the check for both to work.
Ideally the PHP would just check for FB ID + other data, and only display a confirmation / thankyou page.
Currently my php to send to the database is:
class Users_Model extends CI_Model {
protected $_name = 'users';
function add($id,$key,$value) {
$data = array(
'id' => $id,
'name' => $key,
'value' => $value
);
return $this->db->insert($this->_name, $data);
}
function update($id,$key,$value) {
$data = array(
'value' => $value
);
$this->db->where(array(
'id' => $id,
'name' => $key
));
return $this->db->update($this->_name, $data);
}
function exists($id,$key=null) {
if($key == null) {
$this->db->where(array(
'id' => $id
));
} else {
$this->db->where(array(
'id' => $id,
'name' => $key
));
}
$query = $this->db->get($this->_name);
if($query->num_rows() > 0) {
return true;
}
return false;
}
function remove($id) {
$data = array(
'id' => $id,
);
return $this->db->delete($this->_name, $data);
}
function all() {
$query = $this->db->get($this->_name);
$results = array();
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$results[]=$row;
}
}
return $results;
}
}
Any help much appreciated...
What's the best way to check if the user has already submitted their data ?
Check if you already have a record for the user’s Facebook id in your database.