PHPUnit – test query func

I have part of the php code I am writing test for:

$_image_file = db_get_field('SELECT image_path FROM ?:images WHERE image_id = ?i', $image_id);

When duping it, it return: image_1.jpg

And I want to write it in PHPUnit test:

FunctionMocker::replace('db_get_field', function () {
        return FnImagesFunctionsTest::$functions->db_get_field();


Which is okay, but I want to call it with sql call as I have multiple db_get_field methods with different sql queries.

So, like ->withArgs('SELCET ...', $image_id = 190)

Can someone please help, I am new with PHPUnit tests..


Create an appointment in Zimbra calendar using IMAP PHP library

I would like to create an appointment in my Zimbra calendar using IMAP. The final goal would be to create a cron job that doing it recurrently but for the moment I only managed to connect to the server and now I’m stuck here :

    $server_host = '{zimbra:7143/imap/novalidate-cert}';
    $server_username = '[email protected]';
    $server_password = 'mypassword';
    $imap = imap_open($server_host, $server_username, $server_password);
    if ($imap) 
        //create an appointment


I’ve searched through the whole internet there is no IMAP function in PHP to do that, I’ve only found out some Zimbra API on git which could do this but I need to use IMAP.

submit form dependent dropdown to a table and show in the table the name instead of id issue

Hello stackoverflow community, i have a doubt on how to do this:
-im making a country city state like , dependent dropdown, and im trying to insert into a table in database the form submission.. i’m having an issue on how to submit into the table, the country_name. i have the following in the php form (alredy submitting the id’s instead of names of the countries:

<form method="POST" action="">
<div class="form-group">
<label for="distrito">Distrito</label>
<select class="form-control" name="distrito" id="distrito_name">
<option value="">Seleccione o distrito</option>
require_once "db.php";
$result = mysqli_query($conn,"SELECT * FROM distrito");
while($row = mysqli_fetch_array($result)) {
<option value="<?php echo $row['id'];?>"><?php echo $row["distrito_name"];?></option>
<div class="form-group">
<label for="concelho">Seleccione o concelho</label>
<select class="form-control" name="concelho" id="concelho_name">
<div class="form-group">
<label for="freguesia">Freguesia</label>
<select class="form-control" name="freguesia" id="freguesia_name">
$(document).ready(function() {
$('#distrito_name').on('change', function() {
var distrito_id = this.value;
url: "concelho-by-distrito.php",
type: "POST",
data: {
distrito_id: distrito_id
cache: false,
success: function(result){
$('#freguesia_name').html('<option value="">Seleccione o concelho primeiro</option>'); 
$('#concelho_name').on('change', function() {
var concelho_id = this.value;
url: "freguesia-by-concelho.php",
type: "POST",
data: {
concelho_id: concelho_id
cache: false,
success: function(result){
<button type="submit" name="submit" class="btn btn-primary">Save Event</button>

and i have the following in the data submission code wich is in a separate page: the connection to the database and this:

  if (isset($_REQUEST['distrito_id'])) {
    $i=implode(',', $_REQUEST['distrito_id']);
      $query = "SELECT distrito_name FROM distrito where id IN ($i)";
$result = $db_name->query($query);
if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo $row["distrito_name"]."<br>";
} else {
  echo "0 results";

$distrito = $_POST['distrito']; 
$query = "INSERT INTO table (distrito) VALUES '$distrito' 
$query_run = mysqli_query($con, $query);

if someone can, please help me make this, thanks in advance

Can’t attach an EventlLstener to a form in jquery/php

I stuck with a problem for almost one week now.
I’m working on a website that allow people to check the availability of vehicle spare parts and order them if available.
for that, the user has to select the make then the model, then the year and submit the request, the application tells whenever it’s available or not and displays the form for preordering.
Until here nothing special.
i use method to send elements to a backend.php file and to generate the form regarding those elements without refreshing the page.
Every thing work fine except for my last form, I’m not able to add an eventlistener (onSubmit) …
Could someone help please !!
Here’s my code:

  1. jquery
$(".form").on("submit", function(e) {
                var marque = $("#marque").val();
                var model = $("#model").val();
                var year = $("#year").val();
                if (typeof year != "undefined") {
                    year = year;
                } else {
                    year = "0";

                $.post("backEnd.php", {
                    "references": [marque, model, year]
                }, function(data5) {
                        scrollTop: $(".result").offset().top
                    }, 'slow')

            $("#mail_form").on("submit", function(e) {
  1. backend.php
if (isset($_POST["references"])) {
    $marque = $_POST["references"][0];
    $model = $_POST["references"][1];
    $year = $_POST["references"][2];

    $req = $connexion->prepare("SELECT * FROM suspension WHERE marque = ? AND model = ? AND year_range = ?");
    $req->execute(array($marque, $model, $year));
    $results = $req->fetchAll();

    $front = $results[0]["front"] + $results[0]["both_sides"];
    $rear = $results[0]["rear"] + $results[0]["both_sides"];
    $modelYear = ($year != "0") ? " - modèle " . $year : "";

    $message1 = ($front > 0) ? "<span>Disponibles</span>" : "Non disponible";
    $message2 = ($rear > 0) ? "<span>Disponibles</span>" : "Non disponible";
    <h2 class="main_result_title"><?php echo $marque . " - " . $model . $modelYear . " :"; ?></h2>
    <h3 class="main_result_subtitle"><?php echo "Amortisseurs Avants : " . $message1; ?></h3>
    <h3 class="main_result_subtitle"><?php echo "Amortisseurs Arrières : " . $message2; ?></h3>

    <p class="main_result_text">Vos amortisseurs sont disponibles chez <span>Algérie Pièces</span>, pour avoir plus de détails ou pour une précommande, utilisez le formulaire de contact ci-dessous pour nous contacter, un agent commercial prendra attache avec vous très rapidement pour vous prendre en charge</p>

    <div class="form2">
        <form action="" method="post" id="mail_form">
            <input type="text" name="id" id="ref" value="<?= $results[0]['id']; ?>" hidden="true">

            <label for="user_name">Vos noms et prénoms <small style="font-style: italic">(obligatoire)</small>
                : </label><input type="text" name="user_name" id="user_name" placeholder="Nom et prénom" required><br />

            <label for="user_mail">Votre Adresse mail : </label><input type="email" inputmode="email" name="user_mail" id="user_mail" placeholder="Adresse mail"><br />

            <label for="user_tel">Votre numéro de téléphone : </label><input type="tel" name="user_tel" id="user_tel" placeholder="Numéro de téléphone" inputmode="tel"><br />

            <label for="user_msg">Message <small style="font-style: italic">(facultatif)</small> :
            </label><textarea name="user_msg" id="user_msg" cols="30" rows="10" placeholder="Remarque ou besoin d'informations supplémentaires"></textarea><br />

            <div class="buttons2" style="text-align: right">
                <input type="submit" value="Envoyer" class="btn2" />
                <input type="reset" value="Effacer" class="btn2" />
        <div class="state_message"></div>


the function works fine, everything is ok except the last eventlistener

Multitenant View bookings for external users

I can only seem to view bookings for users in my group.

When I try create an access token for a user external with a Microsoft account, I can’t access it using “users/[email protected]” but when I change it back to “users/[email protected]” it starts working?

I have enabled multitenant in settings. Is the problem with the token?

How I generate token

 $token = json_decode($guzzle->post($url, [
        'form_params' => [
            'scope' => '',
            'client_id' => '####################',
            'client_secret' => '###################',
            'grant_type' => 'client_credentials',

press + to active input text label field in form

i have normal form like this :

<form class='modal-content animate' action='' method='post'>

Goods name : <input type='text' name='goods-name' style='width:100%; height: 40px; ' autocomplete='off'> <br>

Goods count : <input type='text' name='goods-count' style='width:100%; height: 40px; ' autocomplete='off'>


i need : – if i press key (+) any where on page active the label of goods name to write . thanx

Sql list unregistered classroom

There is one student. This student is enrolling in classes. What I want is to list the classes where this student is not registered. My SQL query is like this, where am I going wrong?

SELECT * FROM class, userClass WHERE <> userClass.class AND userClass.user<>$userid

Not being able to get data from an API in Javascript

I wrote an API that has manages a database, and that on get requests it has to send a JSON file with the data from the database. Also, from the frontend I want to call this API using fetch(), but I get a null response. What should I do?

The api code:

    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json');
    include_once '../Model/database.php';
    include_once '../Model/verifiedEvents.php';

    $db = new database();
    $event = new verifiedEvents();

    $result = $event->read();
    $count = $result->num_rows; 
    if ($count > 0){
        $outputArray = array();
        while($row = $result->fetch_assoc()){
            array_push($outputArray, $row);
        echo json_encode($outputArray);
    } else {
        echo json_encode(
          array('message' => 'No events found')


The clientside Javascript code:

const events_api_url = 'http://localhost/Proiect/API/getVerifiedEvents.php';
            const user_locations_api_url = 'http://localhost/Proiect/API/getUserLocations.php';
            async function getEvents(){
                const response = await fetch(events_api_url, {method: 'GET', mode: 'cors', cache: 'default', headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'}});
                const data = await response.json;
                const {description, title, longitude, latitude} = data;
                console.log(" ");

PHP giving specific item access to admins

So I have this food ordering system where each admin uploads his or her food from the backend and users can browse through those food from the frontend, a simple program. But what I want is that an admin should not be able to view or update the food from another admin as right now any of the admins can view and update all the food that are uploaded on the backend. What I want is only a specific admin only viewing and updating his or her added food items.
Attached below is the snippet and picture of the food view and update page where it displays all foods and can update them.
FYI the code is in PHP and the backend is SQL in phpMyAdmin
Please do let me if there are any confusions in my explanation.

<?php include('partials/menu.php'); ?>

<div class="main-content">
    <div class="wrapper">
        <h1>Manage Food</h1>

        <br /><br />

                <!-- Button to Add Admin -->
                <a href="<?php echo SITEURL; ?>admin/add-food.php" class="btn-primary">Add Food</a>

                <br /><br /><br />

                        echo $_SESSION['add'];

                        echo $_SESSION['delete'];

                        echo $_SESSION['upload'];

                        echo $_SESSION['unauthorize'];

                        echo $_SESSION['update'];

                <table class="tbl-full">

                        //Create a SQL Query to Get all the Food
                        $sql = "SELECT * FROM tbl_food";

                        //Execute the qUery
                        $res = mysqli_query($conn, $sql);

                        //Count Rows to check whether we have foods or not
                        $count = mysqli_num_rows($res);

                        //Create Serial Number VAriable and Set Default VAlue as 1

                            //We have food in Database
                            //Get the Foods from Database and Display
                                //get the values from individual columns
                                $id = $row['id'];
                                $title = $row['title'];
                                $price = $row['price'];
                                $image_name = $row['image_name'];
                                $featured = $row['featured'];
                                $active = $row['active'];

                                    <td><?php echo $sn++; ?>. </td>
                                    <td><?php echo $title; ?></td>
                                    <td>$<?php echo $price; ?></td>
                                            //CHeck whether we have image or not
                                                //WE do not have image, DIslpay Error Message
                                                echo "<div class='error'>Image not Added.</div>";
                                                //WE Have Image, Display Image
                                                <img src="<?php echo SITEURL; ?>images/food/<?php echo $image_name; ?>" width="100px">
                                    <td><?php echo $featured; ?></td>
                                    <td><?php echo $active; ?></td>
                                        <a href="<?php echo SITEURL; ?>admin/update-food.php?id=<?php echo $id; ?>" class="btn-secondary">Update Food</a>
                                        <a href="<?php echo SITEURL; ?>admin/delete-food.php?id=<?php echo $id; ?>&image_name=<?php echo $image_name; ?>" class="btn-danger">Delete Food</a>

                            //Food not Added in Database
                            echo "<tr> <td colspan='7' class='error'> Food not Added Yet. </td> </tr>";



<?php include('partials/footer.php'); ?>

Attached is a picture of this

How to fix error: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

Yes. I read about this error a lot of info. Nothing helps me.
My server Ubuntu with Apache2, PHP.
My website has to start a video from But I get an error
“Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true”

I updated .htaccess:
Header set Access-Control-Allow-Origin ""

Same error.

Header set Access-Control-Allow-Origin ""

Same error.

Header set Access-Control-Allow-Origin ""

Same error.

Header add Access-Control-Allow-Origin ""

Same error.

Header add Access-Control-Allow-Origin ""

Header set Access-Control-Allow-Credentials true

Same error.

SetEnvIf Origin "http(s)?://(.+.)?{1,5})?$" CRS=$0

Header always set Access-Control-Allow-Origin "%{CRS}e" env=CRS

Header merge Vary "Origin"

Same error.

Apache2 has enabled .htaccess.
headers enabled.

In PHP added

Same error.

Added these settings to apache Virtual Directory, restarted Apache2 – same error.

enter image description here

I don’t know what to do. How I can fix this error?

Uncaught TypeError: Cannot set properties of undefined (setting ‘innerHTML’)

I am trying to create a web page using php that, on the elements of class “continut-text-box” (a defined by my class), on click has to launch a Javascript function that should change the contents of another element of id “harta-modal”, but this does not happen. I keep getting the same error and that is “Uncaught TypeError: Cannot set properties of undefined (setting ‘innerHTML’)”, even though the function is declared after the element that it is supposed to change, and the console log that I wrote in the function does not return null.
What did I do wrong?

    if (!isset($_SESSION['username']) && !isset($_SESSION['password'])){
        echo "<script>location.href='loginPage.html'</script>";
<!DOCTYPE html>
<html lang="en"> 
    <title>Crisis Containment Service</title>
    <link rel="icon" href="">
    <link href="style1.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
    <h1 id="titlu-pagina">Crisis Containment Service Web App</h1>
    <div id="slider">
            <img src="Images/wildfire.jpg">
            <img src="Images/furtuna.jpg">
            <img src="Images/hurricane.jpg">
            <img src="Images/landslide.jpg">
            <img src="Images/tornada.jpg">
            <img src="Images/vulcan.jpg">
            <img src="Images/inundatie.jpeg">
            <img src="Images/wildfire.jpg">

    <div id="text-box">
            $url = 'http://localhost/Proiect/API/getVerifiedEvents.php';

            $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

            $headers = array("Accept: application/json",);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            $resp = curl_exec($curl);

            $json = json_decode($resp);

            $i = 0;

            while($i < sizeof($json)){
                //if (substr($json[$i]->name, 0, 5) == date("m-d")){
            <div class="continut-text-box" id="open" onclick="makeMap(<?php echo $json[$i]->longitude?>, <?php echo $json[$i]->latitude?>)"><h2><?php echo $json[$i]->description;?></h2></div>
        <?php /*}*/$i = $i + 1;}?>

    <div class="modal-container" id="modal-container">
        <div class="modal">
            <div id="harta-modal"><p>te rog functioneaza<!--to be generated by javascript!--></div>
        <button id="close">X</button>

    <iframe id="harta-europa" src="!1m18!1m12!1m3!1d47139330.24912588!2d-12.8611109417314!3d43.85258716626324!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x46ed8886cfadda85%3A0x72ef99e6b3fcf079!2sEurope!5e0!3m2!1sen!2sro!4v1649962131724!5m2!1sen!2sro" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>
    <button id="buton-about" onclick="window.location.href='about.html';">About</button>
    <button id="buton1" onclick="myFunction1()">Log Out</button>
    <button id="buton2" onclick="myFunction2()">Report Event</button>

    <select id="type-event">
        <option selected>All</option>
        <option>Volcanic erruptions</option>
        <option>Sink holes</option>

      <input type="datetime-local" name="datetime" id="datetime">
    <script src="myScript.js"></script>
            function myFunction1() {
            function myFunction2() {
            function makeMap(longitude, latitude){
                document.getElementById('harta-modal')[0].innerHTML = `${longitude} ${latitude}`;

How to create default value for OneToOne field using symfony

I currently have a user entity that contains multiple values as first_name and last_name for example.

I want to add a OneToOne relation user_informations to my user that will contains a bio field. (Note that I don’t want to add the bio field directly into the user entity )

I have created the entity using the command php bin/console make:entity userInformation

php bin/console make:entity UserInformation

 created: src/Entity/UserInformation.php
 created: src/Repository/UserInformationRepository.php

Then, i have created the OneToOne relation with the User entity

 New property name (press <return> to stop adding fields):
 > user

 Field type (enter ? to see all types) [string]:
 > relation

 What class should this entity be related to?:
 > User

 Relation type? [ManyToOne, OneToMany, ManyToMany, OneToOne]:
 > OneToOne
 Is the UserInformation.user property allowed to be null (nullable)? (yes/no) [yes]:
 > no

And finally, I added the bio field into the user_information

 Add another property? Enter the property name (or press <return> to stop adding fields):
 > bio

 Field type (enter ? to see all types) [string]:

 Field length [255]:

 Can this field be null in the database (nullable) (yes/no) [no]:
 > yes

 updated: src/Entity/UserInformation.php

The problem

the problem is that all my user currently have a null value for the user_information.

I would like to add an empty user_information for all my user but I have no idea about how to do this.

I know I could write some script to create a user_information for each user but there might be something else

How do I update column values to equal column values based on another column?

I have a sql table like this,

| name  | start | end |
| Joe   |    14 |   - |
| Joe   |    13 |   - |
| Steve |    11 |   - |
| Steve |    15 |   - |
| Bruce |    10 |   - |

and i want to update the values for column “end” with the values from “start” for each unique column value “name”, so it looks like this.

| name  | start | end |
| Joe   |    14 |  14 |
| Joe   |    13 |  13 |
| Steve |    11 |  11 |
| Steve |    15 |  15 |
| Bruce |    10 |  10 |

my question is: how do i do this in SQL code, and how would it look like with a PHP mysql query?

Enable dl in PHP 8.0

I’ve been trying to enable the PHP 8.0 dl function but I couldn’t succeed, as you see in the screenshot below


but when trying to load an extension

error message

I also know about

refsect1-function.dl changelog

So is there anyway to re-enable this function !

Bulk import of student scores

I have a web app that I had someone do a bit of customization on. It was to create bulk import of scores of students.
As at the time, the students only have exam scores (i.e just one column for scores).

std_id | scores

  101  |  80

However, the students now have a myriad of test scores and an exam scores.

std_id | ca1 | ca2 |ca3 | ca4 | exam

  101  | 7   |  8  | 4  | 8   | 45

Well, I figured it should be easy enough to look through his code and see how I could work on it to allow for bulk import of the new tests columns.

However, I got stuck trying to figure how the value for marks is gotten.

Here is the original code:


 public function uploadfile()

        $this->form_validation->set_error_delimiters('', '');
        $this->form_validation->set_rules('file', $this->lang->line('image'), 'callback_handle_upload');
        if ($this->form_validation->run() == false) {
            $data = array(
                'file' => form_error('file'),
            $array = array('status' => 0, 'error' => $data);
            echo json_encode($array);
        } else {
            $return_array = array();
            if (isset($_FILES["file"]) && !empty($_FILES['file']['name'])) {

                $fileName = $_FILES["file"]["tmp_name"];
                if (isset($_FILES["file"]) && !empty($_FILES['file']['name']) && $_FILES["file"]["size"] > 0) {

                    $file = fopen($fileName, "r");
                    $flag = true;
                    while (($column = fgetcsv($file, 10000, ",")) !== false) {
                        if ($flag) {
                            $flag = false;
                        if (trim($column['0']) != "" && trim($column['1']) != "" && trim($column['2']) != "") {
                            $return_array[] = json_encode(
                                    'adm_no'     => $column['0'],
                                    'attendence' => $column['1'],
                                    'marks'      => number_format($column['2'], 2, '.', ''), <!-- Where is this gotten from?-->
                                    'note'       => $this->encoding_lib->toUTF8($column['3']),

                $array = array('status' => '1', 'error' => '', 'student_marks' => $return_array);
                echo json_encode($array);


                            if (empty($resultlist)) {
                                    <td colspan="7" class="text-danger text-center"><?php echo $this->lang->line('no_record_found'); ?></td>
                            } else {

                                foreach ($resultlist as $student) {
                                    <tr class="std_adm_<?php echo $student['admission_no']; ?>">
                              <td><?php echo $student['admission_no']; ?></td>
                              <td style="white-space: nowrap;"><?php echo $student['firstname'] . " " . $student['lastname']; ?></td>
                                        foreach ($attendence_exam as $attendence_key => $attendence_value) {
                                            $chk = ($student['exam_group_exam_result_attendance'] == $attendence_value) ? "checked='checked'" : "";
                                            <label class="checkbox-inline"><input type="checkbox" class="attendance_chk" name="exam_group_student_attendance_<?php echo $student['exam_group_class_batch_exam_students_id']; ?>" value="<?php echo $attendence_value; ?>" <?php echo $chk; ?>><?php echo $this->lang->line($attendence_value); ?></label>

                                <td> <input type="number" class="marksssss form-control" name="exam_group_student_mark_<?php echo $student['exam_group_class_batch_exam_students_id']; ?>" value="<?php echo $student['exam_group_exam_result_get_marks']; ?>" step="any"></td>
                                <td> <input type="text" class="form-control note" name="exam_group_student_note_<?php echo $student['exam_group_class_batch_exam_students_id']; ?>" value="<?php echo $student['exam_group_exam_result_note']; ?>"></td>



<script type="text/javascript">
    $(document).ready(function () {
        $(document).on('click', "#btnSubmit", function (event) {

            //stop submit the form, we will post it manually.
            var file_data = $('#my-file-selector').prop('files')[0];
            var form_data = new FormData();
            form_data.append('file', file_data);

                url: baseurl + "/admin/examgroup/uploadfile",
                type: 'POST',
                dataType: 'JSON',
                data: form_data,
               contentType: false,
cache: false,
 beforeSend: function () {

                    $('#examfade,#exammodal').css({'display': 'block'});
                success: function (data) {
  if (data.status == "0") {
           var message = "";
          $.each(data.error, function (index, value) {
            message += value;
       } else {
           var arr = [];
                    $.each(data.student_marks, function (index) {
                        var s = JSON.parse(data.student_marks[index]);
                            adm_no: s.adm_no,
                            attendence: s.attendence,
                            marks: s.marks,
                            note: s.note

                    $.each(arr, function (index, value) {
                         var row=$('.marksEntryForm').find('table tbody').find('tr.std_adm_' + value.adm_no);
                       row.find("td input.marksssss").val(value.marks);
                       row.find("td input.note").val(value.note);
                       if(value.attendence == 1){
                         row.find("td input.attendance_chk").prop( "checked", true );
                         row.find("td input.attendance_chk").prop( "checked", false);

            error: function (xhr) { // if error occured
                alert("Error occured.please try again");
                    $('#examfade,#exammodal').css({'display': 'none'});
            complete: function () {
                    $('#examfade,#exammodal').css({'display': 'none'});


This is what the bulk import file looks like:

   A     |     B     |     C     | D
adm_no   |  status   |    marks  | note

Now, I want the file to be like this:

   A     |     B     |    C   |  D   |  E   |  F   |  G  |  H |
adm_no   |  status   |   ca1  | ca2  |  ca3 | ca4  |exam | note