How to display the HTML which is the inside for each if the foreach is empty

I have the below code on my page and it’s working when there is any data in the $getbanking variable. But if $getbanking is empty then I am getting the below error

Warning : Invalid argument supplied for foreach() in

I have to run the below code if there $getbanking is empty at least once. So that it will display the upload option to the user.

<?php 
  $getbanking = unserialize($info['banking_details']); 

  $i=1;
  foreach ($getbanking as $bankdoc => $b) { ?>
<div class="col-xl-3 col-lg-3 col-md-3 col-sm-12 col-xs-12">
  <div class="documentUploadWrap">
    <label>Bank <?php echo $i;?></label>
    <div class="upload_doc <?php if(!empty($b)){ echo " imgext uploaded ";} ?>">
    <input type="hidden" name="banking[<?php echo $bankdoc;?>]" value="<?php echo $b;?>">
      <input type="file" name="banking[<?php echo $bankdoc;?>]" class="fileupload noofbank" accept="image/png, image/jpeg, application/pdf, .doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
      <div class="uploadInfo">
        <div class="upload_icon"></div>
        <p>Drop your image here, or <span>browse</span></p>
        <span>Supports: JPEG, PNG, DOC, PDF</span>
      </div>
      <div class="previewFile">
        <a href="uploads/<?php echo $b;  ?>" target="_blank">
          <div class="previewFileIcon text-center"></div>
        </a>

        <p class="fileNamePreview"><?php echo $b;  ?></p>

      </div>
      <?php if($i>=2){?>
      <div class="close-box close-box-bank"><img src="assets/images/x-circle.svg"></div>
      <?php }?>
    </div>
  </div>
</div>
<?php $i++; } ?>

PHP don’t recognize row variables

I am having trouble posting a mysql table to my website.

Basically, the php error says that the row variable that I used was undefined. I tried using a code from a youtube tutorial but to no avail.

I also checked my sql query on phpmyadmin and it seems to work just fine.

Here is my test code for your reference:

 <!DOCTYPE html>
<html>
<head>
<title>Table with database</title>
<style>
table {
border-collapse: collapse;
width: 100%;
color: #588c7e;
font-family: monospace;
font-size: 25px;
text-align: left;
}
th {
background-color: #588c7e;
color: white;
}
tr:nth-child(even) {background-color: #f2f2f2}
</style>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Transaction</th>
<th>Website</th>
</tr>
<?php
$conn = new mysqli('localhost','sasuke', 'sharinganrox', 'uchiha_db');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT clientData.Client_ID, clientData.Client_Name, transactionData.Transaction_ID, transactionData.Transaction_Date, websiteProduct.Website_ID, websiteProduct.Website_Name,
            FROM clientData CROSS JOIN transactionData on clientData.Client_ID = transactionData.Client_ID CROSS JOIN websiteProduct on transactionData.Website_ID = websiteProduct.Website_ID WHERE monthname(transaction_date)='January' ORDER BY transaction_date ASC;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {

// output data of each row
while($row = mysqli_fetch_array($result)) {
echo "<tr><td>" . $row["client_name"]. "</td><td>".$row["transaction_ID"]."</td><td>".$row["transaction_date"]."</td><td>".$row["website_Name"]."</td><td>".$row["website_Price"]."</td></tr>";
}
echo "</table>";
} else { echo "0 results"; echo "number of rows: " . $result->num_rows; }

$conn->close();
?>
</table>
</body>

The error says:
Notice: Undefined index: client_name in C:wamp64wwwaugusta_webapptestingtable.php on line 41

Notice: Undefined index: transaction_ID in C:wamp64wwwaugusta_webapptestingtable.php on line 41

Notice: Undefined index: transaction_date in C:wamp64wwwaugusta_webapptestingtable.php on line 41

Notice: Undefined index: website_Name in C:wamp64wwwaugusta_webapptestingtable.php on line 41

Notice: Undefined index: website_Price in C:wamp64wwwaugusta_webapptestingtable.php on line 41

PHP session lost after file download

I installed my web application at a new host.
Everything is fine except when downloading files.
The PHP session is lost when a user opens a file (example: a PDF) in another tab of the browser and therefore the user is logged out of the application.
I am having this problem with Chrome and Edge, but not with Firefox.
I did not have this problem when the application was hosted at the previous host.
I would like to stay with the new host because its servers are very efficient.
PHP server version is 7.3.
Do you know why this may happen?

Error Messages For Entire Form Are Being Outputted On Each Instance Of A Loop – PHP

I have a form that outputs images and some HTML <input> elements for adding titles and tags to images. This is outputted onto the page using a while loop inside a <form> element. The submit button for the form is outside of the loop, so you can submit multiple images one go.

When an error is present I would like to output the error message for that particular instance of the image component inside its related upload component – namely the div with the class upload-component. Is that possible with PHP or is it better to just prevent the form processing with PHP if an error is found (e.g. an empty title input element), and then show the specific errors with JavaScript for that particular image component (which I should be able to work out how to do with JS)?

Currently when an error is found the PHP outputs each error for the entire form in each component – i.e. if there are 3 errors on just one component, 3 error messages appear appear at the top of every component in the loop. This is obviously being caused by using a foreach loop to output the errors. When I remove the foreach though it doesn’t output anything because it can’t process the array of potential errors?

NOTE: The $user_id variable is assigned through a $_SESSION when the user is logged in.

Many thanks in advance for any help.

<?php 

if(isset($_POST['upload-submit'])) {
    
    $image_title = $_POST['image-title'];
    $image_tags = $_POST['image-tags'];
    $image_id = $_POST['image-id']; // value attribute from hidden form element

    // check for errors - empty title input element not allowed
    forEach($image_title as $title) {
        if(empty(trim($title))){
            $error[] = "Image Title must be between 10 and 150 characters long";
        }
    }

    if (!isset($error)) {

        // ---- UPDATE DATABASE WITH PDO STATEMENTS IF NO ERRORS

    } 
}
?>

<form method="post" enctype="multipart/form-data">

    <!-- IMAGE COMPONENT - START -->

        <?php

        $stmt = $connection->prepare("SELECT * FROM lj_imageposts WHERE user_id = :user_id");

        $stmt->execute([
            ':user_id' => $user_id
        ]); 

        while ($row = $stmt->fetch()) {
            $db_image_id = htmlspecialchars($row['image_id']);
            $db_image_title = htmlspecialchars($row['image_title']);
            $db_image_tags = htmlspecialchars($row['image_tags']);
        ?>

    <div class="upload-component">                
        <?php 
            // echo error messages from above
            if(isset($error)) {
                foreach($error as $msg) {
                    echo "<p>** ERROR: {$msg}</p>";
                }
            }
        ?>
            <div class="upload-image-wrapper">
                <img class="img upload-details-img" src="project/img/image.jpg">
            </div>
            <div class="edit-zone">
                <div class="form-row">
                    <label for="title-id-<?php echo $db_image_id; ?>">Image Title</label>
                    <input id="title-id-<?php echo $db_image_id; ?>" value="<?php $db_image_title; ?>" type="text" name="image-title[]">
                </div>
                <div class="form-row">
                    <label for="tags-id-<?php echo $db_image_id; ?>">Comma Separated Image Tags</label>
                    <textarea id="tags-id-<?php echo $db_image_id; ?>" type="text" name="image-tags[]"></textarea>
                    <input type="hidden" name="image-id[]" value="<?php echo $db_image_id; ?>">
                </div>
            </div>
    </div>

    <?php } ?>

    <div class="form-row">
        <button type="submit" name="upload-submit">COMPLETE UPLOAD</button>
    </div>
</form>

How to query to display data that has different months?

So, I have a view report display that filters Period From and Period To, as shown below:

View Filter Report

And, I have employee data with dates like this:

View Data Employee

Then, when I view the report, the end_date for February doesn’t appear because the Period From and To process is only in January. It should appear because the start_date is in January.

Image Display of Report Results

This is my query, please help.

$this->db->select("a.id, a.employee_id, a.employee_name, a.leave_name, a.start_date, a.end_date, a.status, 
                   b.id, b.employee_id, b.job_title_name, b.employment_status_name")
         ->join('hr_employee b', 'a.employee_id = b.employee_id', 'left')
         ->where("a.start_date AND a.end_date BETWEEN '$data[from]' AND '$data[to]'");

   return $this->db->get('hr_leaves a');

Laravel composer install problem ( newbie )

Can someone help me. I want to clone this project from https://github.com/chogainz/calorie-counter .

I want do composer install for this project and i got this error.

my php is 7.4

So how i want to solve this problem ?

The error i got after “composer install”
error after composer install

env file :

APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null 
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_KEY=
PUSHER_SECRET=
PUSHER_APP_ID=

composer.json :

{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
    "php": ">=5.6.4",
    "laravel/framework": "5.3.*"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~5.0",
    "symfony/css-selector": "3.1.*",
    "symfony/dom-crawler": "3.1.*"
},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\": "app/"
    },
    
        "files": [
    "app/helpers.php"
]
    
},
"autoload-dev": {
    "classmap": [
        "tests/TestCase.php"
    ]
},
"scripts": {
    "post-root-package-install": [
        "php -r "file_exists('.env') || copy('.env.example', '.env');""
    ],
    "post-create-project-cmd": [
        "php artisan key:generate"
    ],
    "post-install-cmd": [
        "Illuminate\Foundation\ComposerScripts::postInstall",
        "php artisan optimize"
    ],
    "post-update-cmd": [
        "Illuminate\Foundation\ComposerScripts::postUpdate",
        "php artisan optimize"
    ]
},
"config": {
    "preferred-install": "dist"
}

}

Can a slash in the url be taken as a query insntead of a path to a file directory

By my limited understanding the ” / ” in an URL defines a path in the file directory the html is suppost to be pulled from.

So how is it possible that sites like reddit have URLs such as “reddit.com/u/username”, where the slash doesn’t define the file directory but is more so taken as a query that requests certain data from a user? Shouldn’t you get an error back, that the site doesn’t exist because it’s not actually a file in the directory?

How to solve this MYSQL Query in php page?

I am new on MYSQL. I have a data in MYSQL database like this (example):-

S.no Book Name Date of Publication Publication ctags
1 ABC 2021 Oxford Free,Video,Audio,Licensed
2 DEF 2020 Cambridge Free,Video,Licensed,
3 GHI 2019 Bloomberry Free,Audio,Licensed
4 JKL 2018 Penguin Free,
5 MNO 2017 Jaya Prakash Licensed
6 PQR 2016 Null Free,Video,Audio

There are multiple tag in the ctags column that are separated with comma. I shared above table only for simple example. In my MYSQL Database there is a column named as ctags and here I am sharing the original mysql querry on php page.

The below code show all the information (s.no 1 to 6) in the page but I want to show those resource that are not ctags with licensed (s.no 4 and 6)

$qnew = "SELECT title, 
                location, 
                access_restrictions 
         FROM title t, location_title lt, location l 
         WHERE t.title_id = lt.title_id 
         AND l.location_id = lt.location_id 
         AND eres_display = 'Y' 
         order by t.title_id DESC limit 0,5";

The below code show nothing but I want to show those resource that are ctags with licensed (s.no 1, 2, 3 and 6).

$qnew = "SELECT title, 
                location, 
                access_restrictions 
         FROM title t, location_title lt, location l 
         WHERE t.title_id = lt.title_id AND l.location_id = lt.location_id 
         AND eres_display = 'Y' 
         AND ctags = 'Licensed' 
         order by t.title_id DESC limit 0,5";

What should I use to get the information from the MYSQL database. Kindly help me to get this.

Rrweriter function does not work at the beginning of the sentence

I have a rewriter function. I compare and replace the variables in the curly brackets with the ones in the text.

For example;

My variables are: [“Hello|Hi”,”How are you| What’s up”,”quick|rapid|swift|agile|brisk”]

Text: Hello, how are you?

Rewritten text: Hello, {How are you| what’s up}

Even if I add an extra word per sentence with str_replace, the first words do not change. Even if I change the first sentence to
“word_to_be_deleted Hello, how are you?” I still get the same result.

Sentences:

$sentences = ["Hello|Hi","How are you| What's up","quick|rapid|swift|agile|brisk"];

Rewrite function:

function rewriter($text) {
    global $sentences;
    $text = nl2br($text);
    $text = str_replace(', ', ' , ', $text);
    $text = str_replace(', ', ' , ', $text);
    $text = str_replace('?', ' ? ', $text);
    $text = str_replace('.', ' . ', $text);
    $text = str_replace('<br />', ' <br /> word_to_be_deleted ', $text);
    foreach ($sentences as $sentence) {
        $exsentence = explode('|', trim($sentence));
        $i = 0;
        foreach ($exsentence as $sax) {
            if (count($exsentence) > $i) {
                // $lastsentences[trim($exsentence[$i])] = implode('|', array_diff($exsentence, array($exsentence[$i])));
                $lastsentences[trim($exsentence[$i])] = implode('|', $exsentence);
            }
            $i++;
        }
    }
    // uzunluğa göre array'i diz
    array_multisort(array_map('strlen', array_keys($lastsentences)), SORT_DESC, $lastsentences);

    foreach ($lastsentences as $key => $value) {
        $text = preg_replace(sprintf('/{[^}]+}(*SKIP)(*F)|%s/i', preg_quote(' ' . $key . ' ', '/')), ' {<b style="color:red">' . $value . '</b>} ', ' ' . $text . ' ');
    }

    $text = str_replace(' | ', '|', $text);
    $text = str_replace(' , ', ', ', $text);
    $text = str_replace(' , ', ', ', $text);
    $text = str_replace('.  ', '. ', $text);
    $text = str_replace(' .', '.', $text);
    $text = str_replace(' .', '.', $text);
    $text = str_replace('word_to_be_deleted', '', $text);
    return html_entity_decode($text);
}

Headings that do not change even though the variable is defined:
enter image description here

php laravel eloquent object can not be changed

I have a weird bug, I dont know why it will not work. So I am using Laravel php framework and getting from db a object. Since some decimal number looks like this : ‘.00’, I want to change it to this ‘0’, but it cannot be changed when I loop through it.
It looks like this:

 $stipendien = Stipendium::where('id','=',$request->input('id'))->get()->toArray();


        
        foreach($stipendien as $object => $test)
        {
            foreach($test as $key => $value)
            {
                if($test[$key] == ".00")
                {
                    $test[$key] = "0";
                }
            }
        }
return $stipendien;

Should not the ‘$stipendien’ be changed when I assign the value new, since it does go to the if statement and getting the correct key ?

array:2 [
  0 => array:17 [
    "id" => 1
    "Kosten_Kurs" => "22.00"
    "Kosten_Prüfung" => ".00"
    "Kosten_Unterlagen" => ".00"
    "Kosten_Lernurlaub" => ".00"
    "Kosten_Reise" => ".00"
    "Kosten_Sonstig" => ".00"

  ]
  1 => array:17 [
    "id" => 2
    "Kosten_Kurs" => "22.00"
    "Kosten_Prüfung" => "2.00"
    "Kosten_Unterlagen" => ".00"
    "Kosten_Lernurlaub" => ".00"
    "Kosten_Reise" => ".00"
    "Kosten_Sonstig" => ".00"
  ]
]

But when I return it, it did not change at all. What did I wrong here?

If statement with file get contents to avoid 403 error

i am trying to get string of cross domain but sometime or some website gives a 403 Forbidden error. So to protect from getting error i am trying to include if statement, if site one get error while getting string then it will move to else part and take string from site two.

Error :

Warning: file_get_contents(https://www.example.com): Failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden

Code :

$siteone = file_get_contents("https://www.example.com");
$sitetwo = file_get_contents("https://www.example.net");

if ($siteone === false) {
      $error = error_get_last();
      echo $sitetwo;
} else {
      echo $siteone;
}

So, here if example.com give 403 error then it automatically ignore example.com and get string from example.net.

I have also tried try and catch but it didn’t work. Please help!!

how to count number of present(status 1 means present) for each student and input beside each student profile under present column

daily_attendances database

below is under crud_model

public function take_attendance()
    {
        $students = $this->input->post('student_id');
        $data['timestamp'] = strtotime($this->input->post('date'));
        $data['class_id'] = html_escape($this->input->post('class_id'));
        $data['section_id'] = html_escape($this->input->post('section_id'));
        $data['school_id'] = $this->school_id;
        $data['session_id'] = $this->active_session;
        $check_data = $this->db->get_where('daily_attendances', array('timestamp' => $data['timestamp'], 'class_id' => $data['class_id'], 'section_id' => $data['section_id'], 'session_id' => $data['session_id'], 'school_id' => $data['school_id']));
        if($check_data->num_rows() > 0){
            foreach($students as $key => $student):
                $data['status'] = $this->input->post('status-'.$student);
                $data['student_id'] = $student;
                $attendance_id = $this->input->post('attendance_id');
                $this->db->where('id', $attendance_id[$key]);
                $this->db->update('daily_attendances', $data);
            endforeach;
        }else{
            foreach($students as $student):
                $data['status'] = $this->input->post('status-'.$student);
                $data['student_id'] = $student;
                $this->db->insert('daily_attendances', $data);
            endforeach;
        }

        $this->settings_model->last_updated_attendance_data();

        $response = array(
            'status' => true,
            'notification' => get_phrase('attendance_updated_successfully')
        );

        return json_encode($response);
    }



public function get_presentcount_by_student_id($student_id="",$status ="") {
        
        $checker = array(
        
            'student_id' => $student_id,
            'status'    => 1
        );
        $presentcount_by_student_id = $this->db->get_where('daily_attendances', $checker);
        return $presentcount_by_student_id->num_rows();
    }

under the list.php where it shows the student name and the number of days present for each student.The code is below but it does not count number of presents for each student.It still remains 0

<td>
            
                
              <?php  echo $this->crud_model->get_presentcount_by_student_id($student['user_id'],'status');?>
              <br>
              
            </td>

Student detail list shown in table format
student_detail_list

Transparent dynamic circular progress bar in JavaScript/CSS like hollow from inside or background image visible?

I achieved the circular progress bar with background color like this:

enter image description here

But when i try to use this same code but without background color it becomes PI or rectangular. I want to achieve like this:

enter image description here

But what i have is:

enter image description here

If i try to remove bg color it becomes

enter image description here

I searched a lot but couldn’t found any solution.

Here is the code that i am using for this.

<!-- Progress bar -->
<div class="bar-container">
   <div class="circular-progress" style="background: conic-gradient(#FFCAF0 <?php echo $percentage * 3.6; ?>deg, #003866 5deg);">
      <div class="value-container"><?php echo $percentage; ?>%</div>
     </div>
</div>

Here is CSS code:

.bar-container {
        background-color: #003866;
        display: grid;
        place-items: center;
    }
    .circular-progress {
        position: relative;
        height: 200px;
        width: 200px;
        border-radius: 50%;
        display: grid;
        place-items: center;
    }
    .circular-progress::before {
        content: "";
        display: block !important;
        position: absolute;
        height: 84%;
        width: 84%;
        background-color: #003866;
        border-radius: 50%;
    }
    .value-container {
        position: relative;
        font-size: 20px;
        color: #FFCAF0;
    }