How do I multiple records in the bills_infos table?
It takes the data and stores in the array variable and even I can access it with the compact function. I have marked from where the problem starts.
public function store(Request $request){
$request->validate([
'from'=>'required',
'to'=>'required',
'textbox1'=>'required',
'rate1'=>'required',
'qty1'=>'required',
]);
$store_bill=new Bills();
$store_bill->from=request('from');
$store_bill->name=request('to');
$store_bill->discount=request('discount');
if(is_null($store_bill->discount))
{
$store_bill->discount=0;
}
$store_bill->save();
$invoice_no=Bills::orderBy('created_at','desc')->pluck('id')->first();
for($i=1;$i<=10;$i++)
{
$item_name[$i]=request('textbox'.$i);
$amount[$i]=request('rate'.$i);
$quantity[$i]=request('qty'.$i);
}
//return compact('item_name','amount','quantity');
//Works fine till here.
/* Not Working From Here. */
for($i=1;$i<=10;$i++)
{
if(!(is_null($item_name[$i]) || is_null($amount[$i]) || is_null($quantity[$i])))
{
$store_bills_info=new Bills_Infos();
$store_bills_info->bills_id=$invoice_no;
$store_bills_info->item_name=$item_name[$i];
$store_bills_info->amount=$amount[$i];
$store_bills_info->quantity=$quantity[$i];
$store_bills_info->total=$amount[$i]*$quantity[$i];
$store_bills_info->save();
//return compact('store_bills_info');
return view('print')->with('invoice_no',$invoice_no);
}
}
return "Invoice can't be created due to some error";
}
You can use laravel's 'insert' function instead.
Eg.
for($i=1;$i<=10;$i++)
{
if(!(is_null($i`enter code here`tem_name[$i]) || is_null($amount[$i]) || is_null($quantity[$i])))
{
$store_bills_info[$i]['bills_id'] =$invoice_no;
$store_bills_info[$i]['item_name'] =$item_name[$i];
$store_bills_info[$i]['amount'] =$amount[$i];
$store_bills_info[$i]['quantity'] =$quantity[$i];
$store_bills_info[$i]['total'] =$amount[$i]*$quantity[$i];
}
}
Bills_Infos::insert($store_bills_info);
As a query in a loop in not a good practice, we should avoid doing so.
It not work because when your loop is in 0 iteration you used return !
And your loop dosnt go to the next iteration .
When you returning some thing in PHP functions codes after that will not be compiled .
So simply move your return after for .
Related
Today I came up with a legacy code. I have a function that sometimes generates very long runtimes and often occurs timeout at our partner. Mainly the function checks for reserved seats at a theatre but instead of get all the data and check for empty seats it runs the query for every single seat. which (i think) generates the huge runtime.
Here is the correspondig code:
public function printTicketChaos(){
$input = Input::all();
if( isset($input['date_id']) && !isset($input['reserve_id']) ){
$program_date = \Model\ProgramDate::find($input['date_id']);
if($input['piece'] > $program_date->available_capacity){
//dd($input['piece'] . ' ??? ' . $program_date->available_capacity);
return true;
}
$reserved_seats = Session::get('reserved_seats');
if($reserved_seats != null && count($reserved_seats) > 0){
foreach ($reserved_seats as $row => $seats) {
foreach ($seats as $key => $seat) {
$reserve = \Model\Reserve::whereForeignDateId($program_date->id)->whereTableName('programs')->whereHas('seats', function($query) use($row, $seat){ $query->whereRow($row)->whereSeat($seat); })->first();
if($reserve != null){
return true;
}
$oi = \Model\OrderItem::whereForeignId($program_date->id)->whereTableName('programs')->whereHas('order', function($query){ $query->whereStorno(0); })->whereHas('seats', function($query) use($row, $seat){ $query->whereRow($row)->whereSeat($seat); })->first();
if($oi != null){
return true;
}
}
}
}
}
return false;
}
I think the solution could be that i query all the seats and then check for the empty ones in the foreach. Is this a good idea or what do you think which is the best way to do it?
The code uses Laravel 4.2
Thank you for your aswers!
Okay, i made changes in the query and the logic aswell but it was still slow as hell.
The system uses a 3rd party PDF generator to create the "ticket" for the costumer and this was the "bad guy".
Just wondering if it is necessary to use else {return false;} in my codeigniter model functions or if () {} is enough and it returns false by default in case of failure?
controller:
if ($this->model_a->did()) {
$data["results"] = $this->model_a->did();
echo json_encode($data);
}
model:
public function did()
{
//some code here
if ($query && $query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
in your controller -- test the negative condition first - if nothing came back from the method in your model
if ( ! $data["results"] = $this->model_a->did() ) {
$this->showNoResults() ; }
else { echo json_encode($data); }
so thats saying - if nothing came back - then go to the showNoResults() method.
If results did come back then its assigned to $data
However - in this situation in the model i would also put ELSE return false - some people would say its extra code but for me it makes it clearer what is happening. Versus methods that always return some value.
I think this is more of a PHP question than a CodeIgniter question. You could easily test this by calling your model methods and var_dump-ing the result. If you return nothing from a method in PHP, the return value is NULL.
As much i have experience in CI returning false is not a plus point, because if you return false here then you need to have a condition back in controller which is useless you should be doing like this will save you at least some code of lines
if ($query && $query->num_rows() > 0) {
return $query->result_array();
} else {
return array();
}
so returning an array will save you from many other errors, like type error.
I have to search for multiple values in a field using mysql in codeigniter. Here follows my code.
In Controller
public function vpsearch()
{
$data['info'] = $this->psearch_m->emp_search_form();
$this->load->view("employer/result",$data);
}
IN Model
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
$jrole = $this->input->post('ps_jobrole'));
if ( $jrole !== NULL)
{
return $this->db->get('js_edu_details');
$this->db->like('js_skills','$skill');
}
}
In view i.e, (../employer/result)
foreach($info->result() as $row)
{
echo $row->js_id."<br/><br/>" ;
}
However I am getting all the records in 'js_edu_details' table instead of fields having searched 'skills'.
Where I am going wrong? Any help wud b appreciated, thanx in advance.
Try:
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
//$skill = $this->input->post('ps_skills', true); other short way of getting the above result with `xss clean`
if ( $jrole !== NULL)
{
$this->db->like('js_skills',$skill); #remove the single quote around the `$skill`
$res = $this->db->get('js_edu_details');
echo $this->db->last_query(); #try to print the query generated
return $res;
}
}
Return statement should be after the like statement
You should arrange the code properly like this
public function emp_search_form()
{
$ps_skills = $this->input->post('ps_skills')
$skill = $this->security->xss_clean($ps_skills);
if ( $jrole !== NULL)
{
$this->db->like('js_skills','$skill');
return $this->db->get('js_edu_details');
}
}
Also you should note the condition will never meet. It will always give error undefined variable $jrole
I have the following code to validate form data. I have created functions to validate various groups, and then have an if isset statement to check if these functions return true. I have tried many different ways to get this to work.
The problem I am having is this. I want the if isset to end if returning FALSE; but it doesn't, it keeps going and pops up the next alert (in my code I have many functions). How can I get it to exit after the first return FALSE? Do I need to make the isset into a function? So it can exit on return FALSE. thanks
I am having trouble writing a function to call functions in php.
function namecheck ($fname, $lname)
{
$regexp ="/^[A-Za-z]+$/";
//filter through names
if (preg_match($regexp,$fname,$lname))
{
return TRUE;
}
else
{
echo'<script type="text/javascript">alert("Enter your names.")</script>';
return FALSE;
}
}
function emailcheck ($email1, $email2)
{
$regexp="/^[a-zA-A-Z0-9_.]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+$/";
//validate email address
if (preg_match($regexp,$email1,$email2))
{
return TRUE;
}
else
{
echo '<script type="text/javascript">alert ("Enter a valid email address.")</script>';
return FALSE;
}
}
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$namecheck=namecheck($fname,$lname);
$email1=$_POST['email1'];
$email2=$_POST['email2'];
$emailcheck=emailcheck($email1,$email2);
if (isset($_POST['submit']))
{
if ($namecheck !==TRUE)
{
return FALSE;
}
elseif ($emailcheck!==TRUE)
{
return FALSE;
} //and so on..
else
{
return TRUE;
}
}
A general structure for your functions you could follow is something like this:
function validateName($name) {
// Do Validation. Return true or false.
}
function validateEmail($email) {
// Do Validation. Return true or false.
}
function isFormValid()
{
// Name Validation
if( ! validateName( $_POST['name'] ) )
return false;
// Email Validation
if( ! validateEmail( $_POST['email'] ) )
return false;
// Form is valid if it reached this far.
return true;
}
// In your regular code on Form Submit
if( isset($_POST['submit']) )
{
if( isFormValid() ) {
// Save Form Data to DB
} else {
// Show Some Errors
}
}
That general structure should work fine for you. It could be made a LOT better but, for the sake of learning, this is sufficient.
If you want the script to, as you put, "exit" then you need to use exit(); Generally this is bad as the script will completely stop executing. Maybe you can look into using "break;" to get you out of a loop and stop executing functions within that loop. Another problem is that you are echoing out HTML code in your function which gets executed on assignment and so you will always get an alert generated when it evaluates to FALSE.
edit:
within your if(isset()) block. Inside here you can do{}while(false); which is a loop and will let you break out of it at anytime and prevent further execution of code within that loop.
If a function isn't returning false, then it never reached a return FALSE; statement. It's as simple as that. So let's examine the relevant code:
if (isset($_POST['submit']))
{
if ($namecheck !==TRUE)
{
return FALSE;
}
elseif ($emailcheck !== TRUE)
{
return FALSE;
} //and so on..
else
{
return TRUE;
}
}
So, if $_POST['submit'] is set and is not null, the if block will be reached. Then, if $namecheck is not true OR $emailcheck is not true, the function will return FALSE. You can simplify the above code to just:
if (isset($_POST['submit']))
{
return !(!$namecheck || !$emailcheck);
}
However, it doesn't look like this code is inside a function, so the return statement will do nothing. You have to put it in a function if you want it to work like a function.
Beyond that, I can't help you. I don't know what you want to do with this code. You seem to know how to use and call functions, so I'm not sure what the problem is. If you want to return from a function, put code in a function and call return. Right now your code is not in a function, so return won't do anything.
I need little Active record help. I am trying to update page views which i store in database. Each time post() function runs, add +1 . Here is my code:
public function post($id) {
if($id == NULL){
redirect('blog');
}
else{
$this->db->where('entry_id',$id);
$this->db->set('views','views+1');
$this->db->update('entry');
Please help!
Correct your code like this for example:
public function post($id) {
if(!isset($id) || (int) $id<=0){
header('Location: /blog');
}
else{
$this->db->where('entry_id',$id);
$this->db->set('views','views+1');
$this->db->update('entry');
}
Mark the header('Location: /blog') - you should put here your real server path to the blog.
If you use a custom redirection function, like your redirect() then check if the is an output before calling her. Header redirection only works if no other output is sent to the browser before invoking it.
public function post($id) {
if($id == NULL){
redirect('blog');
}
else{
$this->db->where('entry_id',$id);
$this->db->set('views','views+1',FALSE);
$this->db->update('entry');
FALSE turns off Active record escaping,by default it ignores +1.