PHP mysqli_fetch_assoc [closed]

I’m going to view a result using two tables. one table is task details and one the table I assigned two or more users for each task. Now how can I show each task in one row and how many users I have assigned to each task from another table (as in screenshot).

enter image description here

How to hide attributes for sold out products in filter area without hiding the sold out products in woocommerce

I’m using woocommerce for my e-commerce website. I need to keep sold out products visible for my clients but I want to hide attributes of sold out products in filtering area. for example if all products of an attribute is out of stock, I don’t want the users to see and select the attribute while filtering the products.
This is my shop page address: www.dyadartisans.com/shop

I tried some plugins but I prefer a snippet

Set a parent page for author’s archive in WordPress

I want to make a page /authors with authors list and set it as a parent for author’s archive (author.php). URL should look like authors/jonhsmith with breadcrumbs “Authors -> John Smith”.
Is it possible using default author.php without creating custom post type?

I’ve created “Authors” page with slug “authors”. Changed author page slug from “author” to “authors” with Edit Author Slug plugin.

if the product has multiple images from the image table that shows it, and if it does not exist

How can I do condition if the product has multiple images from the image table that shows it, and if it does not exist, it appears empty

@foreach($products as $product)
<tr>
    <td>{{ $product->id }}</td>
    <td>{{ $product->name }}</td>
    <td class="text-center">
        <span class="badge rounded-pill text-bg-primary">
            {{ AppModelsProjectEcommerceProductImage::where('product_id', $product->id)->count() }}
        </span>
    </td>
    <td>


        // mutli image Product //
        @if (!empty($product->images))
            <img src="{{ asset('Image/ProductImage/'. $product->images->pull('0')->image) }}" alt="{{ $product->title_image }}" class="object-fit-contain" width="50" height="50">
        @endif
        // end mutli image Product //


    </td>
</tr>
@endforeach

Attempt to read property “image” on null

How to stop or timeout a consumer from consuming after specific time in RabbitMQ using php

Here is a hello world example on rabbitmq docs about consumer using php and php-amqplib package:

<?php

require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLibConnectionAMQPStreamConnection;

$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();

$channel->queue_declare('hello', false, false, false, false);

echo " [*] Waiting for messages. To exit press CTRL+Cn";

$callback = function ($msg) {
    echo ' [x] Received ', $msg->getBody(), "n";
};

$channel->basic_consume('hello', '', false, true, false, false, $callback);

try {
    $channel->consume();
} catch (Throwable $exception) {
    echo $exception->getMessage();
}

$channel->close();
$connection->close();

Are there any ways to stop or timeout the consumer after a specific time?
And I wonder how the process can reach the close() method of connection and channel in the code above if there are not any exception occur because the consume() method is blocking it?

I found out that there is a basic_cancel method but I don know where and when to use it because like I said, the consume() method is blocking the code.

Laravel: Function return “Object” instead of “Array”

I’m building a diet plan with Laravel 8.

Database looks like this:

Recipes Category Calories
Eggs breakfast 180
Yogourt breakfast 50
Apple pie snacks 289
Banana pie snacks 386
Tomato Pasta lunch-dinner 712
Chicken Salad lunch-dinner 956
Vegetables soup lunch-dinner 410
Fish with potatoes lunch-dinner 652

I’d like to get the day’s meals according to average daily calories.

For example, if my daily calories is 1500kcal, I want to get 4 recipes (breakfast/lunch/dinner/snacks) for the day whose total calories are between 1300-1500 calories.

I use the same category for lunch and dinner but I need 2 results from this category.

I built some functions to do this:

use AppModelsRecipe;

// Function to generate combinations of recipes
function generateCombinations($items, $n, $start = 0, $result = [], &$results = []) {
    if ($n === 0) {
        $results[] = $result;
        return;
    }

    for ($i = $start; $i < count($items); $i++) {
        $result[] = $items[$i];
        generateCombinations($items, $n - 1, $i + 1, $result, $results);
        array_pop($result);
    }
}

// Function to filter combinations by total calories
function filterCombinationsByCalories($combinations, $dailyCaloriesMin, $dailyCalories) {
    return array_filter($combinations, function($combination) use ($dailyCaloriesMin, $dailyCalories) {
        $totalCalories = array_sum(array_column($combination, 'calories'));
        return $totalCalories >= $dailyCaloriesMin && $totalCalories <= $dailyCalories;
    });
}

// Function to get daily meal plan
function getDailyMealPlan($dailyCalories, $dailyCaloriesMin) {
    $mealCategories = ['breakfast', 'lunch-dinner', 'snacks'];
    $mealPlan = [];

    foreach ($mealCategories as $category) {
        $recipes = Recipe::where('meal', $category)->get()->toArray();

        // Generate combinations of recipes for this meal category
        $combinations = [];
        if ($category == 'lunch-dinner') {
            generateCombinations($recipes, 2, 0, [], $combinations);
        } else {
            generateCombinations($recipes, 1, 0, [], $combinations);
        }

        // Filter combinations by total calories
        $filteredCombinations = filterCombinationsByCalories($combinations, $dailyCaloriesMin, $dailyCalories);

        // If there are no valid combinations, choose a single recipe with the highest calories
        if (empty($filteredCombinations)) {
            $selectedRecipe = Recipe::where('meal', $category)->orderBy('calories', 'desc')->first();
            $mealPlan[$category] = $selectedRecipe;
        } else {
            // Randomly select a combination from the filtered combinations
            $selectedCombination = $filteredCombinations[array_rand($filteredCombinations)];
            $mealPlan[$category] = $selectedCombination;
        }
    }

    return $mealPlan;
}

But when I do:

$mealPlan = getDailyMealPlan($dailyCalories, $dailyCaloriesMin);
dd($mealPlan);

I get an Object for breakfast, an Object for snacks and one Array with 2 results for lunch-dinner

See here:

array:3 [▼
  "breakfast" => AppModelsRecipe {#1388 ▶}
  "lunch-dinner" => array:2 [▶]
  "snacks" => AppModelsRecipe {#1736 ▶}
]

I don’t understand why I don’t get 3 Array. I would like to obtain this result:

array:3 [▼
  "breakfast" => array:1 [▶]
  "lunch-dinner" => array:2 [▶]
  "snacks" => array:1 [▶]
]

Any solution?

Select SQL query in PHP foreach loop

I have a DB with two tables in it : Users and Commands. I’m trying to print on a web page a different array for the purchases of every user, based on their user ID.

I have this code :

try
{
$mysqlClient = new PDO(
'mysql:host=$host;dbname=FirstDB;charset=utf8',
'$user',
'$pwd'
);
}
catch (Excetion $e)
{
die(Error : ' . $e->getMessage());
}


$UsersSelectQuery = 'SELECT * FROM Users';
$UsersStmt = $mysqlClient->prepare($UsersSelectQuery);
$UsersStmt->execute();
$UsersRows = array($UsersStmt->fetchAll());

foreach ($UsersRows as $Row)
{
$sql = 'SELECT * FROM Commands WHERE UserID=?';
$stmt = $mysqlClient->prepare($sql);
$stmt->bind_param("i", $Row);
$stmt->execute();
$result = $stmt->get_result();
$response = $result->fetchAll();

echo '<pre>'; print_r($response); echo '</pre>';

}

This code results in a blank page and my “$response” variable is empty. I guess that the way I include the “foreach” auto PHP variable ($Row) in the SQL “select” query is wrong.

I’ve tried everything I found on the web to concatenate the PHP variable in the SQL query (with dots, single and double quotes, prepared statements, placeholders, params…), but each time, the “$response” variable is empty.

If I set a fixed value instead of the “$Row” variable (for example “1”), the array variable does display data on the web page (with the “print_r” command).

Does anyone know what I’m doing wrong ?

Thank you !

How do I validate email in PHPMailer which does not exists?

I want to know how to validate emails entered in the input box are real and exist, and if the provided email does not exist I want to throw an error.

What I mean to say is when I enter this email “[email protected]”(doesn’t exist) and send it, I receive from mail delivery subsystem

Address not found

but PHPMailer doesn’t throw any error simply moves forward, do’s what the next line in the program is.

How to add record in two tables with the ID in first table

I want to use the id in one table as value in second table in 2nd query.

When i insert data in first table it save its id in one variable and then use that variable value in 2nd query as value of other column.

i have two tables h_patients and appointments table.

i want that when i insert data in h_patients table on registration.. it adds value in the appointment table too.

i want to use the id of patient (in h_patients table) in patient id column in appointment table.

i tired using $last_id = mysqli_insert_id($conn);

$sql = “INSERT INTO h_patients ( p_name, p_username, p_password, p_email, p_phone, p_disease, department_id, department_name, p_reg_date, appointment_time, p_doctor_id, appointment_status, room_no) VALUES (‘$p_name’,’$p_username’,’$p_password’,’$p_email’,$p_phone,’$p_disease’,$dept_id,’$dept_name’,’$p_reg_date’,’$appointment_time’,$p_doctor_id,’$appointment_status’,$room_no)”;

$result = mysqli_query($conn, $sql) or die(“Query Unsuccessful.”);

if ($result) {
$last_id = mysqli_insert_id($conn);

$sqlIn = ” INSERT INTO appointments( patient_id, patient_name, doctor_id, appointment_status, appointment_time) VALUES ($last_id,’$p_name’,$p_doctor_id,’$appointment_status’,’$appointment_time’)”;

$resultIn = mysqli_query($conn, $sqlIn) or die(“Query Unsuccessful.”);

}

Slow calls from php

Slow calls from php
I’m trying to understand the problem with slow calls from PHP. The PHP application makes a call, using the REST API, to a Golang microservice 400 RPS, 7 instances of Go service, nginx as load balancer. According to the Go microservice metrics, 99% of calls are completed within 5 ms. Maximum duration of calls was 6 ms. Jaeger traces in the microservice show same. Go service just returns data from in-memory cache. However, in PHP app logs I see slow calls, lots of calls for 1 seconds, for 3 seconds.
What can be reason for it, how to fix the slowness?

My websites links are all showing 404 Not Found pages, likely to do with the .htaccess configuration

I’m having a bit of a head scratcher with the navigation links on my website all things horror. All are returning a 404 page not found error.

I’ve added some security to my site in the form of public and private folders, all my pages for navigation are in the public folder, but I don’t think my .htaccess file is set up correctly and thus resulting in the 404 error.

All php files for navigation are in the public directory, and worked without issue before they were moved into separate folders, additionally, the index.php makes use of a file stored in the private directory which is required for the generator to work properly.

File structure is like this, on the SiteWorx platform:

html -> private,
public
.htaccess

-> public -> index.php, about.php, .htaccess

The public .htaccess is currently empty as I have honestly no idea how it really works.
The html one currently has DirectoryIndex /public/index.php as the only value, but it seems to be working, previously it was:

# BEGIN Sitepad
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
</IfModule>
# END Sitepad

php_value display_errors Off

private does not have an .htaccess file, not sure if it’s required.

The urls do work, but only with /public/ before the filename.php (Ideally I don’t want public to be visible in the url.

This is a side project of mine which I unfortunately don’t have a whole lot of time to dedicate to due to other more important things, but I would like to have it working and get a better understanding of how these things work and fix them when they do, so any help would be much appreciated.

Thank you.

Clicking on a navigation link returns a 404 error instead of the desired page. By adding /public/ to the URL before the page name it returns the desired result.

Elementor Forms API – Set different headers for Email 1 and Email 2

I am currently trying to dynamically add CC email addresses to an Elementor form’s email through the WordPress functions.php file. My client wants me to only add the CC email addresses when a specific value from a drop down / select field is selected. I’ve managed to get it to work but now it adds those CC email addresses to both emails. (Reference: Add CC or BCC email addresses dynamically when submitting a Elementor form, through the WordPress functions.php file)

I use the Elementor Form Actions After Submit Emails in the following ways:

  1. Email = supplied information is send to the website owner
  2. Email 2 = a copy of the supplied informi s send to the visitor who filled out the form

Here is the code:

##############################################################################
// Action is called when the forms is submitted and being processed
##############################################################################
add_action( 'elementor_pro/forms/process', 'add_cc_emails_to_submitted_elementor_forms', 10, 2 );
function add_cc_emails_to_submitted_elementor_forms( $record, $handler ) {
    // Get the form name
    $form_name = $record->get_form_settings( 'form_name' );
    
    // Check which form is being processed
    if ( $form_name !== 'FORM NAME') {
        return;
    }

    // Create an array of all the fields used in the form
    $raw_fields = $record->get( 'fields' );
    
    // Get the selected drop down value
    $drop_down_field_value = $raw_fields['field_name']['value'];
    
    // Set the CC email addresses
    if( $drop_down_field_value === 'SOMETHING' ){   
        // Call the filter to apply the needed CC Emails
        add_filter( 'elementor_pro/forms/wp_mail_headers', 'add_cc_emails_to_elementor_form', 10, 1 );
    }
}

##############################################################################
// Add CC email addresses to the Email Header
##############################################################################
function add_cc_emails_to_elementor_form( $headers ) {
    
    // Set all the CC email addresses   
    $headers .= "Cc: [email protected]";
    $headers .= "Cc: [email protected]";
    
    return $headers;
}

Is there a way for me to set the headers based on the email that is being send. I only need the CC email addresses added to Email 1 (the one that gets send to the website owner) and not Email 2. The information on the developer docs (https://developers.elementor.com/docs/hooks/forms/) don’t mention anything about it.

Attempt to assign property “username” on null

Recently we upgraded PHP at 8.1 at our company and one crucial file has stopped working.

function checkVATGR($username,$password,$AFMcalledby="",$AFMcalledfor)
{
    $client = new SoapClient( "https://www1.gsis.gr/webtax2/wsgsis/RgWsPublic/RgWsPublicPort?WSDL",array('trace' => true) );
    //$version = $client->rgWsPublicVersionInfo();
    $authHeader = new stdClass();
    $authHeader->UsernameToken->Username = "$username";
    $authHeader->UsernameToken->Password = "$password";
    $Headers[] = new SoapHeader('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'Security', $authHeader,TRUE);
    $client->__setSoapHeaders($Headers);
    $result = $client->rgWsPublicAfmMethod(
        array(
            'afmCalledBy'=>"$AFMcalledby",
            'afmCalledFor'=>"$AFMcalledfor",
            )
        );
    return $result;
}    

The full code can be found at github . I do realize, based also on this question, that it has to do with SOAP and that is backwards incompatible with PHP 7.

How could the code be modified to continue working? I have no idea how SOAP works and it would take me a while to learn it whereas we need the company application to continue working.