I have a code that does not work after PHP update, can someone help me update? [closed]

I have a code that does not work after PHP update, can someone help me update? I an not a programmer, and used a lot of time to make this code the first time. I have tried to change coding according to new standards SQLi, but I cannot get it to work.
The code below is the original.

{
            var data1 = google.visualization.arrayToDataTable(
                    [
                          ['date','Outdoor'],
                          <?php
    
    
                          // select average readings      select * from readings where year(date) = 2015 
                          $result = mysql_query("SELECT DATE_FORMAT( date  , '%d.%c.%y %H:%i') AS Time1, AVG( out_temp ) AS out_temp FROM $table WHERE TIMESTAMPDIFF(HOUR,date, now()) < $hours GROUP BY ROUND( UNIX_TIMESTAMP( date ) DIV ($avg*3600) ) ");
                          if ($result !== false) 
    
                          {
                                   $num=mysql_numrows($result);
                                   $i=0;
                                   while ($i < $num) 
    
                                   {
                                    $time=mysql_result($result,$i,"Time1");
                                    $out_temp=mysql_result($result,$i,"out_temp");
    
                                    echo "['";
                                    echo "$time";
                                    echo "',";
                                    echo "$out_temp";
                                    echo "]";
                                    if ($i < ($num - 1)){
                                     echo ",";
                                    }
                                    $i++;
                                   }
    
                          }
    
                          ?>
                    ]);
    
    
            var options1 =  
            {
                  title: 'Temperatures',
                  curveType: 'function',
                  legend: {position: 'bottom'},
    
                  animation:{duration: 1000,easing: 'in',startup: true},
    
                  vAxis: {viewWindowMode:'explicit',viewWindow: {max:35,min:-10} }
            };
    
    
    
    
            var chartA = new google.visualization.LineChart(document.getElementById('chart_div'));
            chartA.draw(data1, o

ptions1);

Odd PHP cURL proxy behavior

I’m trying to request Keycloak container from another container within the same network using PHP curl with proxy. The Keycloak’s service name is keycloak and its exposed port is 8080.

Here is my code:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://localhost:10210/realms/test/.well-known/openid-configuration");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, "keycloak:8080");

$response = curl_exec($ch);

curl_close($ch);

When I execute this code I receive this error message:

{"error":"RESTEASY003210: Could not find resource for full path: http://localhost:10210http://localhost:10210/realms/test/.well-known/openid-configuration"}

It looks like it duplicates the hostname when I use proxy option and I have no idea why it happens.

Woocommerce – Remove Only one Unit of a product from cart

I am working on this woocommerce search function that uses AJAX to fetch products on every keystroke and that gives the possibility to add or remove units of a certain product to cart right from the instant search results modal.

In each search result there is this group of two buttons that allow the client to add 1 or remove 1 product from cart at a time. I managed to make the add to cart button work but can’t seem to find a good solution to remove just one single unit from cart instead of all of them at once.

enter image description here

I have tried this:

function remove_product_from_cart_programmatically() {
   if ( is_admin() ) return;
   $product_id = 282;
   $product_cart_id = WC()->cart->generate_cart_id( $product_id );
   $cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
   if ( $cart_item_key ) WC()->cart->remove_cart_item( $cart_item_key );
}

but it removes all products with that ID at once.

I want to be able to remove unit by unit in case there are items in cart with that ID.

This is the code I have right now for the remove from cart button:

add_action('wp_ajax_search_remove_from_cart', 'search_remove_from_cart');
add_action('wp_ajax_nopriv_search_remove_from_cart', 'search_remove_from_cart');

// handle the ajax request
function search_remove_from_cart()
{
    $product_id = $_REQUEST['product_id'];
    WC()->cart->remove_cart_item($product_id);

    $products_in_cart = WC()->cart->get_cart_item_quantities($product_id);
    $updated_qty = $products_in_cart[$product_id];

    // in the end, returns success json data
    wp_send_json_success(["Product removed from cart Successfuly!", $updated_qty]);

    // or, on error, return error json data
    wp_send_json_error(["Could not remove the product from cart"]);
}

Is there any function to remove only one unit of a certain product from cart?

Thank you all !

getting child of child in eloquent relations

I’m new to laravel relations and eloquent and I have the following three models and I want to get the num_rooms by using a reservation object inside my blade view which , I tried the below code but it didn’t work and I got an error :

“Trying to get property ‘rtypes’ of non-object”

how can I achieve this ?? and thank you in advance

@foreach($reservations as $reservation)

           <p>{{$reservation->rdates->first()->rtypes->first()->num_rooms}}</p><br>

@endforeach

Reservation model:

    <?php


    namespace AppModels;

    use IlluminateDatabaseEloquentModel;

class Reservation extends Model
{
    protected $table = 'reservations';


    protected $dates = [
        'canceled_at'
    ];

    protected $fillable = [
        'canceled_at',
        'created_by',
        'updated_by'
    ];
  

    public function rdates(){
        return $this->hasMany('AppModelsRDate','reservation_id','id');
    }
   }

rdate model:

<?php


namespace AppModels;

use IlluminateDatabaseEloquentModel;


class RDate extends Model
{
    protected $table = 'r_dates';

    protected $casts = [
        'reservation_id' => 'int'
    ];

    protected $dates = [
        'date'
    ];

    protected $fillable = [
        'reservation_id',
        'date',
        'created_by',
        'updated_by'
    ];

    public function rtypes(){
        return $this->hasMany('AppModelsRtype','r_date_id','id');
    }

    public function reservations(){
        return $this->belongsTo('AppModelsReservation','reservation_id','id');
    }

}

and finally rtype model:

<?php

namespace AppModels;

use IlluminateDatabaseEloquentModel;

class Rtype extends Model
{
    
    protected $table = 'r_types';
    protected $casts = [
        'r_date_id' => 'int',
        'num_rooms' => 'int'
    ];

    protected $fillable = [
        'r_date_id',
        'num_rooms',
        'created_by',
        'updated_by'
    ];


    public function rdates(){

        return $this->belongsTo('AppModelsRDate','r_date_id','id');
    }
}

Web is slow to load video when i use nginx to deploy

i use nginx to deploy some projects together,when i use a domain name to enter one of the web page ,the page is slow to load video(eg:www.xxxxxx.com).but when i use domain name + port or ip+port to enter,the speed is normal(eg:wwww.xx.com:9023,xx.xx.xx.xx:9023).
here is part of my nginx configuration.(some project is deploy with nginx in a same machine,but some projects are other machine, and all projects are coding in different languages. that means there is no link between the projects)

server
    {
        listen 80;
        server_name xxx1.com;
        proxy_http_version  1.1;
        location / {
            proxy_set_header Host $Host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://127.0.0.1:9025/;
            proxy_redirect http://127.0.0.1:9025/ ;
        }
    }
    server{
        listen 80;
        server_name www.xxx2.com;
        proxy_http_version  1.1;
        location / {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP    $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://www.xxx2.com.com:9023; # Reverse proxy to port 9023

        }
    }

    server{
        listen 80;
        server_name xxx3.com;
        proxy_http_version  1.1;
        location / {
            proxy_set_header Host $host;
                    proxy_set_header X-Real-IP    $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
                    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://xxx3.com:9024; # Reverse proxy to port 9024


2 methods tried

1.i hava try to add proxy_buffer under “location”.

proxy_buffer_size 128000k; 
proxy_buffers 32 128000k; 
proxy_busy_buffers_size 128000k;

2.add worker_connections.

worker_connections 10240;
  1. change proxy_pass to ip
proxy_pass http://39.170.xx.xx:9023

but it all doesnt work

i dont know what i should add to nginx or my method that use nginx to do routing distribution is error. because i only have one public network ip and many place hava to use 80,i have to use nginx to do routing distribution.

WordPress website is opening extremely slow

So, i have a client that i’m working for this is his website. so this website is extremely slow as you can see below:
Website test
full page

i tried

  • reducing image sizes
  • used optimising plugins
  • removing unused plugins
  • deleting extra themes
  • started removing things from homepage

still nothing but then i found this
site health status
but i don’t know what are these can any one help me with these

important info:
theme
plugins: Classic Widgets, Contact Form 7, Content Views, Content Views Pro, Envato Market, Fonts Plugin | Google Fonts Typography, Joinchat, Ninja Google Place Reviews Pro, Select Core, Select Membership, Select Tours, Site Kit by Google, Select Slider Revolution, Smush, Super Socializer, UpdraftPlus – Backup/Restore, Use Any Font, WooCommerce, WooCommerce Payments, WPBakery Page Builder & Yoast SEO

The basic profile information is not being displayed using Instagram API

I am trying to create a login with instagram form. However at the callback.php, there is no information displayed.enter image description here

Kindly let me know what could be the possible issue.

Callback.php:

<?php
    session_start();

    if (isset($_GET['error'])) {
        header('Location: login.php');
        exit();
    }

    require "InstagramAPI.php";

    $data = $Instagram->getAccessTokenAndUserDetails($_GET['code']);

    $_SESSION['loggedIn'] = 1;
    $_SESSION['accessToken'] = $data['access_token'];
    $_SESSION['id'] = $data['user']['id'];
    $_SESSION['username'] = $data['user']['username'];
    $_SESSION['bio'] = $data['user']['bio'];
    $_SESSION['website'] = $data['user']['website'];
    $_SESSION['fullName'] = $data['user']['full_name'];
    $_SESSION['profilePicture'] = $data['user']['profile_picture'];

    header('Location: index.php');
    exit();
?>

PHP & MySQL – Generate own unique reference

I am currently coding a web application which I will need to create unique reference for quotes and invoices.

I wanted to create a reference that included the year and month then an reference number. i.e YYYY-MM-001.

The web application will be multi tenant and several users will be using it at the same time. One of my concerns is, how would I generate my reference without it be duplicated at the same time if there is multiple users doing the same request at the same time?

What would be the best way for me to approach this?

I am using PHP 8 and a MySQL database.

Error function get_cart() on null in theme function file

I have added this code in theme function to add quantity
//add qunitty

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
    if (!is_page('wishlist')) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
        $html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
        // Access the cart items
        $in_cart = false;
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $product_id = $cart_item['product_id'];
            $quantity = $cart_item['quantity'];
            if($product_id == $product->get_ID()){
                $in_cart = true;
                break;
            }
        }
        // If we have match update quantity
        if($in_cart) {
            $html .= woocommerce_quantity_input( array('input_value' => $quantity), $product, false );
        } else {
            $html .= woocommerce_quantity_input( array(), $product, false );
        }
        $html .= '<button type="submit" class="button alt">' . esc_html( $product->add_to_cart_text() ) . '</button>';
        $html .= '</form>';
    }
    return $html;
}
return $html;
}

But I got this error in theme log-file

function get_cart() on null

What I’m doing wrong?

How to create numuerous pages in laravel at once from mysql ids

I need to create numeros files in Laravel each having it’s own incremental number:
page1.blade.php; page2.blade.php … ecc incrementing the number of the page automatically.
I can’t create the pages manually because i have to create more than 192 pages.

I want to create the pages using the function:
$page_number = $articles->id / 8
how can i do it?
$articles is the result of a query from mysql database.

Email message not correctly formatted with PHP and outlook

I need to know if there is a way to format a text in the message body of an email in outlook.

I have this part of the message I have to send with mail function towards outlook:

Δ request and Δ fault must be....

Well, when php script sends email, in outlook I have this formatting:

Î" request and Î" fault must be...

How should I do to get the greek letter Δ correctly?

500 internal server error after uploading large amount of data php

I am on Php,Right now i am trying to upload xls file in server(not localhost),Whenever i upload file with low data then file uploading correctly,But whenever i uploading file with large amount data ( like 1,00,000 records) then showing me “500 internal server error”, I already increased maxisum execution time but still getting same error,Is this because of server ? should i increase bandwidth of server ?

Categorizing different types of likes on a post and displaying it using AJAX php

I want to create a LIKE BUTTON for 3 separate columns in my table, which I have created using Handsontable. On clicking any of these like buttons the response should be taken and sent to a PHP file. The PHP file, fetches the data and processes the SQL query to update the number of likes on the post. The required system is exactly like any other LIKE BUTTON feature (For Ex: Instagram).

Columns in the table:

  1. Employee Name
  2. Employee ID
  3. Rank (For the top 3 best targets)
  4. Goal Comment
  5. Goal Commit
  6. Result (target reached: O/X)
  7. Reply Comment
  8. Goal Comment Like (like button corresponding to 4. Goal Comment)
  9. Goal Commit Like (like button corresponding to 5. Goal Commit)
  10. Reply Comment Like (like button corresponding to 7. Reply Comment)

Column 8,9 and 10 are displayed within column 4,5 and 7 respectively since they represent like button using innerHtml and a custom Renderer like this:

function detailRenderer(instance, td, row, col, prop, value, cellProperties) {
    if (col == 4) {
        if (value != null && instance.getDataAtCell(row, 8) != null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            cellProperties.readOnly = false;
            td.innerHTML =   '<div class="like">'+value+'<div class="in-like" style="color:red;"><i class="far fa-heart"></i>' + instance.getDataAtCell(row, 9) + '</div</div>';
            console.log(instance.getDataAtCell(row, 8));
        }
        else if(value != null && instance.getDataAtCell(row, 8) == null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML =   '<div class="like">'+value+'<i class="far fa-heart" style="color:red;"></i></div>';
        }
        else{
            Handsontable.renderers.TextRenderer.apply(this, arguments);
        }
    }
    else if (col == 6) {
        if (value != null && instance.getDataAtCell(row, 9) != null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML = '<div class="like">'+value + '<div class="in-like" style="color:red;"><i class="far fa-heart"></i>' + instance.getDataAtCell(row, 9) + '</div></div>';
        }
        else if(value != null && instance.getDataAtCell(row, 10) == null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML = '<div class="like">'+value+'<i class="far fa-heart" style="color:red;"></i></div>';
        }
        else{
            Handsontable.renderers.TextRenderer.apply(this, arguments);
        }
    }
    else if (col == 8) {
        if (value != null && instance.getDataAtCell(row, 10) != null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML = '<div class="like">'+value + '<div class="in-like" style="color:red;"><i class="far fa-heart"></i>' + instance.getDataAtCell(row, 11) + '</div></div>';
        }
        else if(value != null && instance.getDataAtCell(row, 10) == null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML = '<div class="like">'+value+'<i class="far fa-heart" style="color:red;"></i></div>';
        }
        else{
            Handsontable.renderers.TextRenderer.apply(this, arguments);
        }
    } 
    else{
        Handsontable.renderers.TextRenderer.apply(this, arguments);
    }
}

This is my AJAX function which I know is definitely wrong since I am new to AJAX:

$(document).on("click", ".in-like", function(e) {
        e.preventDefault();
        var likesCounter = hot.getDataAtRowProp(row, 9);
        $.ajax({
            url: '/mycommit/like.php',
            type: 'POST',
            data: {
                'challengeId': '{{challengeId}}',
                'userId': '{{SYANM}}',
                'likesCounter': '{{likesCounter}}',
                type: 'POST',
            },
            success: function(data) {
                likesCounter = data;
                console.log(likesCounter);
            },
        });
    });

My PHP file is:

<?php
use serviceLoginService;
use utilTwigCommon;
use utilDbUtil;

$out = array();
$challengeID = $_GET['challengeID'];
$userID = $_GET['userID'];
$likesCounter = getLikesCounter($challengeID, $userID);

$out['SYANM'] = $_SESSION["login"]["SYANM"];
if(LoginService::hasRole(['system'])){
    $out["systemUser"] = 1;
}
else {
    $out["systemUser"] = 0;
}
$out['challengeID'] = $challengeID;
$out['userID'] = $userID;
$out['likesCounter'] = $likesCounter;

function getLikesCounter($challengeID, $userID){
    $params = array();
    $params['challengeID'] = $challengeID;
    $params['userID'] = $userID;

    $sql = <<<SQL
    SELECT COUNT(*) as likesCounter from HB_MYC_LIKES
    WHERE CHALLENGE_ID = :challengeID
    SQL;
    $result = DbUtil::query($sql, $params);
    $list = array_values($result);
    foreach ($list as $key => $value) {
        $list[$key]['GOAL_COMMIT_LIKES'] = count($list[$key]['GOAL_COMMIT_LIKES']);
        $list[$key]['GOAL_COMMENT_LIKES'] = count($list[$key]['GOAL_COMMENT_LIKES']);
        $list[$key]['REPLY_COMMENT_LIKES'] = count($list[$key]['REPLY_COMMENT_LIKES']);
    }
    return $list;
}
//-----------------------------------------------//
/*This is just an attempt for different approach*/
//-----------------------------------------------//

if(isset($_GET('challengeID'))) {
    $challengeID = $_GET['challengeID'];
    $likesCounter = getLikesCounter($challengeID, $userID);
    echo json_encode($likesCounter);
}

I am unable to understand how to get categorized LIKES data, currently this code is taking just likes if it exists without categorizing and I do not want to assign separate value to each like column in the frontend. Instead I want to do it in the backend with the PHP file. Since I am a beginner to this, any help would be appreciated.

Display Authenticated User’s Name in Redirect Status Message – Laravel

I want to include the authenticated user’s name when the user log in and the application redirect the person to the applicable page. In this specific example the person is being redirected to their authenticated homepage and the status message should display “Welcome back, {{Name}}”

Currently the message displays the code and and not the actual value.

I have tried the following:

public function authenticated()
    {
        if(Auth::user()->role_as == '1') //Admin = 1
        {
            return redirect('admin/dashboard')->with('status', 'Welcome to your Admin Dashboard, {{ Auth::user()->name }}.');
        }
        else
        {
            return redirect('/home')->with('status', 'Welcome back,' . " " . '{{ Auth::user()->name }}');

        }
    }

This returns the following (image contains user with
"role_as == '0'")
:

enter image description here

What other method is there to get to the desired result?