input text change avatar

I have a chat where the user changes their avatar using a library, but it overwrites the name and changes the gif to a static image.

I thought of adding an input so that the user can change their avatar by uploading it to another page and changing it using the URL, like this:

<input type="text" class="upload-image" name="avatar" value="{{USER.avatar_url}}">

The problem here is that I don’t know how to proceed so that the URL is saved and the avatar is changed. My English is not good enough so I’ll use google translate, hopefully someone will understand and help.

<input type="file" class="upload-image" name="avatar" value="Upload Photo">
// profile image upload
$(document).on("change", ".upload-image", function() {
  var uploadFile = $(this);
  var files = !!this.files ? this.files : [];#

  if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support

  if (/^image/.test(files[0].type)) { // only image file
    var reader = new FileReader(); // instance of the FileReader
    reader.readAsDataURL(files[0]); // read the local file
    reader.onloadend = function() { // set image data as background of div
      uploadFile.closest(".imgUp").find('img').remove();
      uploadFile.closest(".imgUp").find('.imagePreview').css("background-image", "url(" + this.result + ")");
    }
  }
});

How to integrate a custom search option with dynamic filelds using CodeIgniter 4 master data listing UI?

Can anyone suggest a best way for integrating search/filter options for master data UI ?

I have around 20 fields/columns to search. I do not want to show 20 separate fields for this. Instead I want to provide a common field for choosing the search column and another field for entering the value.

I am not using any grid libraries for the table data listing.

I am using codeIgniter4 with MySQL in the backend and jQuery in the frontend side.

It will be a great help if someone can suggest a suitable method.

Instant response of the Like/Dislike buttons using Alpine.js in Livewire 3

I have logic for like/dislike button in two separate livewire components (LikeButton.php/DislikeButton.php)

The problem is I want like/dislike buttons react immediately after clicking

Currently, button looks like this:

<div>
    <button wire:click="toggleLike()">Like recipe</button>
    {{ $recipe->countLikes() }}
</div>

And now after clicking I need to wait and If my user will have slow internet he’ll be waiting more way longer.

LikeButton.php:

class LikeButton extends Component
{
    public Recipe $recipe;

    public function toggleLike()
    {
        $this->dispatch('refresh-dislikes');

        // Check if user is authenticated
        // if so, get the user
        if (! $user = auth()->user()){
            return $this->redirect(route('login-page'));
        }

        // Check if user has already liked recipe
        // if true, then return unlike()
        $hasLiked = $user->likes()->where([
            'recipe_id' => $this->recipe->id,
            'liked' => true
        ])->exists();

        if ($hasLiked){
            return $this->recipe->unlikeBy($user);
        }

        // return like()
        return $this->recipe->likeBy($user);
    }

    #[On('refresh-likes')]
    public function render()
    {
        return view('livewire.like-button');
    }
}

Is there any solution to fix it by using Alpine.js?

Reading from firestore in PHP not working with non-GRPC Firebase client

I’m using this firestore client that doesnt require GRPC and it is made by bensontrent
GITHUB REPO: https://github.com/bensontrent/firestore-php

The problem I have is that my index.php is not working and I think I initialized the firebase client correctly, I am logging the errors in a file but there is no error showing up in the file and I get this errors only in the website when i load it.

HTTP ERROR 500
This page isn’t working
e-barter.x10.bz is currently unable to handle this request.

I tried initializing the firebase like this, just how the repo documentation said:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error_log.txt'); // Log errors to a file
// Database connection
require 'db_connect.php';

require '../vendor/autoload.php';

use bensontrentfirestore-phpFirestoreClient;

// Initialize variables with default values
$topRanked = $topRated = $topPosters = [];
$totalUsers = $totalItems = 0;
$recentItems = [];

try {
    // Initialize Firestore client
    $firestore = new FirestoreClient(
        'ebarter-f3229',
        'AIzaSyB2rf5zxpvwUc7U8UZZ3TqujAycg62av8Q', (here in the API key, I'm not sure if its the firebase webapi key or i need to generate another key in the google cloud???)
        ['database' => '(default)']
    );

this is the queries i’m trying to do:

// Function to calculate user rankings
    function calculateUserRankings($firestore) {
        $userStats = [];
        
        try {
            // Get all users
            $users = $firestore->listDocuments('users');
            foreach ($users as $userDoc) {
                $userId = $userDoc->id();
                $userData = $userDoc->data();
                
                $userStats[$userId] = [
                    'fullName' => $userData['fullName'] ?? 'Anonymous',
                    'postedItemsCount' => 0,
                    'completedTradesCount' => 0,
                    'totalRatings' => 0,
                    'sumRatings' => 0,
                    'averageRating' => 0,
                    'totalScore' => 0
                ];
            }
            
            // Get items
            $items = $firestore->listDocuments('items');
            foreach ($items as $item) {
                $itemData = $item->data();
                $userId = $itemData['userId'] ?? '';
                if ($userId && isset($userStats[$userId])) {
                    $userStats[$userId]['postedItemsCount']++;
                }
            }
            
            // Get completed trades
            $completedTrades = $firestore->query('barterOffers')
                ->where('status', '=', 'completed')
                ->get();
                
            foreach ($completedTrades as $trade) {
                $tradeData = $trade->data();
                $itemOwnerId = $tradeData['itemOwnerId'] ?? '';
                $likerId = $tradeData['likerId'] ?? '';
                
                if ($itemOwnerId && isset($userStats[$itemOwnerId])) {
                    $userStats[$itemOwnerId]['completedTradesCount']++;
                }
                if ($likerId && isset($userStats[$likerId])) {
                    $userStats[$likerId]['completedTradesCount']++;
                }
            }
            
            // Get ratings
            $ratings = $firestore->listDocuments('ratings');
            foreach ($ratings as $rating) {
                $ratingData = $rating->data();
                $ratedUserId = $ratingData['ratedUserId'] ?? '';
                $ratingValue = $ratingData['rating'] ?? 0;
                
                if ($ratedUserId && isset($userStats[$ratedUserId])) {
                    $userStats[$ratedUserId]['totalRatings']++;
                    $userStats[$ratedUserId]['sumRatings'] += $ratingValue;
                }
            }
            
            // Calculate scores
            foreach ($userStats as $userId => &$stats) {
                if ($stats['totalRatings'] > 0) {
                    $stats['averageRating'] = $stats['sumRatings'] / $stats['totalRatings'];
                }
                
                $ratingScore = $stats['averageRating'] * 2 * $stats['totalRatings'];
                $tradesBonus = min($stats['completedTradesCount'], 10);
                $itemsBonus = min($stats['postedItemsCount'] * 0.5, 10);
                $stats['totalScore'] = (int) round($ratingScore + $tradesBonus + $itemsBonus);
            }
            
            // Sort and return results
            $topRanked = $userStats;
            usort($topRanked, fn($a, $b) => $b['totalScore'] <=> $a['totalScore']);
            
            $topRated = $userStats;
            usort($topRated, fn($a, $b) => 
                $b['averageRating'] <=> $a['averageRating'] ?: 
                $b['totalRatings'] <=> $a['totalRatings']);
            
            $topPosters = $userStats;
            usort($topPosters, fn($a, $b) => $b['postedItemsCount'] <=> $a['postedItemsCount']);
            
            return [
                'topRanked' => array_slice($topRanked, 0, 5),
                'topRated' => array_slice($topRated, 0, 5),
                'topPosters' => array_slice($topPosters, 0, 5)
            ];
            
        } catch (Exception $e) {
            error_log("Firestore Query Error: " . $e->getMessage());
            return ['topRanked' => [], 'topRated' => [], 'topPosters' => []];
        }
    }

    // Get rankings
    $rankings = calculateUserRankings($firestore);
    $topRanked = $rankings['topRanked'];
    $topRated = $rankings['topRated'];
    $topPosters = $rankings['topPosters'];

} catch (Exception $e) {
    error_log("Firestore Init Error: " . $e->getMessage());
}

// Get database counts (this is from my domain's database and not part of firebase)
try {
    $userCountResult = $conn->query("SELECT COUNT(*) as total_users FROM users");
    $totalUsers = $userCountResult ? $userCountResult->fetch_assoc()['total_users'] : 0;
    
    $itemCountResult = $conn->query("SELECT COUNT(*) as total_items FROM items");
    $totalItems = $itemCountResult ? $itemCountResult->fetch_assoc()['total_items'] : 0;
    
    $itemsResult = $conn->query("SELECT i.*, u.username, u.city FROM items i JOIN users u ON i.userId = u.userId ORDER BY i.created_at DESC LIMIT 12");
    $recentItems = $itemsResult ? $itemsResult->fetch_all(MYSQLI_ASSOC) : [];
    
} catch (Exception $e) {
    error_log("MAIN ERROR: " . $e->getMessage());
    // Display user-friendly error message
    die("<div class='alert alert-danger'>An error occurred while loading the page. Please try again later. Technical details have been logged.</div>");
}
?>

Error before a $_Post is sent to the mysql query [duplicate]

I have the following code for a multiple dropdown menu, which takes the data from mysql database, then depending on the choice, displays a another dropdown menu.

I have done this with php, javascript and MySQL.

The problem I come across is that the first time I load the page I get the error that the array, that comes from $_Post, is not created. Such array enables the mysql query and following chart to appear.

The error is:
“Warning: Undefined array key “titulos” … “

After I do one submission with the dropdown menu, everything works fine.

How can I create a default result for this variable?

Dropdown menu and Chart Query

<form style="text-align:center;margin-top:2%;" name="myform" action="" method="post"><select style="font-size:16px;" name="magazines"   onclick="getSeries(this.value)">
    <option value="">Choose a Magazine</option>
    <?php
        $magazines = getMagazines();
        foreach($magazines as $magazine){
               <option value="<?php echo $magazine['magazine_code'] ?>">
              <?php echo $magazine['Magazine_name']?></option>
    <?php
    }
    ?>
    </select>
    <select style="font-size:16px;" name="titulos">
    <option value="">Choose a Series</option>
    </select>
    <input style="font-size:16px;" value="Send"  type="submit">


     $series_tit =$_POST['titulos'];
     $query = "SELECT * FROM chartdata WHERE Serie_name = '$series_tit'";

PHP functions

function getMagazines(){
    $conn = databaseConnection();
    $res = $conn->query("SELECT * FROM categorias");
    while($row = $res->fetch_assoc()){
        $data[] = $row;
    }
    return $data;


}

if(isset($_GET["magazine_code"])){
echo getSeries($_GET["magazine_code"]);
}

function getSeries($magazine_code){
$conn = databaseConnection();
if(!$conn){
return false;
}
$magazine_code = htmlspecialchars($magazine_code);
$res = $conn->query("SELECT * FROM chartdata WHERE magazine_code ='$magazine_code'");
while($row = $res->fetch_assoc()){
$data[] = $row;
}
return json_encode($data);

}

And Javascript

function getSeries(magazineCode){
    let seriesDropDown = document.forms["myform"].titulos;

    if (magazineCode.trim() === ""){
        seriesDropDown.disabled = true;
        seriesDropDown.selectedIndex = 0;
        return false;
    }

    fetch(`functions_sales.php?magazine_code=${magazineCode}`)
    .then (response => response.json())
    .then(function(series){
        let out = "";
        out += `<option value="">Choose a Series</option>`;
        for (let sery of series){
            out += `<option value="${sery['Serie_name']}">${sery['Serie_name']}</option>`;
        }
        seriesDropDown.innerHTML = out;
        seriesDropDown.disabled = false;


    });

}

I’ve tried making a selected option into the form but the response continue being the same.

How to get the session value set in the API controller

I’m using laravel 12.0.1 and try to check the user is logged in or not in the middleware.

I set the session value in api Controller, but when I call this value in the middleware, it is null.

And my log only shows the token in session.

How to get session value in the middleware?

My laravel_session in header and corresponding session value in database:

laravel_session=fca6d3xPRfTdlHBSTJWBd0KvaieSdKPbcGkFBZxa

a:3:{s:6:"_token";s:40:"0hYLgh1hHAZNW2Ar8E6MDBP5zKJXlLynSjt4dgTp";s:4:"user";s:5:"admin";s:6:"_flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}

My log show another session value:

my session value: {"_token":"T9EtbOAiUwUYc9s1l1gC4TrdSkTj8nT9SDFbqTIA"}

I use the session function to set global session value, and I’m sure that name is not null.

// loginVerify
$validate = $request->authenticate();

if ($validate)
{
    $post = $request->post()['body'];
    
    $acct = User::where([
        [ 'email',    '=', $post['acct'] ],
        [ 'password', '=', $post['ps']   ],
    ])->first();

    session(['user' => $acct['name']]);

    return $acct;
}
// middleware managePage
public function handle(Request $request, Closure $next): Response
{
    Log::debug ('my session value: ' . json_encode(session()->all()));

    dd($request->header('Cookie'));

    if (empty(session('user'))) 
    {
        return redirect('/managerLogin');
    }

    return $next($request);
}

here is my middleware setup:

$middleware->prependToGroup('manageSetting', [
    IlluminateSessionMiddlewareStartSession::class,
]);

$middleware->appendToGroup('managePage', [
    ManagerPage::class,
]);

and this is my route setup:

// web route
Route::middleware(['manageSetting', 'managePage'])->group(function () 
{
    Route::get('/homeManage', function () 
    {
        return Inertia::render('manage/homeManage');
    });

    Route::get('/groupManage', function () 
    {
        return Inertia::render('manage/groupManage');
    });
});

Route::middleware(['manageSetting'])->group(function() 
{
    Route::get('/managerLogin', function () 
    {
        return Inertia::render('manage/login');
    })->name('managerlogin');
});

//api route
Route::middleware(['manageSetting'])->group(function () 
{
    Route::post('/updateGroup', [GroupController::class, 'update']);

    Route::post('/updateHome', [KeyVisualController::class, 'update']);

    Route::post('/loginVerify', [UserController::class, 'login']);
});

Notes:

  1. I’ve tried the reflash and keep functions.
  2. The save function in request is not yielding working results for me, too.

How can I properly override templates and CSS in a custom PrestaShop 1.7/8 theme without breaking updates?

I’m building a custom theme for PrestaShop 1.7 (planning to support 8.x as well), and I want to override certain templates and styles without directly modifying the classic theme.

I’ve cloned the classic theme and renamed it, but I’m not sure if I’m following the best practices when it comes to:

  • Overriding .tpl files (e.g., product listings and checkout templates)
  • Adding or overriding custom CSS/SCSS in a way that doesn’t conflict with PrestaShop’s core or future updates

I have tried these tasks:

  • Duplicated the classic theme and renamed it in config/theme.yml
  • Placed custom .tpl files in /themes/mytheme/templates/
  • Used assets/css/custom.css and enqueued it via theme.yml

The overrides work inconsistently. How to ensure updates don’t break my theme?

MYSQL Incorrect DATE value: ‘202023-05-01’ [closed]

Here I have a problem so when I access the admin dashboard of the system there is an error 500 which error is caused by what probably happened in the database:
https://prnt.sc/P2nHb6-T6q-L

The question is if you look at the screenshot above, there is data in the from_date column even though there is no data recorded in that column at all:
https://prnt.sc/ohiGGjfsXeyX

Then the year number digits is also wrong even though there is no data recorded in that column at all as in the first screenshot.

Here is the coding to display that section:

    public function getStudentMonthlyLeave($start_date, $end_date)
{       
    $this->db->select('student_applyleave.*,students.firstname,students.middlename,students.lastname')
    ->from('student_applyleave')
    ->join('student_session', 'student_session.id = student_applyleave.student_session_id')
    ->join('students', 'students.id=student_session.student_id', 'inner');
    $this->db->where('student_session.session_id', $this->current_session);         
    $this->db->where('students.is_active', 'yes');
    $this->db->where('student_applyleave.from_date >= ', $start_date);
    $this->db->where('student_applyleave.from_date <=', $end_date);     
    $query = $this->db->get();
    return $query->result_array();
}

What causes the error and how to fix it? Thank you.

phone connection rendering faster [closed]

Regardless of browser, my site loads instantly on my phone and takes about five seconds on (a well spec’d)desktop. I can only guess my hosting provider is providing faster php execution for smart devices or phones? Has anyone experienced this? Site is Fedbook.net It’s literally just a php loop that fetches emojis randomly from the db.

Show products in stock only in certain page Woocommerce

I need to show all the products with stock only in some particular page.
In my case, the page ID is: post=36886

I tried this code just for testing purposes trying to see if something happen (I know this is for hide products) but nothing happens.

add_filter( 'pre_option_woocommerce_hide_out_of_stock_items', 'we_hide_out_of_stock_exception' ); 
function we_hide_out_of_stock_exception( $hide ) { 
    if ( is_page( 36886 ) ) { 
        $hide = 'no'; 
    } 
    return $hide; 
}

So, I’m stuck there. Any help will be appreciated.

How print every line of a php script as its being executed?

How to print every line of a php script as it’s being executed?

For example in Python you can do

$ cat test.py 
import time
print('hello')
time.sleep(3)
print('goodbye')

$ python -m trace -t test.py 
 --- modulename: test, funcname: <module>
test.py(1): import time
test.py(2): print('hello')
hello
test.py(3): time.sleep(3)
test.py(4): print('goodbye')
goodbye

Is there a PHP equivalent?

Cannot drag and drop test case to re-order

I installed testlink 1.9.20 and found an issue that the test case is unable to re-oder by drag and drop on the tree view.

Anyone has resolved the issue, please let me know.

I tried to compare the code between 1.9.19 and 1.9.20, do some code reverts but didn’t help.

Laravel application not loading some images when using php artisan serve at http://127.0.0.1:8000/login [closed]

I’m building a Laravel application and running it locally using php artisan serve. The login page at http://127.0.0.1:8000/login is working, but some of the images (like logos, backgrounds, or icons) are not loading in the browser.

Why are some images not loading when running the Laravel app with php artisan serve? How can I fix this?

Displaying individual rows with same key as part of larger associative array using PHP and HTML

I am trying to display data from multiple MySQL tables in individual text fields in an HTML form using PHP. Here are three sample tables from a database, followed by code that I am using to select the data and echo it to text fields in HMTL.

item_id item_title user_id
1 Abc 2
2 Def 4
document_id document_title item_id
1 Ghi 1
2 Jkl 1
3 Mno 1
4 Pqr 2
user_id user_name
1 John Doe
2 Jane Doe
3 James Doe
4 Jan Doe

Here is the code that I am using:

<?php
$sql = "SELECT i.item_title, d.document_title, u.user_name 
       FROM items as i 
       INNER JOIN documents as d
       ON i.item_id = d.item_id
       INNER JOIN users as u
       ON i.user_id = datat.item_number
       WHERE i.item_id = 1;";
    $result = mysqli_query($db_server, $sql);
    while($row=mysqli_fetch_assoc($result))
        {foreach($row as $key=>$value) ${$key}=$value;}
?>
    
    <form method="POST" action="updateItem.php">
    <p><textarea name="item_title"> <?php echo $item_title;?> </textarea></p>
    <p><input type="text" name="user_name" value="<?php echo $user_name?>"/></p>
    <p><input type="text" name="document_title[]" value="<?php echo $document_title?>"/></p>
    <p><input type="text" name="document_title[]" value="<?php echo $document_title?>"/></p>
    <p><input type="text" name="document_title[]" value="<?php echo $document_title?>"/></p>

The problem that I am running into is with the three fields that are supposed to display the document titles. The associate array produces a key=>value combo for these three rows in the document table that all have the same key (document_title). So how can I access these and display these three rows individually in individual fields in the HTML form?

Thank you in advance!

Preprocessing function never called

I’m very new Drupal Developer, and I would like to know why some of my preprocess function are never called.
At the beginning, I only used one single preprocess function.

// Before
function my_theme_preprocess_paragraph(array &$variables): void {
  if ($variables['paragraph']->bundle() == 'cta') {
    ...
  }
}

// Now
function my_theme_preprocess_paragraph__cta(array &$variables): void { 
  ...
}

I’d like to change the organization, so that I don’t have one big function, but several small ones. But the function I use now is never called by Drupal.

I’ve checked the machine names of my paragraphs as well as my file call, and everything seems to work correctly on this side. I’ve also cleared the cache several times using the drush cr command.

Anyone knows how fix it ?

Thanks