Avoid extra line in laravel loop made by key numbers

I have a function that generates excel file from my data like screenshot below

onw

There are 2 sets of issues here (yellow and blue)

Yellow: The columns should start from row #2 where it has 1 as A2 value

Blue: My code somehow adds extra line for each data object which was 1 at first then became 2 and so on… (so for each set of data it adds extra 2 empty rows)

Code

here is my loop part that is in charge of printing data as you see in screenshot above:

$no = 2;
foreach ($br as $key => $value) {
    $no = $no + $key;
    $sheet->setCellValue('A'.$no, $key+1);
    $sheet->setCellValue('B'.$no, $value->va_number);
    $sheet->setCellValue('C'.$no, $value->customer_name);
    $sheet->setCellValue('D'.$no, $value->cabang);
    $sheet->setCellValue('E'.$no, $value->payment_date);
    $sheet->setCellValue('F'.$no, $value->payment_amount);
    $sheet->setCellValue('G'.$no, $value->br_no);
    
    $dtl = DB::table('bank_receive_dtl')
    ->join('inv','inv.id','=','bank_receive_dtl.inv_id')
    ->where('bank_receive_dtl.br_id','=',$value->br_id)
    ->select('bank_receive_dtl.*','inv.inv_no')
    ->get();
    foreach ($dtl as $key => $item) {
        $no ++;
        $sheet->setCellValue('H'.$no, $item->inv_no);
        $sheet->setCellValue('I'.$no, $item->payment_amount);
    }
    $no--;
}

The problem caused by $no ++; and $no--; in second loop where some of my objects have multiple invoice numbers as you see.

PS: Here is what ideal final result should be look like except coloring part :)

two

Can you point me to the part that I’ve made mistake?

Update

Yellow issue is solved by moving $no ++ at the bottom like this:

foreach ($dtl as $index => $item) {
  $sheet->setCellValue('H'.$no, $item->inv_no);
  $sheet->setCellValue('I'.$no, $item->payment_amount);
  $no ++;  // <--moved down here
}

Blue issue still remains.

How do I remove render blocking CSS in WordPress by its link tag id?

We have a WordPress website that uses Divi theme and Litespeed cache plugin. I checked our website on google pagespeed insights and it says that there is a render-blocking css.

According to pagespeed the url(example url) below is render-blocking

<link data-optimized="1" rel="stylesheet" id="divi-dynamic-css" href="https://healthandbeauty.com/wp-content/litespeed/css/0ez9a02P748a67191h2be0c2d4f1cb.css?ver=7f0f3" type="text/css" media="all">

Problem: Is there a way I can create a WordPress hook/function to defer/load asynchronously the CSS file via the id property of the <link id="divi-dynamic-css"> tag? In addition, 0ez9a02P748a67191h2be0c2d4f1cb is a dynamic file name generated by Litespeed cache.

I need WordPress hooks/filters for this since the <link id="divi-dynamic-css"> tag is displayed by Divi or WordPress and not by me. In other words, I cannot manually add or remove <link id="divi-dynamic-css">.

For example:

add_action('style_loader_tag', 'make_css_async');
function make_css_async() {
?>
  $html = <link rel='stylesheet' id='divi-dynamic-css'  href='wp-content/litespeed/css/0ez9a02P748a67191h2be0c2d4f1cb.css?ver=7f0f3' media="all" onload="this.media='all'" />

  return $html;
<?php

Your help is greatly appreciated. Thanks!

Problem sending email from PHP with SMTPS and PhpMailer

I’m trying to modify the mail system of a website to use entirely standard SMTPS with a straightforward script which would be this:

<?php
require "vendor/phpmailer/phpmailer/PHPMailerAutoload.php";

try {
    $mail = new PHPMailer();
    $mail->SMTPDebug = SMTP::DEBUG_CONNECTION;
    $mail->Mailer = 'smtp';
    $mail->Host = 'mydomain.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'my-password';
    $mail->SMTPSecure = 'ssl';
    $mail->From = '[email protected]';
    $mail->FromName = 'TEST';
    $mail->ConfirmReadingTo = '[email protected]';
    $mail->Port = 465;
    $mail->Timeout = 30;
    $mail->IsHTML(false);
    $mail->CharSet = 'UTF-8';
    $mail->addAddress('[email protected]');
    $mail->Subject = 'TEST';
    $mail->Body = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';

    $sent = $mail->Send();
    echo $sent ? "SENT" : "NOT SENT";
} catch (Exception $e) {
    echo "ERROR";
}

This script works on all the machines we have tested and against any email account. It is as simple as possible.

The error it throws is as follows:

2023-05-12 04:26:37 Connection: opening to ssl://mydomain.com:465, timeout=30, options=array ()
2023-05-12 04:26:38 Connection failed. Error #2: stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:error:140943FC:SSL routines:ssl3_read_bytes:sslv3 alert bad record mac [E:wwwAPPvendorphpmailerphpmailerclass.smtp.php line 298]
2023-05-12 04:26:38 Connection failed. Error #2: stream_socket_client(): Failed to enable crypto [E:wwwAPPvendorphpmailerphpmailerclass.smtp.php line 298]
2023-05-12 04:26:38 Connection failed. Error #2: stream_socket_client(): unable to connect to ssl://mydomain.com:465 (Unknown error) [E:wwwAPPvendorphpmailerphpmailerclass.smtp.php line 298]
2023-05-12 04:26:38 SMTP ERROR: Failed to connect to server: (0)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
NOT SENT

Well, after several days and more than 20 hours, I can’t find what the problem is, although I’m sure it’s something directly related to Windows 11. Neither PHP nor the SSL libraries have anything to do with it.

I have done a lot of tests:

  • Minimal script with various libraries on the market; none of them works; they all give exactly the same error.
  • I’ve tested that script on several Windows 10 and 11 machines, and it works on several Linux, and it works on my Mac, and it works on all except this server with Windows 11.
  • I have checked the Windows SSL and TLS options; they are identical on both DEV and PROD machines.
  • I have also tried connecting via Telnet to see if it throws any messages, but nothing.
  • I have tried running the test script from the command line, and the result is the same.
  • I have created an email account on a server of mine, and tried using it to send; the problem is the same.
  • I have forced the SMTP connection with SSL2, SSL3, TLS1.0, TLS1.1, TLS1.2 and TLS1.3 with all of them giving the same error.
  • I have deactivated the antivirus, and the same result. At this point, I have tried to open a case in PHPmailer, but they have rejected it because we are using an obsolete version as it is the only one that supports PHP 7.1, which is what the web uses, so we are stuck.

Any help will be appreciated.

How can I list names of people with birthdays today from a .txt file in PHP?

I have a .txt list with a large number of birthdays, in a format like this:

1975-12-13|Amy Lee|[email protected]

I would like to create php code that would go through the whole list, find persons who have a birthday today, and list their names.

What I manage to do is this, but it is showing only one name, even tho there’s multiple birthdays at the same day:

$f=file('birthday.txt');
$today=date('m-d');
for ($i=0; $i<count($f); $i++) {
    $info=explode ('|',$f[$i]);
    if (substr($info[0],5)==$today) {
        $firstlastname= $info[1];
        $message=''.$firstlastname.'';
}
}

return ''.$message.'';

I guess that I should use foreach there somehow, I’m not a pro in PHP obviously, but I don’t know how to do that. Any suggestions please?

Thanks!

Call to unknown function: ‘add_action’PHP(PHP0417) in VS Code

I am trying to run these hooks in vs code so that whenever we activate the plugin the table will be created in phpmyadmin but it is no working and also it shows call to unknown function bug in code.

register_activation_hook(__FILE__, 'form_data_activate');
register_deactivation_hook(__FILE__, 'form_data_deactivate');

function form_data_activate()
{
    global $wpdb;
    global $table_prefix;
    $table = $table_prefix . 'form_data';

    $sql = "CREATE TABLE $table (
            `id` int(11) NOT NULL,
            `name` varchar(500) NOT NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
            ALTER TABLE $table
                ADD PRIMARY KEY (`id`);
            ALTER TABLE $table
                MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;";

    $wpdb->query($sql);
}

function form_data_deactivate()
{

    global $wpdb;
    global $table_prefix;
    $table = $table_prefix . 'form_data';

    $sql = "DROP TABLE $table";

    $wpdb->query($sql);

}

add_action('admin_menu', 'form_data_menu');
function form_data_menu()
{
    add_menu_page('Form Data', 'Form Data', 8, __FILE__, 'form_data_list');
}

function form_data_list()
{
    include('form_data_list.php');
}

Garder les 0 lors de l’importation Table2excel.js [closed]

Bonjour tout le monde,

J’ai plusieurs problèmes avec Table2excel.js …

J’importe des articles tels que “00240” et en retour dans Excel elles sont transformées en “240” ou encore
“237009972014309000” transformé en 2,3701E+17

enter image description here
enter image description here

J’ai essayer d’importer avec un ‘ devant les nombres mais ca me donne
enter image description here

Please help Me !!!

Error setting image format: Can not process empty Imagick object

I am getting error when i am converting HEIC format to pdf. the code breakes on $imagick->setImageFormat(‘pdf’); line. that gives error Error setting image format: Can not process empty Imagick object.
Your answer will be appreciated.

if ($doc['file_type'] == 'application/octet-stream') {
                    $GLOBALS["log"]->fatal("Converting HEIC document : " . print_r($doc, true));
                    $document_name = $doc['document_revision_id'];
                    $GLOBALS["log"]->fatal("PDF saved at: 1");
                    $directory = "upload/";
                    $img_path = $directory .$document_name;
                    $pdfPath = $directory .$document_name;
                    $GLOBALS["log"]->fatal("PDF saved at: " .$img_path);
                    $GLOBALS["log"]->fatal("PDF saved at: 2");
                    // Load the HEIC image using Imagick
                    $imagick = new Imagick();
                    $GLOBALS["log"]->fatal("PDF saved at: 3");
                    
                    $imagick->readImage('heif:', $img_path);
                    $GLOBALS["log"]->fatal("PDF saved at: 4");
                    // Convert the HEIC image to PDF
                    try {
                        $imagick->setImageFormat('pdf');
                    } catch (Exception $e) {
                        $error_message = $e->getMessage();
                        $GLOBALS["log"]->fatal("Error setting image format: " . $error_message);
                        return false; // or handle the error as needed
                    }
                    // $imagick->setImageFormat('pdf');
                    $GLOBALS["log"]->fatal("PDF saved at: 5");
                    // $pdfPath = "path/to/save/converted/pdf.pdf";
                    $imagick->writeImages($pdfPath, true);
                    
                    $GLOBALS["log"]->fatal("PDF saved at: " . $pdfPath);

                    //Changing file name + file extension
                    $document_revision_bean = BeanFactory::getBean('DocumentRevisions', $doc['document_revision_id']);
                    $GLOBALS["log"]->fatal("Old File Ext : " . $document_revision_bean->file_ext);
                    $GLOBALS["log"]->fatal("Old File Name : " . $document_revision_bean->filename);
                    $file_name_arr = explode(".", $document_revision_bean->filename);
                    $GLOBALS["log"]->fatal("File ext From Name: " . end($file_name_arr));

                    $newName = $this->lastReplace(end($file_name_arr), "pdf", $document_revision_bean->filename);
                    $GLOBALS["log"]->fatal("New File Name : " . $newName);
                    $document_revision_bean->filename = $newName;
                    $document_revision_bean->file_ext = 'pdf';
                    $document_revision_bean->save();
                }

Replacing Woocommerce min and max price with custom field price

i have a Woocommerce e-shop and i have added a custom field for the wholesale prices. How i can get the min_price and max_price from the custome field in variable products?

i have this php script added to functions.php

add_filter( 'woocommerce_get_price_html', 'empty_and_zero_price_html', 20, 2 );
function empty_and_zero_price_html( $price, $product ) {
    global $ask_for_price;
    global $whuser;

    if($product->is_type('variable') and !is_admin()) {
        $prices = $product->get_variation_prices( true );
        if($whuser) {
            $myprice = (float) get_post_meta( $variation_id, '_pricew', true );
        } else {
            $myprice = $prices['price'];
        }

        if ( empty( $myprice) or $myprice==0 ) {
            return $ask_for_price; // <=== HERE below for empty price
        } else {
            $min_price     = current( $myprice );
            $max_price     = end( $myprice );
            if ( $min_price === $max_price && 0 == $min_price ) {
                return $ask_for_price; // <=== HERE for zero price
            }
            elseif ( $min_price !== $max_price && 0 == $min_price ) {
                return wc_price( $max_price );
            }
        }
    }
    else if($product->is_type('simple') and !is_admin()) {
        if ( '' === $product->get_price() || 0 == $product->get_price() ) {
            return $ask_for_price; // <=== HERE for empty and zero prices
        }
    }
    return $price;
}

i have replaced the $prices[‘price’] with $myprice (wholesale price) but it’s returning zero (0).

what i’m doing wrong?

Cannot Receive Firebase Notification on multiple device by sending notify to specific topic

My purpose is to send notification to specific login customer

Example : Customer ID : 1 , I need to subscribe them to topic “/topic/customer_1”

On JavaScript Site, after I got the permission token , I’ve called the server site to subscribe the customer to the topic by their token.

If I login by using PC , Then I can get TOKEN_A

If I login by using same account on mobile , Then I can get TOKEN_B

function IntitalizeFireBaseMessaging() {

    messaging

        .requestPermission()

        .then(function () {

            console.log("Notification Permission");

            return messaging.getToken();

        })

        .then(function (token) {

            console.log("Token : "+token);

            $.ajax({
                url : '/firebase-subscribe-customer-to-topic?token=' + token,
                success: function(data){
                    console.log(data);
                }
            });

            document.getElementById("token").innerHTML=token;

        })

        .catch(function (reason) {

            console.log(reason);

        });

}

This is Server Side (PHP)

$token = $_GET['token'];
$customer_id = 1;
$headers = array
    ('Authorization: key=MY_FIREBASE_KEY' ,
    'Content-Type: application/json');

$ch = curl_init();
// browser token you can get it via ajax from client side

curl_setopt($ch, CURLOPT_URL, "https://iid.googleapis.com/iid/v1/$token/rel/topics/customer_" . $customer_id);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, array());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);

Now the problem is that I can receive the notification only on PC and not on mobile.

And here is the send notification code for firebase

 $payload = [
            'click_action' => 'FLUTTER_NOTIFICATION_CLICK',
            'tab_index' => 3
        ];
 $this->fireBaseNootification("/topics/customer_1" ,"Title","Description","https://www.google.co.in/images/branding/googleg/1x/googleg_standard_color_128dp.png",$payload);


private function fireBaseNootification($to, $title, $message, $img = "", $datapayload = ""){
    $msg = urlencode($message);
    $data = array(
        'title'=>$title,
        'sound' => "default",
        'msg'=>$msg,
        'data'=>$datapayload,
        'body'=>$message,
        'color' => "#79bc64"
    );
    // if($img){
    //     $data["image"] = $img;
    //     $data["style"] = "picture";
    //     $data["picture"] = $img;
    // }
    $fields = array(
        'to'=>$to,
        'notification'=>$data,
        'data'=>$datapayload,
        'content_available' => true,
        "priority" => "high",
    );
    $headers = array(
        'Authorization: key=MY_SERVER_KEY',
        'Content-Type: application/json'
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    curl_close( $ch );
    return $result;
}

Could you tell which part I was wrong?

Issue with foreign key constraint in PHP and MySQL script

I’m facing an issue with my PHP and MySQL script where I have a foreign key constraint between two tables. I’m unsure whether the issue lies in my index.php script or the database.sql script. I would appreciate any insights or suggestions to help me resolve this problem.

Description:
I have a web application where users can shorten URLs. I have two tables: “users” and “url_mappings”. The “users” table stores user information, and the “url_mappings” table stores the shortened URLs along with the corresponding user ID as a foreign key.

Problem:
When trying to insert data into the “url_mappings” table, I’m encountering the following error:
“Execution of prepared statement failed: Cannot add or update a child row: a foreign key constraint fails (tenazped_url_shortener.url_mappings, CONSTRAINT url_mappings_ibfk_1 FOREIGN KEY (user_id) REFERENCES users (id))”

Code snippets:
Here’s a simplified version of the relevant code in my index.php script:

<?php
// Relevant code for URL mapping insertion
// ...

$conn = connectToDatabase();
$stmt = $conn->prepare("INSERT INTO url_mappings (short_url, original_url, user_id) VALUES (?, ?, ?)");

// ...
?>

And here’s a snippet from my database.sql script:

-- Tabel users (users)
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL,
    password VARCHAR(255) NOT NULL,
    is_admin TINYINT(1) DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Tabel URL Shortener (url_mappings)
CREATE TABLE url_mappings (
    id INT PRIMARY KEY AUTO_INCREMENT,
    short_url VARCHAR(255) NOT NULL,
    original_url VARCHAR(255) NOT NULL,
    user_id INT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

Steps taken:
I have verified that the “users” table has valid data, including proper values in the “id” column.
I have checked the code in the index.php script that handles the insertion into the “url_mappings” table, ensuring that the user ID being used exists in the “users” table.
I have examined the database.sql script to confirm that the foreign key constraint is correctly defined between the two tables.

Expected Outcome:
I expect the insertion of data into the “url_mappings” table to succeed without any foreign key constraint errors.

Request:
Could you please help me identify the possible cause of this issue? Is there something I missed in my code or database structure? Any suggestions or insights would be greatly appreciated.
Thank you in advance for your assistance.

Storing state (customizations) of a form that uses interact.js and load each based on chosen data

I would like an opinion on a best way to do the above.

Specifically, I have many campaigns. Each of them has different fields bind to it. When user clicks on a campaign, it opens form that shows fields for the current campaign. And user should be able to reorder/resize fields however they want on a given campaign. But, how to properly store (to the DB) user-defined state of the DOM where this form is, to load it later in that way?

I really appreciate the answers.

My reasoning was to somehow take whole form part (it’s DOM) and store it in a file on a server for specific campaign, then load it through yielding to the component. But not sure how to do it properly.

WooCommerce – Change thank you order notice based on articles in cart (by category)

I need to show a specific notice when there is an article with the product category (product_cat) “media” in the order. I currently just know how to change it for all orders. All my other attempts where not working:

function customize_thankyou_page_notice( $message ) {
  $new_message = 'Your custom message goes here.';
  return $new_message;
}
add_filter( 'woocommerce_thankyou_order_received_text', 'customize_thankyou_page_notice' );

PHP program to exchange first and last characters in a string

I am trying do to this exercise:

“Write a PHP program to exchange the first and last characters in a given string and return the new string.”

The thing I’ve tried to do is this:

function stringReverse($str){

    $newStr = array($str);

    $tab = [];

    for($i = 0 ; $i<count($newStr); $i++){
        if($newStr[$i] == [0] && $str[$i] == [count($newStr)-1]){
            $tab[$i] = count($newStr)-1 && $tab[$i]= $newStr[0];
        }
        return $tab;
    }
}

echo stringReverse("abcd");

but it’s not working – I get this error :

PHP Notice: Array to string conversion in on line 89 Array

I’m expecting this result :

dbca

Goal of exercise : exchange first and last character of a string.

Can anyone help with this?

Create a new feature for a WordPress page

I need a page with a specific title to launch the template I designed.

For this purpose, I added the following code to the functions.php file and it created a new page for me:

$check_page_exist = get_page_by_title('Login', 'OBJECT', 'page'); 

if(empty($check_page_exist)) {
    $page_id = wp_insert_post(
        array(
        'comment_status' => 'close', 
        'ping_status'    => 'close', 
        'post_author'    => 1, 
        'post_title'     => ucwords('Login'), 
        'post_name'      => strtolower(str_replace(' ', '-', trim('Login'))), 
        'post_status'    => 'publish', 
        'post_content'   => ' ', 
        'post_type'      => 'page', 
        'post_parent'    => ' ',
        )
    );
}

But I have changed the attribute of the page and added the template (Login Page) to the page using the following code:

 <?php
    // template name: Login Page
  ?>

Now I want the page that I created with the above code to be replaced with this template instead of the default template.

Is there a way to change the page layout by editing the code?