Using a Variable in WP Download Manger Shortcode

sorry if this isn’t allowed here as it is related to WordPress but it is PHP related.

I am using a wordpress plugin called Pods – Custom Content Types and Fields and WP Download Manager.

In PODs I have created a POD that has a user select from drop down a post from WP Downlods Manger. This is set as resource_link_protected. This is all fine and I can display the Download by using magic tags such as

echo '{@resource_link_protected.ID}'; //DISPLAYS 1554 FOR EXAMPLE

This will display the ID number of the selected download. Works Great! However, I need to uses this value in a shortcode So I use:

$linkid = '{@resource_link_protected.ID}';
echo do_shortcode("[wpdm_package id='$linkid' template='link-template-button']");

This doesn’t work, if I echo $linkid it displays 1554 as per my example above. If I replace $linkid with 1554 in the shortcode, it works and displays a button.

Why when I create a variable ($linkid = '{@resource_link_protected.ID}';) does it work to echo etc. but then doesn’t work inside the shortcode even though $linkid = '1554' would?

How do I manipulate this AND Statement?

I am a novice and in my place of work, I am directed to change the output of the result attached with this my writeup.
We usually use CA1 as our Midterm result, but this time the management said they want to be using the CA1 and CA2 as the Midterm which affect the previous method. The total mark for each CA is 10 but during the midterm we do multiply it by 10 to make it 100 for the grades.
Which is written in the SQL query score*10 as ca. But now when I am asked to add the CA2, it means the total mark for CA1 and CA2 should not exceed 100 because the grade is in percentage and should not exceed 100.

I don’t know how to go about this, I have done some try by error but all to no avail. I would be glad if I could get a help on this. Here is the sql statement

 , score*10 as ca
                            FROM result r
                                 JOIN 
                                 (
                                 student_class sc 
                                 JOIN class cl ON sc.classid = cl.id
                                 JOIN level l ON cl.levelid = l.id
                                 JOIN course c ON c.levelid = l.id
                                 JOIN student st ON sc.studentid = st.id
                                 JOIN semester sm ON sc.semesterid = sm.id
                                 JOIN session sn ON sm.sessionid = sn.id
                                 JOIN subject s ON c.subjectid = s.id
                                 ) ON r.studentclassid = sc.id AND exam = 'CA1'  and r.courseid = c.id

From the sql above, on the last line, I don’t know how to include the CA2, I have tried like separating with comma but not working and on the first line above, can I declare score5 as ca1 and score5 as ca2?

enter image description here

How to get Wav instead of Ogg using Web Audi API?

I developed some web pages (HTML, PHP and VanillaJS) dealing with sound samples with Web Audio API. Everything works fine even if this was a bit challenging for me.

After some treatments of the samples, the goal is to save 1 to 4 samples files in one. I achieved it but the only issue I met is the fact that I’m unable to get merged samples in Wav format but always in OGG format.
Ok, this is not so annoying but I’m not working for me but for somebody who is totally ignorant in term of sound file and would like to be able to play the file without the need of any extra software, so WAV format is a kind of standard for him.

I searched but didn’t find any solution. Hereunder is a part of the code I use to initialize :

const AudioContext = window.AudioContext || window.webkitAudioContext;
const context = new AudioContext();    
var destRec = context.createMediaStreamDestination();
var mediaRecorder = new MediaRecorder(destRec.stream);

Once all the process done :

mediaRecorder.onstop = function(evt) {
// Make blob out of our blobs
var blob = new Blob(chunks, {'type' : 'audio/ogg; codecs=opus'});
//then the rest of the process to save the file...
}

In the posted code I used ‘type’ : ‘audio/ogg; codecs=opus’ but I’ve tried with other options like ‘audio:wav’ but it doesn’t work.

So, is it a “normal” behavior or did I missed something ?
Another solution would be to keep the OGG file and then convert it to WAV. I also tried that using FFmpeg but this is another story/nightmare that I’ll develop in another post if this is the only solution I have.

Why is my ajax using jQuery’s call not coming through the right way?

Im making a darts timer system, Im using vue js voor de timer itself and for the addscore I also use VueJs And i’ve tried with php the ajax call for in the console while you can check when the the timer status is started pauzed or stopped. Ive tried several things but I cant fix the issue I assigned everything that I could think of, but for some reason in the POST isset it goes instant too the end even why I haven’t started yet. I need an extra eye with more experience in the field, because I cant see it.

Ill show my full code what I have so far with the filename above my code.

Darts-counter.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Darts Counter</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  <script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- Added jQuery library -->
  <style>
    .container {
      display: flex;
      justify-content: center;
    }

    .dart-counter {
      margin: 0 10px;
    }
  </style>
</head>

<body>
  <div class="container mt-5">
    <div>
      <h1>Darts Counter</h1>
    </div>
  </div>
  <div id="app" class="container mt-5">
    <div>
      <div>
        <countdown-timer></countdown-timer>
      </div>
    </div>
    <div class="dart-counter">
      <div>
        <dart-counter></dart-counter>
      </div>
    </div>
  </div>

  <script src="../js/darts.js"></script>
</body>

</html>    

darts.js

Vue.component('countdown-timer', {
    data() {
      return {
        totalTime: 100 * 60 * 60, // Total time in seconds (100 hours)
          currentTime: 100 * 60 * 60, // Current time in seconds (initialized with total time)
          timer: null,
          isPaused: true, // Set timer as paused by default
          isAdmin: true,
          scores: [],
          scoreInput: null,
          totalScore: 501, // Starting score for darts game
          savedGames: [], // Array to store saved game data
          actionToggle: false,
          action: "end",
          status: "",
          message: "",
          test: "",
          timeLeft: "",
        
      };
    },
    computed: {
      formatTime() {
        const hours = Math.floor(this.currentTime / 3600);
        const minutes = Math.floor((this.currentTime % 3600) / 60);
        const seconds = this.currentTime % 60;

        return `${this.padTime(hours)}:${this.padTime(minutes)}:${this.padTime(seconds)}`;
      },
    },
    methods: {
      startTimer() {
        this.timer = setInterval(() => {
          if (this.currentTime > 0 && !this.isPaused) {
            this.currentTime--;
          } else {
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);

        // Make AJAX call to start the timer
        this.sendTimerRequest();
      },
      toggleTimer() {
        this.isPaused = !this.isPaused;
      
        if (this.isPaused) {
          clearInterval(this.timer);
          this.timer = null;
        } else {
          this.startTimer();
        }
      
        this.actionToggle = !this.actionToggle;
        if (this.actionToggle) {
          this.action = "start";
        } else {
          this.action = "end";
        }  
        this.sendTimerRequest();
      },
      padTime(time) {
        return time.toString().padStart(2, '0');
      },
      
      sendTimerRequest() {
        $.ajax({
          url: "timer.php",
          type: "POST",
          data: { ajax: "1", 
                  data: JSON.stringify({ action: this.action }) },
          dataType: 'json',
          context: this,
          success: function(response) {
            if (response.status !== undefined) {
              this.status = response.status;
            }
            if (response.timeLeft !== undefined) {
              this.timeLeft = response.timeLeft;
            }
            if (response.test !== undefined) {
              this.test = response.text;
            }
            console.log(response);
          },
        }).fail(function () { 
          alert('error');
        });
      },
    },
    mounted() {
      this.startTimer();
    },
    template: `
      <div class="text-center mb-4">
        <p class="h2">{{ formatTime }}</p>
        <button class="btn btn-primary" @click="toggleTimer">{{ isPaused ? 'Resume' : 'Pause' }}</button>
      </div>
    `,
  });

  Vue.component('dart-counter', {
    data() {
      return {
        scores: [],
        scoreInput: null,
        totalScore: 501, // Starting score for darts game
        action: 'start',
      };
    },
    computed: {
      averageScore() {
        if (this.scores.length === 0) {
          return 0;
        }
        return (501 - this.totalScore) / this.scores.length; // Average remaining score per dart
      },
      isGameWon() {
        return this.totalScore === 0; // Check if remaining score is 0
      },
    },
    methods: {
      addScore() {
        if (this.scoreInput === null) {
          alert('Please enter a score.');
          return;
        }

        const score = parseInt(this.scoreInput);
        if (isNaN(score) || score < 0 || score > 180) {
          alert('Score must be between 0 and 180.');
          return;
        }

        if (this.totalScore - score < 0) {
          alert('Busted! You have exceeded the total score.');
          return;
        }

        this.scores.push(score);
        this.totalScore -= score;
        this.sendTimerRequest();

        // Reset the score input
        this.scoreInput = null;
      },
      removeScore(index) {
        const removedScore = this.scores.splice(index, 1)[0];
        this.totalScore += removedScore;
      },
      resetGame() {
        this.totalScore = 501;
        this.scores = [];
      },

      //Een AJAX-oproep met JSON-codering heeft als functie het verzenden en ontvangen van gegevens tussen een webpagina en een server.
      startTimer() {
        this.timer = setInterval(() => {
          if (this.currentTime > 0 && !this.isPaused) {
            this.currentTime--;
          } else {
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);

        // Make AJAX call to start the timer
        this.sendTimerRequest();
      },
    },
    template: `
      <div>
        <div>
          <input type="number" v-model="scoreInput" placeholder="Enter score" @keyup.enter="addScore">
          <button @click="addScore">Add Score</button>
        </div>
        <div>
          <p>Remaining Score: {{ totalScore }}</p>
          <p v-if="scores.length > 0">Average Remaining Score per Dart: {{ averageScore.toFixed(2) }}</p>
          <div v-for="(score, index) in scores" :key="index">
            <span>{{ score }}</span>
            <button @click="removeScore(index)">Remove</button>
          </div>
        </div>
        <button @click="resetGame">Reset Game</button>
        <p v-if="isGameWon" class="text-success">Congratulations! You won!</p>
      </div>
    `,
  });

  new Vue({
    el: '#app',
  });


timer.php

<?php




$ret = new stdClass(); 

class Timer   
{
    private $timeLeft; 
    private $startTime; 
    private $status; 

    public function __construct($startTime)
    {
        $timeLeftFile = "timeleft.txt";
        if (file_exists($timeLeftFile))
        {
            $this->timeLeft = (INT)file_get_contents($timeLeftFile);
        }
        else
        {
            $this->timeLeft = $startTime;
        }
        $statusFile = "timerstatus.txt";
        if (file_exists($statusFile))
        {
            $this->status = file_get_contents($statusFile);
        }
        else
        {
            $this->status = "stopped";
        }
    }

    private function saveTimeLeft($timeLeft)
    {
        $this->timeleft = $timeLeft;
        file_put_contents("timeleft.txt", $timeLeft);
        
    }

    public function reset()
    {
        $this->saveTimeLeft($this->startTime);
        $this->stop();
       
    }

    public function start()
    {
        $this->status = "running";
        $startTimeFile = "starttime.txt";
        file_put_contents($startTimeFile, time());
        
    }
    
    public function stop()
    {
        $this->status = "stopped";
        $startTimeFile = "starttime.txt";
        $startTime = (INT)file_get_contents($startTimeFile);

        $runningTime = time()-$startTime;
        $this->saveTimeLeft($this->timeLeft-$runningTime);
        
    }

    public function isRunning()
    {
        if($this->status == "running") 
        {
          return  true;
        }
        return false;
    }

    public function getTimeLeft()
    {
        if ($this->status == "running")
        {
            return $this->timeLeft-(time()-$this->startTime);
        }
        return $this->timeLeft;
    }
}

if (isset($_POST["ajax"]) && $_POST["ajax"] == "1")
{
    $json = $_POST["data"] ?? "{}";
    $data = json_decode($json);

    $timer = new Timer(100*60*60);

    if (isset($data->action) && $data->action == "start")
    {
        if (!$timer->isRunning() && ($timer->getTimeLeft() > 0))
        {
            $timer->start();
            $ret->status = "running";
            $ret->test = "little test";
            $ret->timeLeft = $timer->getTimeLeft();
            
        }
        else
        {
            $ret->message = "the timer is already started";
        }
    }

    if (isset($data->action) && $data->action == "end")
    {
        if ($timer->isRunning())
        {
            $timer->stop();
            $ret->status = "stopped";
            $ret->timeLeft = $timer->getTimeLeft();
        }
        else
        {
            $ret->message = "timer stopped!";
        }
    }
}
header("Content-type: application/json; charset=utf-8");
echo json_encode($ret);

How to send a file from react to laravel without using append

summary: i want to send a file from react to laravel and then save it in share point

what I’ve already done: I’ve already managed this process in another app using “append” from react and it was working

problem: I don’t want to use append ( const formData = new FormData();
) because “datas” is a large object with lots of nested values. I have also tried to add ‘append’ but I get an empty object when requesting axios. Without using append, i don’t got my file data in laravel.

my question: is it possible to send a file client to server without using append ( const formData = new FormData();
)?

For the form I use react with redux toolkit.
To send the datas to mongodb i use laravel

I know that append method allows you to add key-value pairs to the formData object and allows you to receive and process the files in laravel but do I have another option ?

This is my submit and axios request

    const onSubmit = (data) => {
    const datas = data.internOrders;
    dispatch(postInternOrder(datas, userData));
  };


    
    export const postInternOrder = (datas, userData) => async (dispatch) => {
      dispatch(setLoading(true)); 
      try {
        await axios({
          method: 'post',
          url: `${process.env.REACT_APP_API_URL}api/order/intern`,
          data: datas,
        }).then((res) => {
          console.log(res.data);
          dispatch(setOpen(true)); 
        });
      } catch (err) {
        console.log(err);
        dispatch(setError(true));
      }
      dispatch(setLoading(false));
    };

This is my create function in laravel

public function createInternOrder(Request $request)
{


    if ($request) {
        $driveId = env('DRIVE_ID');
        $driveUrl = env('DRIVE_URL');
        $drivePath = env('DRIVE_PATH');
        $clientId = env('CLIENT_ID');
        $clientSecret = env('CLIENT_SECRET');
        $files = $request->file('files');

        // Obtenir le jeton d'accès
        if ($files) {
            $responseToken = Http::asForm()->post(
                'https://login.microsoftonline.com/8289/oauth2/v2.0/token',
                [
                    'grant_type' => "client_credentials",
                    'client_id' => $clientId,
                    'client_secret' => $clientSecret,
                    'scope' => "https://graph.microsoft.com/.default",
                ]
            );

            $tokenJson = json_decode($responseToken->getBody()->getContents());
            $token = $tokenJson->access_token;


            $fileName = $files->getClientOriginalName();
            $response = Http::withToken($token)->withBody(
                $files->getContent(),
                $files->getMimeType()
            )->put($driveUrl . $driveId . $drivePath . $fileName . ':/content');

            $responseJson = json_decode($response->getBody()->getContents());
            $sharePointUrl = $responseJson->webUrl;
        

        } else {
            $fileName = '';
            $sharePointUrl = '';
        }
        $internOrders = InternOrders::create([
            'History' => $request->get('history'),
            'Urls' => $request->get('urls'),
            'Amount' => $request->get('amount'),
            'BusinessUnit' => $request->get('businessUnit'),
            'Comment' => $request->get('comment'),
            'DeliveryAdress' => $request->get('deliveryAdress'),
            'Entity' => $request->get('entity'),
            'Express' => $request->get('express'),
            'ExpressObject' => $request->get('expressObject'),
            'Object' => $request->get('object'),
            'Paiement' => $request->get('paiement'),
            'Referent' => $request->get('referent'),
            'Status' => $request->get('status'),
            'Type' => $request->get('type'),
            'UserMail' => $request->get('userMail'),
            'UserName' => $request->get('userName'),
            "IdSP" => $request->get("idSP"),
            "SPUrl" => $request->get("sharePointUrl")

        ]);
        if ($internOrders) {
            $internOrders->save();

            return ["result" => " Orders has been saved successfully"];
        } else {
            return ["result" => "failed to save"];
        }
    }
}

Here trying to add append :

 const onSubmit = (data) => {    
 const datas = data.internOrders;

      const formData = new FormData();
      formData.append('internOrders', datas) 
      formData.append('file', data.files);  
    
      dispatch(postInternOrder(formData, userData));
    };

but then, if I log the “$request” in laravel i got empty object (FormData {})

Select query doesn’t return the first row from the table [duplicate]

I have a two table joined by a certain order_id, it selects from table number 2 based on table 1. Its working but not selecting the first row of table 2 for example below its return id 6 and 7 leaving 5 whereas they share the same order_id
Table2 structure
enter image description here

Table 2 example

Here is the result
Query Result

Is it my code or its something esle i cant seem to figure out?
I am testing this on XAMPP
below is my php code

if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
}
$conn = $pdo->open();
try {
    $stmt = $conn->prepare("SELECT *, invoice_address.id as invaid, invoice.id as invid FROM invoice_address LEFT JOIN invoice ON invoice.order_id=invoice_address.invoice_no WHERE invoice_address.id= :id");
    $stmt->execute(['id' =>$id]);
} catch (Exception $e) {
    $_SESSION['error'] = '.......'.$e->getMessage();
}
    
foreach($stmt as $row){
    $output .= '<tr>
        <td>'.$row["item_name"].'</td>
        <td><small>'.$row["item_no"].'</small></td>
        <td>'.$row["qty"].'</td>
        <td>R '.$row["price"].'</td>
        <td>R '.$row["amount_total"].'</td>
    </tr>';
}
echo $output;

When I use this .htaccess code then it’s source URL is returning a 404, Why?

RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} ^name1=([^&]+)&name2=([^&]+)$
RewriteRule ^$ /%1-vs-%2? [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

When I use this .thaccess code then i get this type of link https://example.com/5paisa-vs-abhipra-capital but problem is when i get this url then it’s showing this error “The source URL is returning a 404” so, how to fix this error?

h the UPDATE request. How can you update a table if you don’t know the number of variables in advance

The bottom line is that the table has such a function , add and remove columns and therefore I do not know in advance how many columns

I need to update . And now I ran into a problem . Please explain, friends.

$value is an array that takes the values that we insert into the table. convert it to int and everything works

there is an array of $columnnames in which all the columns of the table are located

the $column variable takes a value from the $columnnames array

the query should have the column name instead of the $column variable

there may be some problem with types, but the $column variable has a string type.

if $column = ‘id’ then everything works

the code below does not work

$mysqli = new mysqli("localhost", "root", "root", "college");

      $table = 'astronom';
      $table = $mysqli->real_escape_string($table);
      $column =$columnnames[1]; 
      

      $value = (int)$value[1];
      
      $sql = mysqli_query($mysqli, "UPDATE `{$table}` 
      SET `{$column}` = $value
      WHERE `Студенческий`={$_GET['red_id']}   ");
       if ($sql) {
        echo '<p>Успешно!</p>';
      } else {
        echo '<p>Произошла ошибка: ' . mysqli_error($mysqli) . '</p>';
      }

There is no extension able to load the configuration for “sentry”

I have this error in my symfony 4 project :

There is no extension able to load the configuration for “sentry” (in C:SourceGitSentrytaxeapprentissageconfig/packages/sentry.yaml). Looked for namespace “sentry”, found “framework”, “doctrine”, “doctrine_migrations”, “maker”, “twig”, “monolog”, “web_profiler”, “security”, “doctrine_fixtures”, “sensio_framework_extra”, “swiftmailer”, “it_input_mask”, “captcha” in C:SourceGitSentrytaxeapprentissageconfig/packages/sentry.yaml (which is loaded in resource “C:SourceGitSentrytaxeapprentissageconfig/packages/sentry.yaml”).

Can you help me ?

I want to install sentry in my symfony 4 project. I have 2 environments, dev and prod.

React Native Post Request for a transactional Insert statement

Good day, please I created a page for payment when the payment is successful, all the Items the user purchased, which are the items in the cartItems should be sent to mySql data base. I am using PHP as my server.

The problem I encountered is that the I get try post the cartItems is said to be undefined and the when I echoed out cartItems I got null

Errors:

Array ( )
Warning: Undefined array key "cartItems" in C:xampphtdocsapiinsertOrders.php on line 14

Warning: Undefined variable $_cartItems in C:xampphtdocsapiinsertOrders.php on line 16
NULL
Warning: foreach() argument must be of type array|object, null given in C:xampphtdocsapiinsertOrders.php on line 23
Cart items inserted successfully!

so the items where not inserted

This is the Php code:

<?php
include 'connection.php';

// Prepare the SQL statement for inserting into orderProducts table
$insertOrderProductsStmt = $mysqli->prepare("INSERT INTO orders (userId, bookId, name, quantity, price) VALUES (?, ?, ?, ?,?)");

// $jsonPayload = file_get_contents('php://input');
// $data = json_decode($jsonPayload, true);

// Get the cart items from the request
print_r($_POST);
// if(isset($_POST['cartItems'])){

    $cartItems = $_POST['cartItems'];
   echo $cartItems;
  var_dump($_cartItems);
  
  // Start the transaction
  $mysqli->begin_transaction();
  
  try {
      // Iterate over each cart item and execute the insert statement
      foreach ($cartItems as $cartItem) {
          $userId = $cartItem['userId'];
          $bookId = $cartItem['bookId'];
          $name = $cartItem['name'];
          $quantity = $cartItem['quantity'];
          $price = $cartItem['quantity'] * $cartItem['price'];
  
          // Bind the parameters and execute the statement
          $insertOrderProductsStmt->bind_param("iisii", $userId, $bookId, $name, $quantity, $price);
          $insertOrderProductsStmt->execute();
      }
  
      // Commit the transaction
      $mysqli->commit();
  
      // Close the prepared statement
      $insertOrderProductsStmt->close();
  
      // Send a success response
      echo "Cart items inserted successfully!";
  } catch (Exception $e) {
      // Rollback the transaction if an error occurred
      $mysqli->rollback();
  
      // Close the prepared statement
      $insertOrderProductsStmt->close();
  
      // Send an error response
      echo "Error: " . $e->getMessage();
  }
  
  // Close the database mysqliection
  $mysqli->close();
// }
// else{
//     echo "an error occured";
// }

?>

This is my react native page :
the insertOrders is responsible for that and I called it in the onSuccess props of the Paystack component

import {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  TextInput,
  Alert,
} from "react-native";
import React, { useRef, useState } from "react";
import { cartTotalPriceSelector } from "../redux/selectors";
import { useDispatch, useSelector } from "react-redux";
import { color } from "react-native-reanimated";
import colors from "../config/colors";

import { clear } from "../redux/features/cart/cartSlice";

import { Paystack, paystackProps } from "react-native-paystack-webview";

const PaymentScreen = () => {
  // const isValidEmail = (email) => {
  //   const emailRegex = /^[^s@]+@[^s@]+.[^s@]+$/;
  //   return emailRegex.test(email);
  // };
  const paystackWebViewRef = useRef(paystackProps.PayStackRef);
  const totalPrice = useSelector(cartTotalPriceSelector);
  const userId = useSelector((state) => state.user.userId);
  const email = useSelector((state) => state.email.email);
  const cart = useSelector((state) => state.cart);
  const cartItems = cart.map((cartItem) => {
    return {
      userId: userId,
      bookId: cartItem.bookId,
      name: cartItem.name,
      quantity: cartItem.quantity,
      price: cartItem.price,
    };
  });

  console.log("myItem",{ cartItems });

  const insertOrders = () => {
    const url = "http://192.168.11.102:80/api/insertOrders.php"; // Replace with the actual URL of your PHP page
  
    const requestOptions = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ cartItems }),
    };
  
    console.log("Before fetch request"); // Debugging statement
  
    fetch(url, requestOptions)
      .then((response) => {
        console.log("Response received"); // Debugging statement
        return response.json();
      })
      .then((result) => {
        console.log("Result:", result); // Debugging statement
      })
      .catch((error) => {
        console.error("Error:", error);
      });
  };

  

  return (
    <View style={styles.container}>
      <Paystack
        paystackKey="*****************************************"
        billingEmail={email}
        amount={totalPrice}
        onCancel={(e) => {
          // handle response here
        }}
        onSuccess={(res) => {
          // handle response here
          Alert.alert("Payment successful");
          console.log("myItem",{ cartItems });
          insertOrders();
        }}
        ref={paystackWebViewRef}
      />
      <Image style={styles.image} source={require("../assets/payment.jpg")} />

      <View style={styles.totalContainer}>
        <Text style={styles.totalText}>₦{totalPrice}</Text>
        <TouchableOpacity
          style={styles.checkoutButton}
          onPress={() => paystackWebViewRef.current.startTransaction()}>
          <Text style={styles.checkoutButtonText}>Pay Now</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

export default PaymentScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  checkoutButton: {
    backgroundColor: colors.orange,
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 20,
    elevation: 3,
  },
  checkoutButtonText: {
    fontSize: 16,
    fontWeight: "bold",
    color: "#FFFFFF",
  },
  image: {
    width: 200,
    height: 200,
    resizeMode: "cover",
    marginRight: 10,
    borderRadius: 11,
  },
  totalContainer: {
    margin: 10,
    borderColor: colors.lightOrange,
    borderWidth: 3,
    borderRadius: 10,
    padding: 20,
    justifyContent: "center",
    alignItems: "center",
  },
  totalText: {
    fontSize: 18,
    fontWeight: "bold",
  },
  emailInput: {
    height: 40,
    width: "100%",
    borderColor: colors.lightOrange,
    borderWidth: 2,
    borderRadius: 5,
    paddingHorizontal: 10,
    marginTop: 10,
  },
  errorText: {
    color: "red",
    marginTop: 5,
  },
});

when I console.log("myItems", {cartItems}) I got these response

myItem {"cartItems": [{"bookId": 18, "name": "The diary of a nigerian christian girl", "price": "2000.00", "quantity": 5, "userId": 31}, {"bookId": 21, "name": "A Time to Love", "price": "1500.00", "quantity": 3, "userId": 31}]}

Warning: Trying to access array offset on value of type null in C:xampphtdocstestservice.php on line 41

stackoverflow. I encountered this error, when i try to access and retrieved the data back from the database. to show in the table. but, after i run i get this error. i really hope that i can a solution.

here is my service.php code

<?php
//sambung ke pangkalan data
require('config.php');
include('session.php');

$photographerID = $_SESSION['photographerID'];
$serviceID = $_SESSION['serviceID'];

//memastikan pengguna login terlebih dahulu
?>

<!--HTML Bermula-->
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<head>
<title>DETAILED SERVICE</title>

<br>
<center><h2 style="color: #00004d;">DETAILED SERVICE</h2>

<fieldset>
    
  <table width="auto" border="1"  class="imagetable">

 <?php
 
 $dataA=mysqli_query($conn,"select * from serviceadvertizing where serviceID='$serviceID'");
 $infoA=mysqli_fetch_array($dataA);
 ?>

<tr>
<td width="200" style="background-color: #FF8500; color: white; text-align: center; height: 50px;" ><b>Service ID </b></td>
  <td style="width: auto; padding-left: 5px; height: auto;"><?php echo $infoA['serviceID'];?></td>
</tr>

<tr>
<td width="200" style="background-color: #FF8500; color: white; text-align: center; height: 50px;" ><b>Photographer ID </b></td>
<td style="width: auto; padding-left: 5px; height: auto;"><?php echo $infoA['photographerID']; ?></td>
</tr>
 
 
</table>

</fieldset>

</body>
</html>

here is my session.php code:

session_start();

if(!isset($_SESSION["photographerID"]) && !isset($_SESSION["artworkID"]) && !isset($_SESSION["serviceID"]) && !isset($_SESSION["Course_ID"])){

echo "kjhfdfm,";

header("Location:index.php");
//exit();
}

i already tried many solution, but i did not found any. the service id is exist in the database but why still error ? or i have a problem in the php query ?

ErrorException Undefined variable $users [duplicate]

ErrorException
Undefined variable $users

So there is the code if you need other page of code tell me so i can provide it. I try to have a page with conversations but when i go on it i got this error undefined varaible $users

index.blade.php

@extends('layouts.app')


@section('content')

<div class="container">

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

@foreach($users as $user)

<div class="list-group">

    <a class="list-group-item" href="{{ route('conversations.show', $user->id )}}">{{$user->name}}</a>

</div>

@endforeach

</div>

</div>

@endsection

ConversationsController.php

<?php

namespace AppHttpControllers;

use AppHttpRequestsStoreMessageRequest;
use AppNotificationsMessageReceived;
use AppRepositoryConversationRepository;
use AppModelsUser;
use IlluminateAuthAuthManager;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;

class ConversationsController extends Controller
{

    /**
     * @var ConversationRepository
     */
    private $r;
    /**
     * @var AuthManager
     */
    private $auth;

    public function __construct(ConversationRepository $conversationRepository, AuthManager $auth)
    {
        $this->middleware('auth');
        $this->r = $conversationRepository;
        $this->auth = $auth;
    }

    public function index () {
        return view('conversations/index');
    }

    public function show (User $user) {
        $me = $this->auth->user();
        $messages = $this->r->getMessagesFor($me->id, $user->id)->paginate(50);
        $unread = $this->r->unreadCount($me->id);
        if (isset($unread[$user->id])) {
            $this->r->readAllFrom($user->id, $me->id);
            unset($unread[$user->id]);
        }
        return view('conversations/show', [
            'users' => $this->r->getConversations($me->id),
            'user' => $user,
            'messages' => $messages,
            'unread'=> $unread
        ]);
    }

    public function store (User $user, StoreMessageRequest $request) {
        $message = $this->r->createMessage(
            $request->get('content'),
            $this->auth->user()->id,
            $user->id
        );
        $user->notify(new MessageReceived($message));
        return redirect(route('conversations.show', ['id' => $user->id]));
    }

}

web.php

<?php

use IlluminateSupportFacadesRoute;


Route::get('/', function () {
    return view('welcome');
})->name('welcome');


Auth::routes();

Route::get('/home', [AppHttpControllersHomeController::class, 'index'])->name('home');

Auth::routes();

/* Ads Routes */

Route::get('/home', [AppHttpControllersHomeController::class, 'index'])->name('home');

Route::get('/annonces', [AppHttpControllersAdController::class,'index'])->name('ad.index');

Route::get('/annonce', [AppHttpControllersAdController::class,'create'])->name('ad.create');

Route::post('/annonce/create', [AppHttpControllersAdController::class,'store'])->name('ad.store');

Route::post('/search', [AppHttpControllersAdController::class,'search'])->name('ad.search');

/* Messages Routes */

Route::get('/message/{seller_id}/{ad_id}' ,[AppHttpControllersMessageController::class,'create'])->name('message.create');
Route::post('/message' ,[AppHttpControllersMessageController::class,'store'])->name('message.store');

/* Messagerie Routes */

Route::get('/messageries', [AppHttpControllersConversationsController::class, 'index'])->name('messageries');
Route::get('/conversations', [AppHttpControllersConversationsController::class, 'index'])->name('conversations');
Route::get('/conversations/{user}', [AppHttpControllersConversationsController::class, 'show'])->name('conversations.show');
Route::post('/conversations/{user}', [AppHttpControllersConversationsController::class, 'store']);

when i try to go on url/conversations i got this error. How can i solve this?
Where can the problem from controller routes or from the index page?

$_SESSION[XX] works but kills auto when redirect to index

We had a website created via WordPress by some devs years ago.
I have created a subdirectory to deploy another website to be used in-company. I have created website locally and everythiung works.
Problem is, When I login to subfolder website, I am able to login and succesfully session being created and I am seing it in console, but session kills automatically if I go to index of subfolder. I deleted redirecting codes from login page to not be directed to index. With this My Navbar shows items that supposed to be seen when logged in. BUT INDEX DOES NOT CARRY MY SESSION IN ANYWAY. Pastin codes below.
I tried many things that thought. at first I thought session not starting because login was not redirecting me to index with header(); then I used JS codes to see session and redirect. etc.
**
my nav.php**

<?php
/* error_reporting(E_ALL);
ini_set('display_errors', 1);
 */

if (!isset($_SESSION)) {
    session_start();
}
require "conn.php";

if (!isset($_SESSION['sesUser'])) {
    $_SESSION['sesUser'] = null;
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="" rel="stylesheet"
        integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
    <script src="" crossorigin="anonymous"></script>
    <!-- jQuery library -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
        <div class="container-fluid">

            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
                aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto mb-2 mb-md-0">
                    <li class="nav-item">
                        <a class="nav-link active" aria-current="page" href="index.php">Home</a>
                    </li>
<?php if (isset($_SESSION['sesUser'])) :?>


                        <li class="nav-item">
                            <a class="nav-link" aria-current="page" href="pricing.php?s=custList">Customers</a>
                        </li>

                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="" id="navbarDropdown" role="button"
                                data-bs-toggle="dropdown" aria-expanded="false">Pricing Sheets</a>
                            <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                                <li><a class="dropdown-item" href="pricing.php?s=kitchen">Kitchen Pricing</a></li>
                                <li><a class="dropdown-item" href="bathroom.php?s=kitchen">Bathroom Pricing</a></li>
                            </ul>
                        </li>
<?php endif;?>
                </ul>

                <ul class="navbar-nav navbar-right">
<?php if (!isset($_SESSION['sesUser'])) :?>
                        <li class="nav-item">
                            <a class="nav-link fa-regular fa-user" style="font-size: 20px; color: green;"
                                href="login.php">Login</a>
                        </li>
<?php else :?>
                        <li class="nav-item">
                            <a class="nav-link fa-regular fa-user" style="font-size: 20px; color: red;"
                                href="logout.php"><?php echo '  ' . $_SESSION['sesUser']?></a>
                        </li>
                        <li></li>
<?php endif;?>
                </ul>
            </div>
        </div>
    </nav>

    <script> console.log("<?php echo $_SESSION['sesUser']; ?>");
            console.log("<?php echo $_SESSION['sesRole']; ?>");</script>
</body>

</html>

my login.php

<?php
require "nav.php";
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">  
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">    
    
    <title>BSKB</title>

    <style>
        #btn {
            position: relative;
        }
    </style>
    <!-- jQuery library -->
    <script src=""></script>

    <!-- Latest compiled JavaScript -->
    <script src=""></script>

</head>
<body>

<div class="container">
<?php if (empty($_POST['username']) && empty($_POST['password'])) { ?>
        <div class="d-flex align-items-center justify-content-center" style="height: 80vh;">
            <form action="" method="post">
                <div class="form-group row ">
                    <div class="col-xm-5">
                        <label for="username">Username</label>
                        <input type="text" class="form-control" id="username" name="username" placeholder="Enter username." >
                    </div>
                </div>
                <div class="form-group row">
                    <div class="col-xm-3">
                        <label for="password">Password</label>
                        <input type="password" class="form-control" id="password" name="password" placeholder="Enter password.">
                    </div>
                </div>
                <div id="btn">
                    <button type="submit" class="btn btn-success mt-3 mb-3" id="button">Login</button>
                </div>
            </form>
        </div>
    </div>
<?php } else { 
        $loginsql = $db->prepare("SELECT * FROM user WHERE username=? AND password=?");
        $loginsql->execute(array($_POST['username'], $_POST['password']));
        $login = $loginsql->fetch(PDO::FETCH_ASSOC);
        
        $_SESSION['sesUser'] = $login['username'];
        $_SESSION['sesRole'] = $login['role'];
        ?>
<script>
    console.log("<?php echo $_SESSION['sesUser']; ?>");
    console.log("<?php echo $_SESSION['sesRole']; ?>");
/*     $(document).ready(function() {
        setTimeout(function() {
            window.location.href = "/pricing/index.php";
        }, 1000);
    }); */
</script>
<?php }?>

    <script src="" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
</body>
</html>

my index.php


<?php  require "nav.php";

?>


<!DOCTYPE html>
<html>
<head>
  
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BSKB</title>
    
    <link href="" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">    <!-- jQuery library -->
    <script src=""></script>
    
    <!-- Latest compiled JavaScript -->
    <script src=""></script>


<style>
body{
  height: 90vh;
}
.btn-secondary,
.btn-secondary:focus {
  color: #333;
  text-shadow: none; 

}
.btn-secondary:hover{

  transform: scale(1.2);
  transition: 0.3s;
  text-shadow: none;
  color: #333;
}

</style>    


<body class="bg-dark">



    <div class="d-flex h-100 text-center text-white">
        <div class="cover-container d-flex w-100 h-100 p-3 mx-auto flex-column mb-auto">
            <header class="mb-auto" style="background-color:red ;">
            
            </header>
            <main class="px-3">
                <h1>  </h1>
                <h2>PRICING SYSTEM</h2>
                <?php if(!isset($_SESSION['sesUser'])): ?>
                <p class="lead pt-5">
                    <a href="login.php" class="btn btn-lg btn-secondary fw-bold border-white bg-white">LOGIN</a>
                </p>
                <?php else: ?>
                <p class="lead pt-5">
                    <a href="pricing.php?s=custList" class="btn btn-lg btn-secondary fw-bold border-white bg-white">JOBS</a>
                </p>
                <?php endif; ?>
            </main>
            <footer class="mt-auto text-white-50">
                <p>Github <a href="" class="text-white">Portfolyo</a>, by <a href="#" class="text-white">Egemen Aydin</a>.</p>
            </footer>
        </div>
    </div>

    <script src="" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
</body>
</head>
</html>

index.php shows only welcome page. Main page is my pricing.php but I can acces there via link. Session works in there.

Find range of most profit from array of net profit programing question

I got the following interview question :
“Given an array of integers which represents net profits of a company, find the range of consecutive months that had the most profit”

I simply dont understand it. I am aware of wat an array of integers is, of what a range of elements is. I dont understand the question.

I tried to read the question but I did’nt understand it.