Query array on model codeigninter - php

I am a student who learns CodeIgniter, I have a school assignment about the database, I create a project, and run query in my model just like this.
class Send_model extends CI_Model{
function hello(){ $table = $this->db->query("SELECT * FROM (`tbl1`) LEFT JOIN `tbl2` ON `tbl2`.`id` = `tbl1`.`child_id` LEFT JOIN `tbl3` ON `tbl3`.`id` = `tbl1`.`child_id` ");
foreach($table->result() as $row){
$modbus[]= $row->modbus;
$data []= $row->data;
$alert[]= $row->alert;
};
$param0 = '&'.$modbus[0].'='.$data[0].':'.$alert[0];
$param1 = '&'.$modbus[1].'='.$data[1].':'.$alert[1];
$param2 = '&'.$modbus[2].'='.$data[2].':'.$alert[2];
$param3 = '&'.$modbus[3].'='.$data[3].':'.$alert[3];
$param4 = '&'.$modbus[4].'='.$data[4].':'.$alert[4];
$param5 = '&'.$modbus[5].'='.$data[5].':'.$alert[5];
$param6 = '&'.$modbus[6].'='.$data[6].':'.$alert[6];
$param7 = '&'.$modbus[7].'='.$data[7].':'.$alert[7];
$param8 = '&'.$modbus[8].'='.$data[8].':'.$alert[8];
$param9 = '&'.$modbus[9].'='.$data[9].':'.$alert[9];
$param10 = '&'.$modbus[10].'='.$data[10].':'.$alert[10];
$param11= '&'.$modbus[11].'='.$data[11].':'.$alert[11];
$param12 = '&'.$modbus[12].'='.$data[12].':'.$alert[12];
$param13 = '&'.$modbus[13].'='.$data[13].':'.$alert[13];
$param14 = '&'.$modbus[14].'='.$data[14].':'.$alert[14];
$param15 = '&'.$modbus[15].'='.$data[15].':'.$alert[15];
$param16 = '&'.$modbus[16].'='.$data[16].':'.$alert[16];
$param17 = '&'.$modbus[17].'='.$data[17].':'.$alert[17];
$param18 = '&'.$modbus[18].'='.$data[18].':'.$alert[18];
$sent = $param0.$param1.$param3.$param4.$param5.$param6.$param7.$param8.$param9.$param10.$param11.$param12.$param13.$param13.$param14.$param15.$param16.$param17;
return $sent;
}
my controller just like this
class Send extend CI_Controller{
function data ()
{
$this->load->model('send_model');
$send = $this->model->send_model->hello();
echo $sent;
}
}
i have a problem,if tbl1 add data then i have to write adding code to my script
can anyone help me to simplify this code?

It is because you're hard-coding to send only 19 rows of data by creating 19 $param variables. In a dynamic condition, you may have an empty record-set or hundreds of records. Modify the structure of your foreach loop to the following:
$param = array();
foreach($table->result() as $row){
$param[] = '&'.$row->modbus.'='.$row->data.':'.$row->alert;
}
return $param;
Hope it answers your question.

Related

Shorter way in php laravel to load a model in another similar one?

I want to copy every property of the contract model into this another templatecontract model and so on. My code works, but I don't know much about laravel (or php in fact) and my intuition tells me that there must be a better way, or more elegant way.
fill() from Laravel does not get much better. Maybe with a constructor?
Equal tables:
Contract -> TemplateContract
Chapter -> TemplateChapter
Clause -> TemplateClause
public function storeTemplate(ContractCreateRequest $request)
{
DB::beginTransaction();
try
{
$contract = Contract::find($request->input()['type']);
$templatecontract = new TemplateContract();
$templatecontract->id = $contract->id;
$templatecontract->pid = $contract->pid;
$templatecontract->deleted = $contract->deleted;
$templatecontract->sorting = $contract->sorting;
$templatecontract->created_at = $contract->created_at;
$templatecontract->updated_at = $contract->updated_at;
$templatecontract->deleted_at = $contract->deleted_at;
$templatecontract->title = $contract->title;
$templatecontract->description = $contract->description;
$templatecontract->hidden = $contract->hidden;
$templatecontract->contract_type = $contract->contract_type;
$templatecontract->process_type = $contract->process_type;
$templatecontract->tstamp = $contract->tstamp;
$templatecontract->is_english = $contract->is_english;
$templatecontract->usecasetitle = $contract->usecasetitle;
if (Auth::user()) {
$templatecontract->user_id = Auth::user()->id;
}
if($templatecontract->save())
{
$chapter = DB::table('chapter')->where('contract', $templatecontract->id)->get();
if(isset($chapter))
{
foreach ($chapter as $key => $value) {
$templatechapter = new TemplateChapter();
$templatechapter->clause = $value->clause;
$templatechapter->contract = $value->contract;
$templatechapter->created_at = $value->created_at;
$templatechapter->deleted = $value->deleted;
$templatechapter->headlinetype = $value->headlinetype;
$templatechapter->hidden = $value->hidden;
$templatechapter->id = $value->id;
$templatechapter->must = $value->must;
$templatechapter->note = $value->note;
$templatechapter->sorting = $value->sorting;
$templatechapter->title = $value->title;
$templatechapter->tstamp = $value->tstamp;
$templatechapter->updated_at = $value->updated_at;
$templatechapters[] = $templatechapter;
if($templatechapter->save())
{
$clause = DB::table('clause')->where('chapter', $value->id)->get();
if(isset($clause))
{
foreach ($clause as $key => $value) {
$templateclause = new TemplateClause();
$templateclause->id = $value->id;
$templateclause->chapter = $value->chapter;
$templateclause->clausetext = $value->clausetext;
$templateclause->variable = $value->variable;
$templateclause->topic = $value->topic;
$templateclause->deleted = $value->deleted;
$templateclause->selectword = $value->selectword;
$templateclause->shortinfo = $value->shortinfo;
$templateclause->sorting = $value->sorting;
$templateclause->created_at = $value->created_at;
$templateclause->updated_at = $value->updated_at;
$templateclause->hidden = $value->hidden;
$templateclause->tstamp = $value->tstamp;
$templateclause->save();
$templateclauses[] = $templateclause;
}
}
}
}
}
}
//DB::commit();
return response()->success(__('success.showing', ['resource' => 'des Vertrags', 'resourceE' => 'contract']), $templatecontract, 200);
}
catch (Exception $e)
{
return response()->error(__('error.showing', ['resource' => 'des Vertrags', 'resourceE' => 'contract']), 400, $e);
}
}
So almost all of the props from the request matches with the column names. You just need to call the create method of Eloquent model to create a new record and pass key value pair but rather an object. Also, you need not to worry about the extra parameters $contract contains since Laravel will only extract and assign params defined in protected $fillable property of the class.
// cast object to array
$contract = (array) $contract;
$templateContract = TemplateContract::create($contract)

How to return multiple results in a php function

I have the following function that aims to fetch all credits from an artist for a particular song using the ID from the url ($id), and a foreach statement that displays the information on the Web page. At the moment it's displaying the artist names fine, but the IDs aren't being displayed. How would I go about returning the ID information so it's displayed as well?
function getArtistsBySongId($id)
{
$query = "SELECT * FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
LEFT OUTER JOIN `Song` AS s ON s.song_id = c2a.song_id
LEFT OUTER JOIN `Project` AS p ON p.project_id = s.project_id
WHERE c2a.song_id = $id";
$res = mysql_query($query);
$artists = Array();
$artisttoid = Array();
$songtoid = Array();
while( $row = mysql_fetch_array($res) ) {
$artist = $row[artist_name];
$credit = $row[credit_name];
$songcr = $row[song_id];
if(!array_key_exists($artist, $artists) ) {
$artists[$artist] = Array();
$artisttoid[$artist] = $row[artist_id];
$songtoid[$songcr] = $row[song_id];
}
$artists[$artist][] = $credit;
}
return $artists;
return $songtoid;
return $artisttoid;
}
I've used include's in the code because I'm still green to PHP and find it easier to understand.
<table border="0" cellspacing="5" cellpadding="5" class="cdinfo" width="100%;">
<tr>
<?php
if (getArtistsBySongId($id) == NULL) {
echo "<th style='font-size: 13px'>Credits:</th>";
echo "<td style='font-size: 13px'>There are currently no artists linked to this song.</td>";
} else {
include 'songs/getsongcredits.php';
}
?>
</tr>
</table>
songs/getsongcredits.php
<?php foreach (getArtistsBySongId($id) as $artist => $creditarr) {
$credits = implode( ", ", $creditarr );
echo "<a href='star.php?id={$artisttoid[$artist]}'>{$artist}</a> ({$credits})<br />";
} ?>
Objects or arrays are the way to do it
return array('artists' => $artists, 'songtoid' => $songtoid, 'artisttoid' => $artisttoid);
I recomend you to return an object with each item you want in attributes.
To return an object, firstly you need a class:
class MyClass {
private $artists;
private $songtoid;
private $artisttoid;
public function __construct($arg1, $arg2, $arg3){
$this->artists = $arg1;
$this->songtoid = $arg2;
$this->artisttoid = $arg3;
}
public function getArtists(){return $this->artists;}
public function getSongtoid(){return $this->songtoid;}
public function getArtisttoid(){return $this->artisttoid;}
}
In your function
function getArtistsBySongId(){
...
return new MyClass($artists, $songtoid, $artisttoid);
}
Also you can return an associative array like this
return array(
"artists"=>$artists,
"songtoid"=>$songtoid,
"artisttoid"=>$artisttoid
);
Or, if you want, you can return an array (as Machavity answered) and read the result using list()
function getArtistsBySongId(){
...
return array($artists, $songtoid, $artisttoid);
}
list($artists, $songtoid, $artisttoid) = getArtistsBySongId();

failure with find() function using PHP with Silex

Here is the failure message I get in Terminal running 'phpunit tests':
1) StylistTest::test_find
null does not match expected type "object".
/Users/evanbutler/Desktop/hairSalonApp/tests/StylistTest.php:163
Here's my test method:
function test_find()
{
//Arrange
$name = "Stylist Jane";
$id = 1;
$name2 = "Stylist Bob";
$id2 = 2;
$test_stylist = new Stylist($name, $id);
$test_stylist->save();
$test_stylist2 = new Stylist($name2, $id2);
$test_stylist2->save();
//Act
$result = Stylist::find($test_stylist->getId());
//Assert
$this->assertEquals($test_stylist, $result);
}
And here's my method:
static function find($search_id)
{
$found_stylist = null;
$stylists = Stylist::getAll();
foreach($stylists as $stylist) {
$stylist_id = $stylist->getId();
if ($stylist_id == $search_id) {
$found_styist = $stylist;
}
}
return $found_stylist;
}
Here's my getAll method:
static function getAll()
{
$returned_stylists = $GLOBALS['DB']->query("SELECT * FROM stylists;");
$stylists = array();
foreach($returned_stylists as $stylist) {
$name = $stylist['name'];
$id = $stylist['id'];
$new_stylist = new Stylist($name, $id);
array_push($stylists, $new_stylist);
}
return $stylists;
}
If you'd like to see all my files here's the link to the git repository:
https://github.com/evanb2/hairSalonApp.git
I've been staring at this for way too long and I'm totally stumped.
Change
$found_styist = $stylist;
to
$found_stylist = $stylist;
You need a better IDE man. Simple static analysis could tell you about the unused variable.

How to change the number of specifiers with count of providing array in php

My code is given bellow
Controller code:
class statController extends baseController {
public function index() {
$this->registry->template->projectsWise = $this->selectProjectWise();
$this->registry->template->show("stat");
}
private static function selectStat($query, $values) {
$statMapper = new statMapper();
$select = new common();
$select->setItems($query);
$select->setValues($values);
return $statMapper->select($select);
}
private function selectProjectWise() {
$date = date("Y-m-d");
$values = array($date, $date);
return self::selectStat("project_wise", $values);
}
private function selectLocationWise(){
$date = date("Y-m-d");
$values = array($date, $date, 1);
return self::selectStat("location_wise", $values);
}
Mapper code:
class statMapper extends baseMapper {
private $query = array(
"project_wise" => "SELECT p.proj_Name, p.proj_Type, p.proj_Category, COUNT(ra.emp_Id) as allocation FROM project AS p, resource_assignment AS ra WHERE p.proj_Start_Date <= '%s' AND p.proj_End_Date >= '%s' AND p.proj_Status = 1 AND ra.proj_Id = p.proj_Id GROUP BY p.proj_Name ",
"location_wise" => "SELECT e.user_Location, p.proj_Name, p.proj_Type, p.proj_Category, COUNT(ra.emp_Id) as allocation FROM project AS p, resource_assignment AS ra, employee as e WHERE p.proj_Start_Date <= '%s' AND p.proj_End_Date >= '%s' AND p.proj_Status = %d AND ra.proj_Id = p.proj_Id GROUP BY p.proj_Name "
);
public function select($select) {
$connect = parent::connect();
$query = sprintf($this->query[$select->getItems()], $select->getValues()[0], $select->getValues()[1]);
try {
$result = $connect->query($query);
if ($result) {
$table = array();
while ($row = $result->fetch_object()) {
$table[] = $row;
}
return $table;
parent::disconnect();
} else {
throw (new Exception($connect->error . "<br/>" . $query . "<br/>"));
}
} catch (Exception $exp) {
require_once 'views/error.php';
exit();
}
}
}
I have added 3 specifiers ($query->"location_wise") In statController->selectLocationWise() function.
When I use it how do I add $select->getValues()[2] value in statMapper->select(), instead of add it manually.
You can use http://www.php.net/manual/ru/function.vsprintf.php instead of sprintf to pass whole array as argument.
But anyway your code looks bad. From the outside view of StatMapper there is no way to identify neither types of arguments, nor their count. Code will be hard to be maintained.
I advise to use Data Access Objects pattern or learn framework.

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