Laravel Getting an error Undefined offset: 3 - php

I am getting an error in my laravel application. The error states that Undefined offset:3.
Controller
public function updateVisaDocuments($type, $details, $visa, $documents_id){
$visas_documents_db = \App\VisaDocuments::where ( 'visa_id', $visa->id )->get();
foreach($visas_documents_db as $document_db){
$count=0;
for($j = 0; $j < sizeof ( $documents_id ); $j ++) {
if($document_db->id==$documents_id [$j]){
$count++;
}
}
if($count==0)
$document_db->delete();
}
for($i = 0; $i < sizeof ( $type ); $i++) {
if(!empty($type[$i])){
if(!empty($documents_id[$i])){
$visa_documents = \App\VisaDocuments::where ( 'id', $documents_id[$i] )->first ();
}else{
$visa_documents=new VisaDocuments();
$visa_documents->id=Uuid::generate ();
}
$visa_documents->type=$type[$i];
$visa_documents->details=json_encode($details);
$visa_documents->visa_id=$visa->id;
if(!empty($documents_id[$i]))
$visa_documents->update();
else
$visa_documents->save();
}
}
}
foreach ($visa->documents as $documents){
$i++;
$det=json_decode($documents->details,true);
$size_det=sizeof($det);
$size_det_inside=sizeof($det[$i]);
$k=0;
View
<?php $size_det_inside = sizeof($det[$i]);?>
#for($j=0; $j< $size_det_inside; $j++)
#if($det[$i][$j] != '')
<input type="text" name="document_details[{{$i}}][]" value="{{$det[$i][$j]}}" />
#endif
#endfor
I am getting error here sizeof($det[$i]); (View). I guess, the result is in json format and in my view file i am treating it as variable.
Can anyone please help me on this.

If your php version is 7.0 or above, you should use count() function instead of sizeof(). Please use count().
http://php.net/manual/en/function.sizeof.php

Related

foreach loop as category with Codeigniter

Here is my database :
-id product prodcut-company category
-1 latitude dell laptop
-2 . acer desktop
-3 . azus mouse
-4 . sony keyboard
+If I have many product separated by category, then I want loop it by category how can I coding and show it in one page then list it as a block like laptop , desktop,...
please help !
thank you
You may create a method in the model like this-
public function getData(){
$this->db->from("product_table");
$this->db->order_by("category");
$q = $this->db->get();
if($q->num_rows() > 0){
return $q->result();
}
return [];
}
Fetch data from model using this method in the controller and pass this value to the view.
$data[
'products' => $this->your_model->getData()
];
$this->load->view('your_view',$data);
Loop these values and print in the view.
...
<?php
if(!empty($products)){
$count = count($products);
$i = 0;
while($i < $count){
$category = $products[$i]->category;
echo '<h3>Category: '.$category.'</h3>';
echo '<table>
<tr><th>Product</th><th>Company</th><th>Category</th></tr>
';
for(; $i < $count && $category == $products[$i]->category ; $i++ ){
echo '
<tr>
<td>'.$products[$i]->product.'</td>
<td>'.$products[$i]->company.'</td>
<td>'.$products[$i]->category.'</td>
</tr>
';
}
echo '</table>';
}
}
?>
...

Getting Undefined offset: 1 in laravel

I am new to Laravel and was developing small application for my practise. I am doing job search functionality. This error giving me alot trouble and confuses me alot.
public function job_search(Request $request) {
$search_skill_set = $request->job_skills;
$search_results = JobPost::whereRaw('FIND_IN_SET(?, job_skills)', $search_skill_set)
->get()
->toArray();
for ($i = 0; $i < count($search_results); $i++) {
$department_id = (int)$search_results[$i]['department_name'];
$department_name = Department::select('department_name')
->where('id', '=', $department_id)
->get()
->toArray();
// the next statement raises an Undefined:offset 1 error
$search_results[$i]['department_name_info'] = $department_name[$i]['department_name'];
}
var_dump($search_results);
}
I am not getting where am i doing wrong, so any suggestion from given snippet and any modification in the code
change this line:
$search_results[$i]['department_name_info'] = $department_name[$i]['department_name'];
to
$search_results[$i]['department_name_info'] = $department_name[0]['department_name'];
for ($i=0; $i < count($search_results) ; $i++) {
$department_id = (int)$search_results[$i]['department_name'];
//I am getting department id correct here
$department_name = Department::select('department_name')->where('id','=',$department_id)->get()->toArray();
//$depratment_name is also going okay and working
$search_results[$i]['department_name_info'] = $department_name[0]['department_name'];
// This line should have a static index.
}

PHP: A string, two arrays and 4 loops result in a 0

In my android app user can upload up to 5 images for an item they have in their collection.
This is what my android app java code is sending over to the PHP server via POST:
[user_id=83,
item_id=24,
item_number_of_photos=1,
item_image_filename_0=http://www.asdqwe.net/item_images/83_image_2014-02-07-16-44-12.jpg,
item_image_description_0=mouse]
This is the PHP Code that handles it:
if (!empty($_POST)) {
$user_id = $_POST["user_id"];
$item_id = $_POST["item_id"];
$item_number_of_photos = $_POST['item_number_of_photos'];
for ($x=0; $x<$item_number_of_photos; $x++) {
if(isset($_POST['item_image_filename_'.$x]) && !empty($_POST['item_image_filename_'.$x])) {
$item_image_filenames[$x] = $_POST['item_image_filename_'.$x];
}
if(isset($_POST['item_image_description_'.$x]) && !empty($_POST['item_image_description_'.$x])) {
$item_image_descriptions[$x] = $_POST['item_image_description_'.$x];
}
}
$query_add_item_photos = "INSERT INTO
product_photos (
product_id,
product_photo,
product_photo_added_by_user,
product_photo_description
)";
////////////////////////////////////////////////////////////
////ADD THE PHOTOS TO THE PHOTOS TABLE//////////////////////
////////////////////////////////////////////////////////////
try {
for($x = 0; $x<$item_number_of_photos; $x++) {
$query_add_item_photos+= " VALUES
(
:product_id,
:product_photo_filename_" . $x .",
:product_photo_added_by_user,
:product_photo_description_" . $x . "
)";
}
$input_parameters = array(
':product_id' => $item_id,
':product_photo_added_by_user' => $user_id,
);
for($x = 0; $x<$item_number_of_photos; $x++) {
$input_parameters[':product_photo_filename_' . $x] = $item_image_filenames[$x];
$input_parameters[':product_photo_description_' . $x] = $item_image_descriptions[$x];
}
$sth = $connection->prepare($query_add_item_photos);
$sth->execute($input_parameters);
} catch(PDOException $pe) {
$response["success"] = $http_response_server_error;
$response["message"] = $http_response_server_error . $pe . $query_add_item_photos;
die(json_encode($response));
}
$response["success"] = $http_response_success;
$response["message"] = "WE MADE IT";
die(json_encode($response));
$connection = null;
} else {
$response["success"] = $http_response_bad_request;
$response["message"] = $http_message_bad_request;
die(json_encode($response));
$connection = null;
}
At the end when I run this, I get a PDO error saying that the query = "0".
I have only basic understanding of PHP so this is huge pain for me
Local Variables Issue
In your for loop, you are assigning values to $item_image_filenames[$x] array element and also to $item_image_descriptions[$x] array element.
for ($x=0; $x<$item_number_of_photos; $x++) {
...
$item_image_filenames[$x] = $_POST['item_image_filename_'.$x];
...
$item_image_descriptions[$x] = $_POST['item_image_description_'.$x];
}
But (assuming you have posted all of your code), these 2 arrays fall out of scope and disappear as soon as you exit your for loop. They weren't defined before your for loop, which means that they are being defined local to your for loop.
The result of this is that, later, when you attempt to reference these arrays, they don't exist, and they have no values. So, later on in your code...
for($x = 0; $x<$item_number_of_photos; $x++) {
$input_parameters[':product_photo_filename_' . $x] = $item_image_filenames[$x];
$input_parameters[':product_photo_description_' . $x] = $item_image_descriptions[$x];
}
... is going to result in assigning to $input_parameters values that don't exist.
To solve this problem, define $item_image_filenames and $item_image_descriptions before you enter your for loop. This way, they will continue to exist inside and after your for loop. You can do this:
$user_id = $_POST["user_id"];
$item_id = $_POST["item_id"];
$item_number_of_photos = $_POST['item_number_of_photos'];
// Define empty arrays so that I can use them throughout my code.
$item_image_filenames = array();
$item_image_descriptions = array();
for ($x=0; $x<$item_number_of_photos; $x++) {
...
String Concatenation Syntax
I also noticed that your line of code:
$query_add_item_photos+= " VALUES
...
... is not the correct way to do string concatenation in PHP. You want to use .= instead of +=. In PHP, strings are concatenated with ., as in the example: $string1 = $string2 . $string3;
Your code should instead be:
$query_add_item_photos .= " VALUES
...

Codeigniter/PHP How to properly use a for loop?

<?php
print_r($optimum);
$dataNumRows = count($optimum);
?>
<?php for ($i = 0; $i < $dataNumRows; $i++) : ?>
<?php echo $cFirstName; ?>
<?php echo $cLastName; ?>
<?php endfor; ?>
My print_r inserted in my VIEW shows the following:
Array ( [cFirstName] => Array ( [0] => Tom [1] => Alexa ) [cLastName] => Array ( [0] => Jones [1] => Planter ) )
My MODEL is the following
//Get all the customers currently pending
//install for the user making the request.
function getAllCustomersPendingInstall()
{
$data=array();
//Need to use sessions to display proper
//records for each user. Temp set id to user #7
$id = 7;
//query the db and return all record where SalesRepId == $id
$query = $this->db->get_where('customers', array('SalesRepId' => $id));
//check logic, if rows exist RETURN all rows, else
//return message that no pending installs is available.
if($query->num_rows != 0) {
foreach($query->result() as $row) {
$data['cFirstName'][] = $row->customerFirstName;
$data['cLastName'] [] = $row->customerLastName;
}
} else {
$data = "No pending installs available!";
return $data;
}
//the following var_dump is only showing the last record.
//need to show all rows (which should be 2)
//var_dump($data); exit;
return $data;
}
My CONTROLLER is the following
{
$this->load->library('table');
$this->load->model('GetData');
$data['optimum'] = $this->GetData->getAllCustomersPendingInstall();
$this->load->view('welcome_message', $data);
}
And my question is how do I properly use the FOR loop in my VIEW so that I can loop through all the returned rows. As you can see the print_r is properly returning the proper rows- However I am unable to loop through them. Thanks for the help! Much appreciated!
Try this in your view:
<?php for ($i = 0; $i < $dataNumRows; $i++) : ?>
<?php echo $optimum['cFirstName'][$i]; ?>
<?php echo $optimum['cLastName'][$i]; ?>
<?php endfor; ?>
I think what you're trying to do is get an associative array for each row returned from the database. Correct me if I'm wrong about that.
Should fix your problem
$data = array();
$data_index = 0;
if($query->num_rows != 0) {
foreach($query->result() as $row) {
$data[$data_index]['cfirst'] = $row->customerFirstName;
$data[$data_index]['clast'] = $row->customerLastName;
$data_index++;
}
} else {
$data = "No pending installs available!";
return $data;
}
then in your view (where $customer is the $data array)
<?php foreach($customer as $c):?>
<?php echo $c['cfirst'];?>
<?php endforeach;?>

Having an issue with array keys, undefined index

I'm working with a couple of arrays, one of which has keys that are the productid, the value being an object that contains a doctrine entity of that product. Similarly, I have a plan with the index being the plan Id. For this for loop, I need to go through and individually set up invoices for each plan-product pair (the quantity will always be the same between them, except in cases where a user is purchasing a plan for an already owned device). Obviously this is somewhat complicated, so I'm not exactly sure how to phrase this question. An error occurs at the commented line, "Notice: Undefined Index"
for ($i = 0; $i < $totalInvoices; $i++) {
if ($i == $planQuantity[key($plans)]) {
next($plans);
}
if ($i == $productQuantity[key($products)]) {
next($products);
}
$data = array(
'planId' => key($plans),
//below here, I'm thinking at key($products) is where the error occurs
'productId' => key($products) != 0 ? key($products) : $plans[key($plans)]->getPricingTier()->getProductId(),
'userId' => $this->userId,
'paymentMethodId' => $paymentMethodId
);
if ($order['hasProduct'] || isset($order['activating'])) {
if (!isset($order['activating'])) {
$planModel->createDevicePlan($data);
$productAmount = $products[key($products)]->getAmount();
} else {
$data['deviceId'] = $order['activating']['inventoryId'];
$planModel->createDevicePlan($data, date('Y-m-d'));
$productAmount = 0;
}
} else {
$productAmount = 0;
}
if ($iteration % 5 == 0 && $order['hasShipping']) {
$invoiceShippingAmount = $billingModel->getShippingAmount($shippingOptionsId);
} else {
$invoiceShippingAmount = 0;
}
$salesData = array(
'paymentMethodsId' => $paymentMethodId,
'planAmount' => $plans[key($plans)]->getAmount(),
'planId' => key($plans),
'productAmount' => $productAmount,
'productId' => key($products),
'shippingAddressesId' => $shippingAddressId,
'shippingAmount' => $invoiceShippingAmount,
'shippingOptionsId' => $shippingOptionsId,
'transactionId' => $transactionId,
'userId' => $this->userId
);
$iteration++;
$billingModel->createInvoice($salesData);
}
Any help would be greatly appreciated.
Based on your comment reply, I think this will help
$plans_on_invoice = 0;
$products_on_invoice = 0;
for ($i = 0; $i < $totalInvoices; $i++) {
next($plans);
if ($plans_on_invoice == 0) {
$plans_on_invoice = $planQuantity[key($plans)];
}
plans_on_invoice--;
next($products);
if ($products_on_invoice == 0) {
$products_on_invoice = $productQuantity[key($products)];
}
products_on_invoice--;

Categories