I use codeigniter mvc for my project, im making a unique id logger that if there id exist it will call the unique generator function again. how to call the function inside model
heres my model:
function getGenLogsId() {
$matches = '12345';
$sql = "SELECT * FROM tbllogs WHERE logsid LIKE '%".$this->db->escape_like_str($matches)."%'";
$q = $this->db->query($sql);
if($q->num_rows() > 0) {
// call function again
} else {
// if not exist save!!
}
}
you can call $this->getGenLogsId();
function getGenLogsId() {
$matches = '12345';
$sql = "SELECT * FROM tbllogs WHERE logsid LIKE '%".$this->db->escape_like_str($matches)."%'";
$q = $this->db->query($sql);
if($q->num_rows() > 0) {
$this->getGenLogsId();
} else {
// if not exist save!!
}
}
if it's in the same controller use :
$this->function();
if it's in the model:
$this->load->model('ModelName');
$this->ModelName->function();
NOTE
if it's in the controller it's a good practice to make it a private function so no direct call is allowed to that function by starting the function name with _
Example:
function _test(){
}
Related
I am new in PHP OOP and was wondering if someone could help me with this.
I have a basic class with one method which returns data from database. Currently I am calling the method which displays everything inside the function.
Here is my class Definition:
class Products{
//properties
public $familyName = "";
public $familyProduct = "";
//Methods
public function getFamily($catId){
global $conn;
$sql = "SELECT * FROM product_family WHERE catID = '$catId'";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "<li>".$row['familyName']."</li>";
echo "<li>".$row['familyProduct']."</li>";
}
}
}
}
Here is how I call the method:
$Products = new Products;
$Products->getFamily( 4 );
This works however, how can I assign each data coming from database ( ex familyName, familyProduct ) into variables inside class implementation and then access them individually where ever I need to. Something like this:
$Products = new Products;
$Products->familyName;
$Products->familyProduct;
I have empty properties but I am not sure how can I assign values to them coming from the loop and then return them each.
Thanks,
There are view things I would change in your Code.
Don't make Properties public use use Getters and Setters.
This will protect you Object from being used the wrong way e.g. now you can't change the familyName from outside: $products->familyName = "some value" because this would make the data of the object corrupt.
global $conn; is a no go in OOP use the construct of the Object,
in your case $products = new Products($conn);
Now you can set a Cat ID $products->setCatId(4); and read the result
$familyName = $products->getFamilyName(); or $familyProduct = $products->getFamilyProduct();
If you have more than one result you will get an array, if catId will always result one row you can delete this part. If you learn more about OOP you will find out that the hole SQL stuff can be done with a separate Object, but this is off Topic.
class Products
{
// Properties
protected $conn;
protected $catId;
protected $familyName;
protected $familyProduct;
public function __construct($conn)
{
$this->conn = $conn;
}
// set Cat ID and get date
public function setCatId($catId)
{
$this->catId = (int) $catId;
$this->getDate();
}
public function getCatId()
{
return $this->catId;
}
// get Family Name
public function getFamilyName()
{
return $this->familyName;
}
// get Family Product
public function getFamilyProduct()
{
return $this->familyProduct;
}
// get date
protected function getDate()
{
$sql = "SELECT * FROM product_family WHERE catID = '$this->catId'";
$result = $this->conn->query($sql);
// Default if no result
$this->familyName = null;
$this->familyProduct = null;
// if one Result
if ($result->num_rows == 1)
{
$row = $result->fetch_assoc();
$this->familyName = $row['familyName'];
$this->familyProduct = $row['familyProduct'];
}
if ($result->num_rows > 1)
{
$this->familyName = [];
$this->familyProduct = [];
while ($row = $result->fetch_assoc())
{
$this->familyName[] = $row['familyName'];
$this->familyProduct[] = $row['familyProduct'];
}
}
}
}
My program is not working properly, i do not know what should i do :S
I got this error message:
Take a look at this:
Here is my code:
My controller file (Home):
<?php
class Home extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model("Crudmodel");
}
public function index(){
# get all data in Study table
$selectStudys = $this->Crudmodel->selectStudys();
foreach ($selectStudys as $key => $study)
{
# get UserNames
$user = $this->Crudmodel->getName($study['user_id']);
#get Subject Names
$subject = $this->Crudmodel->getSubName($study['subject_id']);
#append both NEW VALUES to same array
if(!empty($user[0]['username'])){
$data[$key]['user_id'] = $user[0]['username'];
// your main problem can be this. may be it is not getting value from query this is why we have put validation on model function and error handler condition here
}else{
$data[$key]['user_id'] = ''; // or anything as your else condition you can use as error handler
}
if(!empty($subject[0]['name'])){
$data[$key]['subject_id'] = $subject[0]['name'];
// your main problem can be this. may be it is not getting value from query this is why we have put validation on model function and error handler condition here
}else{
$data[$key]["subject_id"] = "";
// or anything you can use as error handler
}
}
$data['records'] = $selectStudys;
$this->load->view('home', $data);
}
}
?>
Crudmodel:
class Crudmodel extends CI_Model{
public function __construct(){
parent::__construct();
$this->load->database();
}
function selectStudys()
{
$query= $this->db->query("SELECT * FROM cursadas");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
function getName($name)
{
$query= $this->db->query("SELECT username FROM usuarios WHERE id = $name ");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
Dont know what to do now :(
Hope you can help me :S
The problem is in the model. You only return something inside the else. Easy fix, move the return.
You should probably return an empty array if there are no rows. Then the foreach will still have something to work with - even if it is empty. foreach will choke if given something that cannot be used in a loop - a string for instance.
function selectStudys()
{
$query= $this->db->query("SELECT * FROM cursadas");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = array();
}
return $result;
}
I have the following function:
public function count () {
global $db;
$query = "SELECT COUNT(post_id) FROM posts";
$result = $db->select($query);
return $result;
}
This then links to another function:
public function select($query) {
$results = $this->connection->query($query);
while ($obj = $results->fetch_object()) {
$r[] = $obj;
}
if (!empty($r)) {
return $r;
} else {
return false;
}
}
The output is in a form of an array of objects.
Normally I could access the property of that object to get the result.
$result[0]->property
But in this case, the property is encapsulated in the function count(). How can I access that property?
I have utilized a workaround by simply selecting the number of rows from the query. But I still want to know how can I access that property via COUNT().
public function count () {
global $db;
$query = "SELECT * FROM posts";
$result = $db->initiate_query($query)->num_rows;
return $result;
}
public function initiate_query($query) {
$result = $this->connection->query($query);
return $result;
}
Thank you in advance,
Robert
First of all try to use var_dump() on fetched object. That should give you suggestions. I do believe that it is something like $object->count by default in most DBMS engines.
Second option (that I do really prefer in my code) is to use alias on COUNT()ed field:
SELECT COUNT(post_id) as tmp_value FROM posts
Then you should access it as predefined alias states: $object->tmp_value.
In the end you should get something like this:
public function count(){
global $db;
$query = "SELECT COUNT(post_id) as tmp FROM posts";
$result = $db->select($query);
return $result[0]->tmp;
}
I want to store my database query result in my view section in a variable.I am trying but not work.
My View code
$cd=''.base_url().'/video/series/';
$count = count($cd);
for ($i = 0; $i < $count; $i++)
{
print'"'.$cd[$i][1].'",';
}
My Controller code
public function series() {
$result= $this->video_model->series_list();
return $result;
}
My Model Code
function series_list()
{
$string = trim($this->input->get_post('term'));
$query = $this->db->query("SELECT name FROM `series` WHERE name LIKE '%".$string."%'");
return $query->row_array();
}
$cd=''.base_url().'/video/series/'; not get any array data ,only get blank data
You can get post variable value in controller only. But you trying to get it in model. That's wrong.
Controller:
public function series() {
$string = trim($this->input->get_post('term'));
$data['result']= $this->video_model->series_list($string);
$this->load->view('folder/filename', $data);
// in your case i think folder= video and filename = series
// in this way you can pass value from controller to view
}
Model:
function series_list($string = null)
{
if($string != ''){
$query = $this->db->query("SELECT name FROM `series` WHERE name LIKE '%".$string."%'");
return $query->row_array();
}
else
return false;
}
View:
<?php
var_dump($data);
?>
you can get your resultset in view and can play with it as you want.
You need to pass variable inside some array(in view method) so that all variables inside common array would be accessible on view page
Controller code would be
public function series()
{
$inputData =trim(strip_tags($this->input->get_post('term')));
$data['result']= $this->video_model->series_list($inputData);
$this->load->view('directory/viewpage',$data); //$data is array with all variables inside it
}
Model code would be
function series_list($data)
{
$string = $data;
$query = $this->db->query("SELECT name FROM `series` WHERE name LIKE '%".$string."%'");
if( $query->num_rows>0)
{
return $query->row_array();
}
else
{
return false;
}
}
View code would be
<?php
if(isset($result)&&($result!=''))
{
echo "<pre/>";
print_r($result); // Or var_dump($result);
}
?>
I'm using Codeigniter to build a webapp and I received this error:
Fatal error: Call to a member function result_array() on a
non-object in /var/www/application/controllers/people.php on line 29
This is the people.php class:
public function __construct()
{
parent::__construct();
}
function People() {
}
function view($id) {
echo "Hello world " . $id;
}
function all() {
$this->load->model('people_model', '', TRUE);
$allContacts = $this->people_model->get_all_contacts();
$results = array();
foreach ($allContacts->result_array() as $row) {
$eachrow = array("personID"=>$row['personID'],"fName"=>$row['fName'],"lName"=>$row['lName'],"phoneNumber"=>"",
"emailAddress"=>$row['emailAddress'],"address"=>$row['address'],"city"=>$row['city'],"state"=>$row['state'],"zip"=>$row['zip']);
$results = push_array($results, $eachrow);
}
foreach ($results as $row) {
$phoneData = $this->people_model->get_phone_by_id($row['personID']);
$phoneNumbers = "";
foreach ($phoneData->result_array() as $row2) {
$phoneNumbers = $row2['type'] . " " . $row2['phoneNumber'] . " " . $row2['extension'];
}
$results['phoneNumber'] = $phoneNumbers;
}
$data['title']="Page Title Goes Here";
$data['username']="Your Username";
$this->load->view('header', $data);
$this->load->view('people_results', $results);
$this->load->view('footer');
}
}
Here is the people_model class:
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_all_contacts() {
$query = $this->db->query('SELECT * FROM person');
return $query->result();
}
function get_phone_by_id($id) {
$query = $this->db->query('SELECT * FROM phoneNumber WHERE personID = '.$id);
return $query->result();
}
}
The only thing I might question in database.php is if the hostname needs a port number, but I don't think that helped when I tried it.
I just tried adding (based on similar question in side bar)
$this->mydb = $this->load->database('realDB', TRUE);
to the people_model and changing the db to mydb and received this error:
You have specified an invalid database connection group.
and this is my line in database.php:
$db['default']['database'] = 'realDB';
Thanks for all your help.
since get_all_contacts is already using the result() function in your model, you can't also use the result_array() function in your controller. result_array() would be a method of the $query object. The quick and dirty way to get this working(which might break other stuff if its also using the get_all_contacts method) would be to change your get all contacts function to the following:
function get_all_contacts() {
$query = $this->db->query('SELECT * FROM person');
return $query;
}
however, if you want to be smarter about it and not risk breaking other stuff, you can pass a param from the controller, and only return query if its set like so:
REVISED CONTROLLER LINE**
$allContacts = $this->people_model->get_all_contacts(true);
REVISED MODEL CODE
function get_all_contacts($special = false) {
$query = $this->db->query('SELECT * FROM person');
if($special)
{
return $query;
}
return $query->result();
}