How to count the number of students from each course from the mysql database?

So, I want to make a calculator that will calculate this formula:

Result = No. of Attendance / (No. of Students * No. of School Days) 

but I want the No. of students to be counted automatically by course and strand (different column) from the database.

This is the initial code:

<?php include 'includes/session.php'; ?>
<?php include 'includes/header.php'; ?>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">

  <?php include 'includes/navbar.php'; ?>
  <?php include 'includes/menubar.php'; ?>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
        Calculator
      </h1>
    </section>
    <!-- Main content -->
    <section class="content">
      <div class="row">
        <div class="col-md-12">
          <div class="box box-info">
            <div class="box-body">
              <form method="post">
                <label for="D">No. of Attendance:</label>
                <input type="text" id="D" name="D" placeholder="No. of Attendance" value="<?php echo isset($_POST['D']) ? $_POST['D'] : '' ?>"><br>
                <label for="B">No. of Students:</label>
                <input type="text" id="B" name="B" placeholder="No. of Students" value="<?php echo isset($_POST['B']) ? $_POST['B'] : '' ?>"><br>
                <label for="C">No. of School Days:</label>
                <input type="text" id="C" name="C" placeholder="No. of School Days" value="<?php echo isset($_POST['C']) ? $_POST['C'] : '' ?>"><br>
                <button type="submit" name="submit" value="submit">Calculate</button>
              </form>
              <h4>
                <?php
                if (isset($_POST['submit'])) {
                    // Retrieve user input values for D, B, and C
                    $D = isset($_POST['D']) ? $_POST['D'] : 0;
                    $B = isset($_POST['B']) ? $_POST['B'] : 0;
                    $C = isset($_POST['C']) ? $_POST['C'] : 0;

                    // Ensure the inputs are numeric
                    if (is_numeric($D) && is_numeric($B) && is_numeric($C)) {
                        // Check if B and C are not zero to avoid division by zero error
                        if ($B != 0 && $C != 0) {
                            // Calculate A = D / (B * C)
                            $A = $D / ($B * $C);
                            // Convert to percentage
                            $percentage = $A * 100;
                            echo "Result: A = " . $A . " or  " . $percentage . "%";
                        } else {
                            echo "Error: Division by zero";
                        }
                    } else {
                        echo "Please enter numeric values for D, B, and C";
                    }
                }
                ?>
              </h4>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
  <!-- /.content-wrapper -->
</div>
<!-- ./wrapper -->

<?php include 'includes/scripts.php'; ?>
</body>
</html>

This is the code I edited:

<?php include 'includes/session.php'; ?>
<?php include 'includes/header.php'; ?>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">

  <?php include 'includes/navbar.php'; ?>
  <?php include 'includes/menubar.php'; ?>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
        Calculator
      </h1>
    </section>
    <!-- Main content -->
    <section class="content">
      <div class="row">
        <div class="col-md-12">
          <div class="box box-info">
            <div class="box-body">
              <form method="post">
                <label for="course">Select Course:</label>
                <select id="course" name="course">
                  <option value="">Select Course</option>
                  <?php
                  // Fetch courses from your database and populate the dropdown menu
                  // Assuming you have a database connection already established
                  $query = "SELECT * FROM position_college"; // Modify this query according to your database schema
                  $result = mysqli_query($connection, $query);
                  if ($result) {
                      while ($row = mysqli_fetch_assoc($result)) {
                          echo "<option value='" . $row['description_college'] . "</option>";
                      }
                  }
                  ?>
                </select><br>
                <label for="D">No. of Attendance:</label>
                <input type="text" id="D" name="D" placeholder="No. of Attendance" value="<?php echo isset($_POST['D']) ? $_POST['D'] : '' ?>"><br>
                <label for="B">No. of Students:</label>
                <input type="text" id="B" name="B" placeholder="No. of Students" value="<?php echo isset($_POST['B']) ? $_POST['B'] : '' ?>"><br>
                <label for="C">No. of School Days:</label>
                <input type="text" id="C" name="C" placeholder="No. of School Days" value="<?php echo isset($_POST['C']) ? $_POST['C'] : '' ?>"><br>
                <button type="submit" name="submit" value="submit">Calculate</button>
              </form>
              <h4>
                <?php
                if (isset($_POST['submit'])) {
                    // Retrieve user input values for D, B, C, and the selected course
                    $D = isset($_POST['D']) ? $_POST['D'] : 0;
                    $B = isset($_POST['B']) ? $_POST['B'] : 0;
                    $C = isset($_POST['C']) ? $_POST['C'] : 0;
                    $selected_course = isset($_POST['course']) ? $_POST['course'] : 0;

                    // Ensure the inputs are numeric
                    if (is_numeric($D) && is_numeric($B) && is_numeric($C) && $selected_course) {
                        // Check if B and C are not zero to avoid division by zero error
                        if ($B != 0 && $C != 0) {
                            // Calculate A = D / (B * C)
                            $A = $D / ($B * $C);
                            // Convert to percentage
                            $percentage = $A * 100;
                            echo "Result: A = " . $A . " or  " . $percentage . "%";
                        } else {
                            echo "Error: Division by zero";
                        }
                    } else {
                        echo "Please enter numeric values for D, B, C, and select a course";
                    }
                }
                ?>
              </h4>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
  <!-- /.content-wrapper -->
</div>
<!-- ./wrapper -->

<?php include 'includes/scripts.php'; ?>
</body>
</html>

But this code doesn’t work and it doesn’t seem to provide result the I wanted it to give. These are the tables in the database

enter image description here
enter image description here

navigation bar misplaced or just wrong codes. i don’t now what to do anymore

the navigation bar and side bar is not supposed to be in the admin log in page.

the navigation bar and side bar should only pop ups after i logged in as admin.

this is the admin log in page with navigation bar that not supposed to be there.
///picture///

yet this is what happened after i logged in, the design are not existing.

///picture///

i don’t understand why its wrong.

this is the code for that navigation bar and nav side bar.

` <?php

 if(is_admin_login())
{

?>
 <body class="sb-nav-fixed">
    <nav class="sb-topnav navbar navbar-expand navbar-dark bg-dark">
        <!-- Navbar Brand-->
         <a class="navbar-brand ps-3" href="index.php">Library System</a>
        <!-- Sidebar Toggle-->
        <button class="btn btn-link btn-sm order-1 order-lg-0 me-4 me-lg-0" id="sidebarToggle" href="#!"><i class="fas fa-bars"></i></button>
        <form class="d-none d-md-inline-block form-inline ms-auto me-0 me-md-3 my-2 my-md-0">
        </form>
        <!-- Navbar-->
        <ul class="navbar-nav ms-auto ms-md-0 me-3 me-lg-4">
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" id="navbarDropdown" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"><i class="fas fa-user fa-fw"></i></a>
                <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
                   <li><a class="dropdown-item" href="logout.php">Logout</a></li>
                </ul>
            </li>
        </ul>
    </nav>

    <div id="layoutSidenav">
        <div id="layoutSidenav_nav">
            <nav class="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion">
                <div class="sb-sidenav-menu">
                    <div class="nav">

                    <a class="nav-link" href="logout.php">Logout</a>

                    </div>
                </div>
                <div class="sb-sidenav-footer">
                   
                </div>
            </nav>
        </div>
        <div id="layoutSidenav_content">
            <main>

<?php 
}`

and this is the code for the admin login page where that code from above should not be here in admin log in page.

`<?php

//admin_login.php

include ‘database_connection.php’;

include ‘function.php’;

$message = ”;

if(isset($_POST[“login_button”]))
{

$formdata = array();

if(empty($_POST["admin_email"]))
{
    $message .= '<li>Email Address is required</li>';
}
else
{
    if(!filter_var($_POST["admin_email"], FILTER_VALIDATE_EMAIL))
    {
        $message .= '<li>Invalid Email Address</li>';
    }
    else
    {
        $formdata['admin_email'] = $_POST['admin_email'];
    }
}

if(empty($_POST['admin_password']))
{
    $message .= '<li>Password is required</li>';
}
else
{
    $formdata['admin_password'] = $_POST['admin_password'];
}

if($message == '')
{
    $data = array(
        ':admin_email'      =>  $formdata['admin_email']
    );

    $query = "
    SELECT * FROM lms_admin 
    WHERE admin_email = :admin_email
    ";

    $statement = $connect->prepare($query);

    $statement->execute($data);

    if($statement->rowCount() > 0)
    {
        foreach($statement->fetchAll() as $row)
        {
            if($row['admin_password'] == $formdata['admin_password'])
            {
                $_SESSION['admin_id'] = $row['admin_id'];

                header('location:admin/index.php');
            }
            else
            {
                $message = '<li>Wrong Password</li>';
            }
        }
    }   
    else
    {
        $message = '<li>Wrong Email Address</li>';
    }
}

}

include ‘header.php’;

?>

<div class="col-md-6">

    <?php 
    if($message != '')
    {
        echo '<div class="alert alert-danger"><ul>'.$message.'</ul></div>';
    }
    ?>

    <div class="card">

        <div class="card-header">Admin Login</div>

        <div class="card-body">

            <form method="POST">

                <div class="mb-3">
                    <label class="form-label">Email address</label>

                    <input type="text" name="admin_email" id="admin_email" class="form-control" />

                </div>

                <div class="mb-3">
                    <label class="form-label">Password</label>

                    <input type="password" name="admin_password" id="admin_password" class="form-control" />

                </div>

                <div class="d-flex align-items-center justify-content-between mt-4 mb-0">

                    <input type="submit" name="login_button" class="btn btn-primary" value="Login" />

                </div>

            </form>

        </div>

    </div>

</div>

`

i’m watching this from the youtube and carefully write codes line per line and yet the output i get is not the same as i watch from the youtube. this is the video link:

since this is my first time doing php. i used to do java coding.

Undefined array key “text” warning [closed]

I’m trying to solve the issue of Undefined array key “text”, but implemented fix doesn’t seem to work. Any ideas? 🙁 The whole file is fairly big, thousands of line, wondering if that’s part of the issue but error is same line always

ORIGINAL

  static function _helper_to_panel_values() {
        // add the rest
        foreach (self::get_all() as $id => $config) {
            $buffy_array[] = array(
                'text' => $config['text'],
                'title' => '',
                'val' => $id,
                'img' => $config['img']
            );
        }

        // the first template is the default one, ex: it has no value in the database
        $buffy_array[0]['val'] = '';

        return $buffy_array;
    }

TRYING TO FIX

static function _helper_to_panel_values() {
    $buffy_array = array(); // Initialize the array to avoid undefined variable warning

    // add the rest
    foreach (self::get_all() as $id => $config) {
        // Check if 'text' key exists in $config array before accessing it
        $text = isset($config['text']) ? $config['text'] : '';
        $img = isset($config['img']) ? $config['img'] : '';
        
        $buffy_array[] = array(
            'text' => $text,
            'title' => '',
            'val' => $id,
            'img' => $img
        );
    }

    // the first template is the default one, ex: it has no value in the database
    $buffy_array[0]['val'] = '';

    return $buffy_array;
}

Index jumping out of for-loop with recursive method calling and || operator in Javascript

I am working with tree-like structure in Javascript, I found for-loop of Javascript works unexpected way. Let me describe it:

<html>
<head><head>
<body>
<script>
class Test {
        constructor(name, children) {
            this.children = [];
            this.test = () => {
                let result = false;
                for (let i = 0; i < this.children.length; i++) {
                    console.log(this.children[i].name);
                    result = result || this.children[i].test();
                }
                if (this.name.includes('2')) result = true;
                return result;
            };
            this.name = name;
            this.children = children;
        }
    }

    const t = new Test('1', [
        new Test('11', [
            new Test('111', []),
            new Test('112', []),
        ]),
        new Test('12', [
            new Test('121', []),
            new Test('122', []),
        ]),
    ]);
    const result = t.test();
    console.log(result);
</script>
</body>
</html>

The above code is pure Javascript. A Test class may have children which are also Test class. It also have a test() method which returns boolean, the method has for-loop over its children, calls children’s test() method, then sums the result with || operator.

(So it is implementation of a kind of logical Some() operation on child nodes.)

However, the above code does not call the test() method of the Test instances with names 121 and 122.

  • If I replace the following part,

    result = result || this.children[i].test();
    

    with

    const subResult = this.children[i].test();
    result = result || subResult;
    

    then it works fine. It iterates over all the children.

  • If I modify the for-loop as following,

    for (let i = 0; i <= this.children.length; i++) { // <----- '<' has been replaced with '<='
        if (i === this.children.length) {
            console.log(i); // this prints '2' after calling '0'
        }
        console.log(this.children[i].name);
        result = result || this.children[i].test();
    }
    

    I can see the index of for-loop is jumping out.

  • If I make the method to return false by removing the if (this.name.includes('2')) result = true; then the all children’s test() methods are called.

  • I have tested the above codes in Chrome, Firefox and Safari, and got the same result.

Is this behavior correct? And if it is, can someone explain me the theory?

i got 2 errors while trying to import from products.json file into a main.js file

error 1:Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “text/css”. Strict MIME type checking is enforced for module scripts per HTML spec.

error 2:Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “application/json”. Strict MIME type checking is enforced for module scripts per HTML spec.

I found these two errors.

i tried ‘type’ attribute in script element tag.

.

but it couldn’t work.

i was expecting that it would import the products of products.json file into the main.js by using the import statement as follows:

import products from “./api/products.json”;
console.log(products);

Connect with mongodb [closed]

Connecting NodeJs with Mongo

I know two ways to connect with mongo first one is to install local server and work with it and second one is to get link from Mongo Db atlas and put it inside my code which one is better and more common to work with mongodb localserver or direct with Mongo Db atlas

How to set default prop data in Next.js?

I’m making React/Next app with CRUD.
About update form, I made some code below.
This code is fetching existing data and after renewing the data, updating through api.
Regrettably this code has big problem.

If you don’t update input form, the data that is title and content will disappear without trace.
I understand updating data could be done only when setTitle and setContent work.
But I don’t know how to fix this code as I expected.

If you only updated the title, the content would be clear after pushing submit button.
Like this.

Before

  • title: aaa
  • content: bbb

Update title aaa to aaaa

After

  • title: aaaa
  • content:

My code is here.

import Link from "next/link";
import { client } from "@/libs/client";
import { useRouter } from "next/router";
import React, { useState } from "react";

export default function Update ({ blog }) {
  const router = useRouter()
  const id = blog.id;
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");

  async function update(event) {
    event.preventDefault()

    client.update({
      endpoint: "blogs",
      content: {
        title: title,
        content: content,
      },
      contentId: id
    }).then((res) => {
      if (res.status === 401) {
        alert("Something wrong is happening")
      } else {
        alert("Editing is done")
        router.push(`/`)
      }
    })
  }

  return (
    <>
      <div className='main'>
        <h1 className=''>Edit page</h1>

        <div className="contents">

            <div>
                <form onSubmit={ update }>
                  <div>
                      <h2>Here's title</h2>
                      <input name="title" type="text" defaultValue={blog.title} onChange={(event) => setTitle(event.target.value)} />
                  </div>
                  <div>
                  <h2>Contents</h2>
                      <textarea name="content" defaultValue={blog.content} onChange={(event) => setContent(event.target.value)} ></textarea>
                  </div>
                <button type="submit">
                    <p>Submit</p>
                </button>
                </form>
            </div>
        </div>
      </div>
    </>
  );
}

export const getStaticPaths = async () => {
  const data = await client.get({ endpoint: "blogs" });

  const paths = data.contents.map((content) => `/blog/${content.id}/update`);
  return { paths, fallback: false };
};

export const getStaticProps = async (context) => {
  const id = context.params.id;
  const data = await client.get({ endpoint: "blogs", contentId: id });

  return {
    props: {
      blog: data,
    },
  };
};

How do i modify a specific part of a website with a firefox/chrome extension

I am making a extension which works on youtube , what it does is that if comments are turned off it replaces the Comments are turned off. Learn more with a input box . How do i achieve this ?

my js code so far :

document.addEventListener('DOMContentLoaded', function() {
  console.log("DOM content loaded. Checking comments status...");

  function checkCommentsStatus() {
    const addCommentElement = document.querySelector('yt-formatted-string#text');
    console.log("Found 'Add a comment' element:", addCommentElement);
    if (addCommentElement && addCommentElement.textContent.trim() === "Add a comment...") {
      console.log("Comments are turned on.");
    } else {
      console.log("Comments are turned off. Modifying...");


      const container = document.createElement('div');
      container.setAttribute('id', 'comment-modification-container'); 

      
      const textBox = document.createElement('input');
      textBox.setAttribute('type', 'text');
      textBox.setAttribute('placeholder', 'Enter your comment');
      textBox.style.marginRight = '10px';

      
      const submitButton = document.createElement('button');
      submitButton.textContent = 'Submit';
      submitButton.addEventListener('click', () => {
        console.log("Submit button clicked.");
      });

      
      container.appendChild(textBox);
      container.appendChild(submitButton);

      // Find the element containing the "Comments are turned off" text
      const commentsOffElement = document.querySelector('yt-formatted-string#message');
      
      
      if (commentsOffElement && commentsOffElement.textContent.trim() === "Comments are turned off.") {
        commentsOffElement.parentNode.replaceChild(container, commentsOffElement);
        console.log("Text box and submit button added successfully.");
      } else {
        console.log("Failed to find the 'Comments are turned off' element to replace with the text box and submit button.");
      }
    }
  }

  checkCommentsStatus();
});

here’s what i’ve tried so far:

created a content script that listens for the domcontentloaded event to ensure the page is fully loaded.
implemented a function (checkcommentsstatus) to check if comments are turned on or off by searching for specific elements in the youtube video page.
utilized console.log statements throughout the code to track the script's execution and debug any issues.

what i got :

script sometimes fails to detect when comments are disabled or cannot find the appropriate elements to modify

Inherit type of parameters from class

We have a class with some users and we need to type it using interfaces.

class User {
   name: string = '';
   lastName: string = '';
   age: number = 18;
   isAdmin: boolean = false;

   constructor(props) {
      if (props?.name) this.name = props.name;
      if (props?.lastName) this.lastName = props.lastName;
      if (props?.age) this.age = props.age;
      if (props?.isAdmin) this.isAdmin= props.isAdmin;
   }

    add(key, value) {
       this[key] = value;
    }
}

The first interface will describe the types that come to our constructor and will look like this:

interface IUser {
  name?: string;
  lastName?: string;
  age?: number;
  isAdmin?: boolean;
}

The second interface should describe the parameters that come in add method. Types in the second interface must inherit from the type described in the IUser interface. How can we implement this?

Why cant I run successfully two test files appium and webdriverio?

When running android mobile tests using appium 2.5.4, uiAutomator2-server: 3.5.0, I encountered some issues. Sometimes 1 of the tests would pass but most of the time the tests would fail with the error below

```An unknown server-side error occurred while processing the command. Original error: POST /element cannot be proxied to UiAutomator2 server because the instrumentation process is not running (probably crashed). Check the server log and/or the logcat output for more details.```

I have uninstalled the app and tried to run test again but it keeps failing. Also , how can close the app after running each test? I have tried driver.closeApp but none seem to be working

Reducer function in redux gets called multiple times

Please someone make me understand the underlying behavior of redux. Here is my reducer function with one case:

  case INCREASE_QTY:
      return state.map((product) => {
        if (product.id === action.payload.id) {
          return {
            ...product,
            data: {
              ...product.data,
              qty: product.data.qty + action.payload.qty,
            },
          };
        }
        console.log('hello')
        return product;
      });

In above case, I was mistakenly returning state instead of product outside the if block. This was causing unexpected behavior.

action creator:

export const increaseQty = (id, qty) => {
  return {
    type: INCREASE_QTY,
    payload: {
      id,
      qty,
    },
  };
};

and dispatching action:

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { increaseQty } from '../redux/productSlice/actions';
import { deleteFromCart } from '../redux/cartSlice/actions';

const CartCard = ({ product }) => {
  const cart = useSelector((state) => state.cart);
  const dispatch = useDispatch();

  const deleteHandler = (id) => {
    const correspondingProduct = cart.productInfo.find(
      (product) => product.id === id
    );

    dispatch(deleteFromCart(correspondingProduct.id));
    dispatch(increaseQty(correspondingProduct.id, correspondingProduct.qty));
  };

  return (
    <div className="cartCard">
      <div className="flex items-center col-span-6 space-x-6">
        <img className="cartImage" src={product.data.image} alt="product" />

        <div className="space-y-2">
          <h4 className="cartName">{product.data.name}</h4>
          <p className="cartCategory">{product.data.category}</p>
          <p>
            BDT <span className="cartPrice">{product.data.price}</span>
          </p>
        </div>
      </div>

      <div className="flex items-center justify-center col-span-2 mt-4 md:justify-end md:mt-0">
        <button
          className="removeFromCart"
          onClick={() => deleteHandler(product.id)}
        >
          <i className="text-lg text-red-400 fa-solid fa-trash"></i>
        </button>
      </div>
    </div>
  );
};

export default CartCard;

My question is, if I have multiple products in cart and wanna delete an item, the unexpected behavior was it was deleting all items. However I found that I was doing wrong in the reducer function. But I want to understand, if the ID matches, hello should not pe printed on the console. And thus the unexpected behavior would not happen. But in this case, console.log() is being called though the if block is executed. Why?
Thanks in advance.

how to run append file in node.js ? error graphql 500 (Internal Server Error) . terminal error fs-capacitorlibindex.js:169 this.closed = true;

I am a beginner of NodeJS and need a little help. Scenario is that first user with phone and password register and the information commit in MongoDB, then user login according to phone and password and new token generate, after that if we run a user query and send token that generate in previous step with HTTP HEADERS. Print message. Now I want to append index.html file when open index.js in browser user can upload image and in right click on page and select inspect and in the console print POST http://localhost:4000/graphql 500 (Internal Server Error) .also Terminal print error

node_modulesfs-capacitorlibindex.js:169
        this.closed = true;
                    ^

TypeError: Cannot set property closed of #<Writable> which has only a getter

in Robo 3T we have two collections (users, multimedias).the information of image doesnot save in Collections multimedias.
Also the source codes are attach. Thanks for your time and configuration

enter image description here
enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

my source code

main source code