Hide Price and Discount Text from WooCommerce Subscription Dropdown Options

I want to remove the word “for”, the pricing + discount sale and only display the subscription options like “Delivery every month” and “Delivery every 2 months,” etc.

View product page

I’ve managed to change the text, but I’m having trouble removing the pricing. Here’s the hook I’m using.

function wc_subscriptions_custom_price_string( $price_string ) {
    // First, replace 'every' with 'Delivery every'
    $new_price = str_replace('every', 'Delivery every', $price_string);
    
    // Now, use a regular expression to remove ' months for $X.XX'
    // This assumes that the price is always in the format of $ followed by any number of digits, a dot, and exactly two digits
    $new_price = preg_replace('/ months for $d+.d+/', '', $new_price);
    
    // Optionally, if you also want to remove the '(10% off)' part, you can add another line like this:
    // $new_price = preg_replace('/ (.*?% off)/', '', $new_price);
    
    return $new_price;
}
add_filter( 'woocommerce_subscriptions_product_price_string', 'wc_subscriptions_custom_price_string' );
add_filter( 'woocommerce_subscription_price_string', 'wc_subscriptions_custom_price_string' );

FILTER_VALIDATE_EMAIL doesn’t return False [closed]

I’m trying this code :

if(!empty(!$_POST["email"], FILTER_VALIDATE_EMAIL) { 
    die ( "Invalid email" ) 
}

Normally it should return False when an invalid mail address is typed ? When I enter a broken email address, I don’t enter in the if(!empty…) so there’s no error message sent to the user.

But when the email address is correct it’s working because in xampp the mail is properly added .

I’m on Php 8.2.12 on windows 10.

So I would know if it’s a common problem that can be fixed, or will I have to find another way to check if the email address is not wrong ?

Thanks

shopify REST Admin API Response header doesn’t includes a URL for the next page of results

According to the official shopify documentation , “https://shopify.dev/docs/api/usage/pagination-rest#make-a-request-for-paginated-data”
there will be a link to the next page in the response header , but in my practical scenario , theres no link available , am i missing somthing ?

there are almost 60 products in my store,
my first api call returns the exact number of product i set as $perPage value properly, but i can not find the value of “link” to get the URL for the next page of results.

Thanks in advance.

        $productEndpoint = "https://".$this->shop."/admin/api/2024-01/products.json";
        $perPage = 20; // Set the desired number of products per page
      
        
        $allProducts = [];
        
        do {
            // Append query parameters for per_page and page
            $url = $productEndpoint."?limit=".$perPage;
            
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'X-Shopify-Access-Token: ' . $this->accessToken,
            ]);
        
            $response = curl_exec($ch);
            $headers  = curl_getinfo($ch);
          
           
            $productDataArray   = json_decode($response, true);
           echo "All Headers:n";
           var_dump($headers);
            
            // Close the cURL connection
            curl_close($ch);
        


        } while (true);

Doctrine 3.0.2 fatal error on flush PreUpdate must be of type LifecycleEventArgs, PreUpdateEventArgs given

I just updated Doctrine to the last version 3.0.2 and when I try to do a simple flush:

global $entityManager;
$entity = $this->getRepository()->findByUID($uid);
        
if(!$entity) {
    $entity = parent::createNewEntity();
    $entity->setUid($uid);
}

$entity->setSuperHashDate($dateTime);
$entity->setSalt($salt);
$entity->setSuperHash($superHash);

$entityManager->flush();

It returns the following error:

AH01071: Got error ‘PHP message: PHP Fatal error: Uncaught TypeError:
DoctrineEventSubscriber::preUpdate(): Argument #1 ($args) must be of
type DoctrineORMEventLifecycleEventArgs,
DoctrineORMEventPreUpdateEventArgs given, called in
/home/framework/public_html/app/_core/libs/vendor/doctrine/event-manager/src/EventManager.php
on line 41 and defined in
/home/framework/public_html/app/_core/events/subscribers/DoctrineEventSubscriber.php:23
Stack trace:

#0 /app/libs/vendor/doctrine/event-manager/src/EventManager.php(41): DoctrineEventSubscriber->preUpdate()

#1 /app/libs/vendor/doctrine/orm/src/Event/ListenersInvoker.php(95): DoctrineCommonEventManager->dispatchEvent()

#2 /app/libs/vendor/doctrine/orm/src/UnitOfWork.php(1120): DoctrineORMEventListenersInvoker->invoke()

#3 /app/libs/vendor/doctrine/orm/src/UnitOfWork.php(404): DoctrineORMUnitOfWork->executeUpdates()

how do I populate a php generated html table with 2 (or more) Mysql select statements

new to php and MYSQL,and would like some help, so please be gentle
I have some code which populates a HTML table using php echo.
The statement is:

$query= "SELECT Distinct AgeGrp, Gender,Dist, Stroke, First, 
                Family, Name, Year, Time, Event, Date 
        FROM JLSSWIMMING1 
        WHERE Year = '7'  
        and Stroke = 'Freestyle'" ;  

I would like to add more select statements, then display the results in the same html table e.g.

$query2= "SELECT Distinct AgeGrp, Gender,Dist, Stroke, First, 
                Family, Name, Year, Time, Event, Date 
          FROM JLSSWIMMING1 
          WHERE Year = '7'  
          and Stroke = 'Backstroke'" ;

Thanks in advance

From research it look like I may need an array, (not a join), but I am struggling at this point.
Here is my current code:

<?php

    try {
        $pdo = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $query= "SELECT Distinct AgeGrp, Gender,Dist, Stroke, First, 
                        Family, Name, Year, Time, Event, Date 
                FROM JLSSWIMMING1 
                WHERE Year = '7'  
                and Stroke = 'Freestyle'" ;  

        $stmt = $pdo->prepare($query);     
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (count($result) > 0) {
            echo "<br>";
            echo '<table class="special-table">';
            echo '<thead class="fixed-header">';
            echo '<tr>
                <th>Pos.</th>
                <th class="left-align">Name</th>
                <th class="left-align">Stroke</th>
                <th>Yr</th>
                <th>Dist</th>
                <th>Time</th>
                <th>AgeGrp</th>
                <th>Gen.</th>
                <th>DAte</th>
                <th>Event</th>
                </tr></thead><tbody>';
                
                foreach ($result as $row) {
                    echo "<tr>
                            <td >" . $cnt++ ."</td>
                            <td class='left-align'>" . $row["Name"] . "</td>
                            <td class='left-align'>" . $row["Stroke"] . "</td>
                            <td >" . $row["Year"] . "</td>
                            <td >" . $row["Dist"] . "</td>
                            <td >" . $row["Time"] . "</td>
                            <td >" . $row["AgeGrp"] . "</td>
                            <td >" . $row["Gender"] . "</td>
                            <td >" . Date('d-m-y', strtotime($row['Date'])) . "</td>
                            <td >" . $row["Event"] . "</td>
                        </tr>";
                }
                echo "</table></div>";
          } else {
                echo "<br>";
                echo "<br>";
                echo "<div style='font-size: 42px;'>  No results found ";
        }
    } catch (PDOException $e) {
        die("Connection failed: " . $e->getMessage());
    }
    // Close the database connection
    $pdo = null;
?>

Filter the output of a select2_from_ajax field depending on another field in crud Backpack Laravel

I have two fields

public function setupCreateOperation()
{
    ...
    $this->crud->addFields([
        [
            'name'    => 'status',
            'label'   => trans($this->trans_prefix . 'status'),
            'type'    => 'select_from_array',
            'options' => [
                0 => 'one',
                1 => 'two'
            ],
        ],
        [
            'name'                    => 'service_id',
            'label'                   => trans($this->trans_prefix . 'service'),
            'type'                    => 'select2_from_ajax',
            'entity'                  => 'service',
            'method'                  => 'post',
            'data_source'             => url('fetch/service'),
            'minimum_input_length'    => 0,
        ]
    ]);
}

Can I somehow filter the output of the service_id field depending on the status parameter?
Currently my search function looks like this

public function fetchService()
{
    return $this->fetch([
        'model'                 => Service::class,
        'searchable_attributes' => ['name'],
        'paginate'              => 10,
        'query'                 => function ($model) {
            $search = request()->input('q') ?? false;

            if ($search) {
                return $model->where('name', 'like', "%$search%");
            } else {
                return $model;
            }
        }
    ]);
}

It would be great to somehow pass the status parameter to the function fetchService().
Then the queries would look something like this

'query' => function ($model) {
    $search = request()->input('q') ?? false;
    
    $status_param = $this->crud('status'); // something like this

    if ($search) {
        return $model->where('name', 'like', "%$search%")->where('status', $status_param);
    } else {
        return $model->where('status', $status_param);
    }
}

Symfony 7 MapRequestPayload nested DTOs

I want to parse JSON Requests into nested DTOs with MapRequestPayload. The goal is to have the data into the DTOs validated.

Example JSON:

{
    "meta": {
        "locale": "ger",
        "validateOnly": false
    },
    "content": {
        "firstName": "firstName",
        "lastName": "lastName",
        "displayMode": "system",
        "favoriteMandates": [
            {
                "mandateId": "{{mandateId}}",
                "position": 0
            }
        ]
    }
}

“meta” always contains the same set of data, while content varies depending on endpoint.

My first approach was something like this:

use SymfonyComponentValidatorConstraints as Assert;
final class UpdateUserRequestDTO 
{
    public function __construct(
        #[AssertValid] public Meta $meta,
        #[AssertValid] public UpdateUserDTO $content,
    )
    {}
}
use SymfonyComponentValidatorConstraints as Assert;
use CustomConstrains;

final readonly class UpdateUserSettingsDto
{
    public Name $name;
    public FavoriteMandatesCollection $favoriteMandates;

    public function __construct(
        string $firstName,
        string $lastName,
        #[AssertIsArray] array $favoriteMandates,
        #[CustomConstrainsIsEnumValue(DisplayModeEnum::class)] string $displayMode,
    ) {
        $this->name = Name::fromStrings($firstName, $lastName);
        $this->favoriteMandates = FavoriteMandatesCollection::fromInputArray($favoriteMandates);
        $this->displayMode = DisplayModeEnum::fromString($displayMode);

    }
}

The problem is that this would mean 2 Classes per endpoint where the difference between the requestDTO classes is just the type for $content. While this most likely would work it feels kinda dirty, especially if the project grows bigger.

My second approach was then defining $content as array (which would only 1 reusable requestDTO) and then calling the constructor with $dto = new UpdateUserSettingsDto(...$content) at this approach I seem to have missed something, since the constrains aren’t checked.

Efficient bulk data insertion (2.5 lakh records) in Laravel without exceeding PHP time limit? (Queue, multi-tenancy)

I’m encountering a PHP execution time error while inserting approximately 2.5 lakh records into a MySQL database using Laravel Eloquent. I’m aiming to achieve this without increasing the overall execution time, considering the following constraints:

  1. Frontend: Angular
  2. Multi-tenancy: Implemented using
    https://tenancyforlaravel.com/
  3. Attempted solutions: Laravel Queue

How to optimize CPU usage and memory consumption when generating large CSV files using Node.js and Sequelize?

I’m developing a Node.js application that generates CSV reports from data fetched using Sequelize from a PostgreSQL database. While the solution works well for smaller datasets, CPU usage spikes to 100% and memory consumption increases significantly when generating CSV files containing more than 100k records.

Here’s a simplified version of the function responsible for creating the CSV report:

exports.createReport= (fileName, filePath, response) => {
    return new Promise((resolve, reject) => {
        const ws = fs.createWriteStream(filePath);

        const totalCount = response.count;

        ws.on('error', (error) => {
            reject(error);
        });

        response.rows.forEach(row => {
            let temp1 = JSON.stringify(row.dataValues.offer_details);
            row.dataValues.offer_details = tempOfferDetails;

            let temp2 = JSON.stringify(row.dataValues.allowances);
            row.dataValues.allowances = tempAllowances;

            let temp3 = JSON.stringify(row.dataValues.failure_reason);
            row.dataValues.failure_reason = tempFailureReason;
        });

        const csvStream = fastcsv
            .format({ headers: true })
            .on('end', () => {
                console.log("CSV writing complete");
                resolve({
                    'fileName': fileName,
                    'filePath': filePath,
                    'totalRows': totalCount
                });
            });

        response.rows.forEach(row => {
            csvStream.write(row.dataValues);
        });

        csvStream.pipe(ws);
    });
}

However, this approach becomes inefficient for larger datasets, causing CPU usage to hit 100% and memory consumption to increase significantly. What optimizations can I implement to improve the performance of CSV generation, especially for datasets exceeding 100k records?

Any suggestions/solutions/approaches would be greatly appreciated. Thank you!

the above works fine on locally even records reaches a million but am using a microservice architecture and php is getting the file from Nodejs . That also works fine for records under 100k. Nodejs app is deployed on K PODS and using console and logging i have seen that when we get records more than 100k then our sequlize query get success but after that it wont console anything in file function and does not throw error but CPU suddenly becomes 100%

I have also checked nginx timeout and also file size limitation they are all ok

How to setup laravel in docker at production server

My docker-compose.yml file

version: '3'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
      args:
        user: testuser
        uid: 1000
    container_name: test-app
    restart: unless-stopped
    volumes:
      - ./:/var/www
    networks:
      - default

  nginx:
    image: nginx:alpine
    container_name: test-nginx
    restart: unless-stopped
    volumes:
      - ./:/var/www
      - ./docker-compose/nginx:/etc/nginx/conf.d/
    ports:
      - 8000:80
    networks:
      - default

networks:
  default:
    driver: bridge

1.I already have a database in DigitalOcean, so I want to connect it to this database.
2.Then how to setup this application on production server

Is adding ‘readonly’ to a DirectInjection service (in Symfony) useful? [duplicate]

In Symfony you can inject services into the controller and use them. I get the suggestion that the properties can be readonly. Please see the follow two examples:

class ExampleAController
{
    public function __construct(
        private FooService $fooService,
        private BarService $barService,
    ){}
}

class ExampleBController
{
    public function __construct(
        private readonly FooService $fooService,
        private readonly BarService $barService,
    ){}
}

Are there any realworld advantages/disadvantages to adding readonly here?

Adding readonly ensures it doesnt change and helps protect the code from unwanted changes, but in the case if a service, which often has its own dependencies, rewriting the property will be a lot or work and will not go unnoticed in any way.

To be clear, I’m specifically talking about services. If, for example, you inject a private readonly string $apiKey I can see somewhat of a benefit.

mysqli_connect_error() not working to show errror

<?php 
echo "Welcome to the stage where we are ready to get connected to a database <br>";

// connecting to the Database
$servername = "localhost";
$username = "root";
$password = "hh";

// create a connection
$conn = mysqli_connect($servername, $username, $password);

// die if connection is unsuccessful
if (!$conn) {
    die("Sorry we failed to connect: ". mysqli_connect_error());;
} else {
    echo "Connection was successful";
}
?>

so in this code when i enter the wrong password (it is suppose to be empty) it is suppose to show the “Sorry we failed to connect: ” and then followed by the error.
but instead i get the fatal error message insteadenter image description here

Issue with CreatePassengerNameRecord API

`I’m passing the correct Amountspecified value (603.53) to CreatePNR API but as response i’m getting below error. I’m attaching the AirPrice array which i have received from the CreatePassengerNameRecord API response.

{
            "type": "BusinessLogic",
            "timeStamp": "2024-02-29T08:52:02.818Z",
            "SystemSpecificResults": [
              {
                "Message": [
                  {
                    "code": "WARN.SP.BUSINESS_ERROR",
                    "content": "EnhancedAirBookRQ: Price comparison AmountReturned "603.53" is over the specified limit for .../OTA_AirPriceRQ[1]/PriceComparison"
                  }
                ]
              }
            ]
          }
"AirPrice": [
        {
          "PriceComparison": {
            "AmountReturned": "603.53",
            "AmountSpecified": "603.52999999999997"
          },
         
        }
      ]

Anyone know that why Amountspecified value dispaly as decimal value in PNR response?`

Get bitcoin price from the new coinmarketcap api [duplicate]

I have this code to access the api and turn in into an array

`

    $parameters = [
      'convert' => 'USD',
      'symbol' => 'BTC,XMR',
      'aux' => 'is_fiat'
    ];
    
    $headers = [
      'Accepts: application/json',
      'X-CMC_PRO_API_KEY: xxx'
    ];
    $qs = http_build_query($parameters); // query string encode the parameters
    $request = "{$url}?{$qs}"; // create the request URL
    
    
    $curl = curl_init(); // Get cURL resource
    // Set cURL options
    curl_setopt_array($curl, array(
      CURLOPT_URL => $request,            // set the request URL
      CURLOPT_HTTPHEADER => $headers,     // set the headers 
      CURLOPT_RETURNTRANSFER => 1         // ask for raw response instead of bool
    ));
    
    $response = curl_exec($curl); // Send the request, save the response
    print_r(json_decode($response)); // print json decoded response
    $array = get_object_vars(json_decode($response));
    $decoded_json = json_decode($response, TRUE);
    curl_close($curl); // Close request  
    echo '<pre>'; print_r($array); echo '</pre>';  

This is the output

Array
(
    [status] => stdClass Object
        (
            [timestamp] => 2024-02-29T09:51:16.590Z
            [error_code] => 0
            [error_message] => 
            [elapsed] => 17
            [credit_count] => 1
            [notice] => 
        )

    [data] => stdClass Object
        (
            [BTC] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 1
                            [name] => Bitcoin
                            [symbol] => BTC
                            [slug] => bitcoin
                            [infinite_supply] => 
                            [is_fiat] => 0
                            [self_reported_circulating_supply] => 
                            [self_reported_market_cap] => 
                            [tvl_ratio] => 
                            [last_updated] => 2024-02-29T09:50:00.000Z
                            [quote] => stdClass Object
                                (
                                    [USD] => stdClass Object
                                        (
                                            [price] => 62565.521930099
                                            [volume_24h] => 91758833391.577
                                            [volume_change_24h] => 101.4421
                                            [percent_change_1h] => -0.15773114
                                            [percent_change_24h] => 5.45946662
                                            [percent_change_7d] => 20.44854353
                                            [percent_change_30d] => 44.17944122
                                            [percent_change_60d] => 46.45120123
                                            [percent_change_90d] => 61.85312782
                                            [market_cap] => 1228830646572.5
                                            [market_cap_dominance] => 52.9737
                                            [fully_diluted_market_cap] => 1313875960532.1
                                            [tvl] => 
                                            [last_updated] => 2024-02-29T09:50:00.000Z
                                        )

                                )

                        )

                )

            [XMR] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 328
                            [name] => Monero
                            [symbol] => XMR
                            [slug] => monero
                            [infinite_supply] => 1
                            [is_fiat] => 0
                            [self_reported_circulating_supply] => 
                            [self_reported_market_cap] => 
                            [tvl_ratio] => 
                            [last_updated] => 2024-02-29T09:50:00.000Z
                            [quote] => stdClass Object
                                (
                                    [USD] => stdClass Object
                                        (
                                            [price] => 140.09858558716
                                            [volume_24h] => 72409439.318754
                                            [volume_change_24h] => 25.6254
                                            [percent_change_1h] => 2.04702992
                                            [percent_change_24h] => 1.91404701
                                            [percent_change_7d] => 13.25468147
                                            [percent_change_30d] => -16.42126433
                                            [percent_change_60d] => -15.56793655
                                            [percent_change_90d] => -17.98997717
                                            [market_cap] => 2578373000.537
                                            [market_cap_dominance] => 0.1112
                                            [fully_diluted_market_cap] => 2578373000.54
                                            [tvl] => 
                                            [last_updated] => 2024-02-29T09:50:00.000Z
                                        )

                                )

                        )

                )

        )

)

I only need to access the [price] and convert it into two variables, one for each coin.

I havent had any luck doing so thus far.

I expect variables for bitcoin price and monero price.

Im not able to access the value itself by myself.

In Amaedeus Wsdl How to make flight issue and payment same time in laravel(php)

So Amaedeus Provide issue ticket and payment in same time if issue ticket filed payment also not recive and if payment fail then no issueing ticket example I Had make flight booking system.I use paypal paymen now what I do first I recept payment throw paypal and issue ticket now what I want receve payment and issue ticket in same time.If issuing ticket failed then payment does not recept
i need code in php to manage such things