WP all import duplicate product id’s and schedule sale on week

I have an import using WP ALL-IMPORT where the xml looks like this.

<ROW artnum="53241" klant="-1" week="35" dag="0" jaar="2024" klantgroep="0" advprijs="2.95" artorg="3.2" artbtw="9"/>
<ROW artnum="53241" klant="-1" week="36" dag="0" jaar="2024" klantgroep="0" advprijs="2.95" artorg="3.2" artbtw="9"/>
<ROW artnum="53241" klant="-1" week="37" dag="0" jaar="2024" klantgroep="0" advprijs="2.95" artorg="3.2" artbtw="9"/>
<ROW artnum="54137" klant="-1" week="35" dag="0" jaar="2024" klantgroep="0" advprijs="2.95" artorg="3.1" artbtw="9"/>
<ROW artnum="54137" klant="-1" week="36" dag="0" jaar="2024" klantgroep="0" advprijs="2.95" artorg="3.1" artbtw="9"/>
<ROW artnum="54137" klant="-1" week="37" dag="0" jaar="2024" klantgroep="0" advprijs="2.95" artorg="3.1" artbtw="9"/>

artnum = product_ID

Week is the week the product is on sale
For example week 37 = ‘2024-09-09 to 2024-09-15’

I created a function to get the start date and the end date. it looks like this.

function get_current_year_week_start_date($week) {
    // Get the current year
    $year = date('Y');
    
    // Create a new DateTime object
    $dto = new DateTime();
    
    // Set the DateTime object to the start of the specified week in the current year
    $dto->setISODate($year, $week);
    
    // Return the start date of the week
    return $dto->format('Y-m-d');
}

So the problem now is that the import for product id 54137 is happening 3 times so it overwrites the data so the sale is only on week 37 and not from 35 to 37.

Is there a way to see in the import wich value is lower? or will it be better to skip already imported product_ids and only import the lowest week number?

Unable to save data using HasOne association in Cakephp 4

I have tried to join two tables using hasOne association in my cakephp app
There are two tables users and admin. In both tables the id is primary key. i have linked the mobile field of admin to the add users table. So by hasOne association the user added in user table is supposed to be linked to admin and get added in admin table too. But i am unable to enter the user as an error is occuring

Here is the table structures

user tableenter image description here

admin table
enter image description here

Here is the code of add page of the user template. It is the page to enter users

<?php
/**
 * @var AppViewAppView $this
 * @var AppModelEntityUser $user
 */
?>
<div class="row">
    <aside class="column">
        <div class="side-nav">
            <h4 class="heading"><?= __('Actions') ?></h4>
            <?= $this->Html->link(__('List Users'), ['action' => 'index'], ['class' => 'side-nav-item']) ?>
        </div>
    </aside>
    <div class="column-responsive column-80">
        <div class="users form content">
            <?= $this->Form->create($user  , ['type'=> 'file']) ?>
            <fieldset>
                <legend><?= __('Add User') ?></legend>
                <?php
                    echo $this->Form->control('email');
                    echo $this->Form->control('password');
                    echo $this->Form->control('Re_enter_password');
                    echo $this->Form->control('admin.mobile');
                    echo $this->Form->control('image' , ['type'=> 'file']);
                ?>
            </fieldset>
            <?= $this->Form->button(__('Submit')) ?>
            <?= $this->Form->end() ?>
        </div>
    </div>
</div>

This is the user file in the Entity folder.I have added the admin = true in the accessible function so that admin will be accessible by user

  protected $_accessible = [
        'email' => true,
        'password' => true,
        'created' => true,
        'modified' => true,
        'articles' => true,
        'admin' => true,
        'status' => true,
        '*' => true,
        'id' => false

    ];

This is the add function in the UserController file. It is used to add new users

public function add()
    {
        $user = $this->Users->newEmptyEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData());

    
           if (!$user->getErrors) {
                $image = $this->request->getUploadedFiles();
                
               $name = $image['image']->getClientFilename();
               

         

               $targetPath = WWW_ROOT.'img'.DS.$name;

                if ($name) {
                   $image['image']->moveTo($targetPath);
                }

                $user->image = $name; 
            } else {
                echo "Error uploading" ;
                echo $user->getErrors;
            }


            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.')); 
        }
        $this->set(compact('user'));
       
    }

This is the Users table file where i have defined the HasOne relation

 public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('users');
        $this->setDisplayField('email');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

        $this->hasMany('Articles', [
            'foreignKey' => 'user_id',
        ]);

        $this->hasOne('Admin');
    }

I hashed my password using this PHP function, and everything looks fine in the database, but I cannot log in [duplicate]

I hashed my password using this PHP function,

$hashed_password = password_hash($password, PASSWORD_BCRYPT);

and everything looks fine in the database, but I cannot log in.

I tried this code for login but it won’t work

<?php require_once 'db.php'; 

// step 1 form submission check
if($_SERVER['REQUEST_METHOD'] == "POST"){

    // step 2 input validation
    $username = htmlspecialchars($_POST['username']);
    $password = htmlspecialchars($_POST['password']);

    if(empty($username) || empty($password) ){
        header('Location: login.php?message=Both Fields Are Required');
        exit();
    }else{
        // step 3 Database Query
        $stmt = $conn->prepare("SELECT * FROM mismatch_user WHERE username = :username");
        $stmt->bindParam(':username', $username);
        $stmt->execute();

        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        // step 4 Authentication
        if (password_verify($password, $result['password'])) {
            session_start();
            $_SESSION['username'] = $username;

            header("Location: index.php");
            exit();
        }else{
            header("Location: login.php?message=Invalid Username or Password");
            exit();
        }
    }
}
?>

php artisan l5-swagger:generate

enter image description here

l5-swagger in config file
'annotations' => [ base_path(‘app/Swagger’), // You should add this line to work
base_path(‘app/’), ],
add but don’t work why
Most commonly this manifests with a warning about the required @OAInfo not being found. While most annotations have specific related code, the info annotation (and a few more) is kind of global.

The simplest solution to avoid this issue is to add a ‘dummy‘ class to the docblock and add all ‘global‘ annotations (e.g. Tag, Server, SecurityScheme, etc.) in a single docblock to that class.

How do I echo get_post_meta, wrapped with an HTML tag?

I’m hoping someone can help. I have a custom field for WooCommerce products but I need to wrap the output in an HTML tag.

Please could someone help correct this?

I know it’s not the correct syntax, but this is what I have tried to do and hopefully you can see what I’m trying to achieve:

echo '<p> get_post_meta( get_the_ID(), '_textarea', true ) </p>';

Image not loaded in Gmail when sent via Custom Laravel App

I was making a clone to the famous service ZOHO Mail in Laravel. I made a simple mailer client that sends emails to provided users’ email addresses. I am using Gmail SMTP.
Now there is thing in ZOHO Mail client that offers brief analytics for each sent email using their service. These analytics included a count for “Times Opened” (not called exactly this, but to get the gist) for each email. I dug down the logic behind how it works, and found out that my app must send a 1by1 Pixel invisible image in the Email body itself, and when the pixel is loaded, you record it in the server (since it is being loaded from the server). So this way, whenever anyone opens the recieved email, the pixel gets loaded and i get a record in the database.
Here is the code for appending the TrackingPixel with the body,

$emailId = uniqid();
$trackingPixel = '<img src="' . route('tracking.pixel', ['id' => $emailId]) . '" width="1" height="1" style="display:block;" alt="" title="" />';
$bodyWithPixel = $request->body . $trackingPixel;

First thing is that when it is recieved in the email, it looks like this,

<img src=3D"http://127.0.0.1:8000/tracking-pixel/66d03=d818509c" width=3D"1" height=3D"1" style=3D"display:block;" alt=3D"" title==3D"" />

What even is this 3D, and the second this is that the image is not being loaded in the email. I don’t know if it is becuase of this 3D or something else.
I researched it, and found out that Google doesn’t allow loading images from unknown sites/links (I am using LocalHost for now). Maybe this could be the reason, but anyone could tell a way around this problem?

$emailId = uniqid();
$trackingPixel = '<img src="' . route('tracking.pixel', ['id' => $emailId]) . '" width="1" height="1" style="display:block;" alt="" title="" />';
$bodyWithPixel = $request->body . $trackingPixel;

a pixel image loaded in the email body, but there is no image being loaded there.
Any other way that i can implement to record the email being opened?

Sending Laravel logs to stdout and Telescope error

I’m trying to use https://stackoverflow.com/a/46767123/499915 workaround for sending logs from Laravel Scheduler jobs to stdout. In fact, it’s just using a symlink like
ln -sf /proc/1/fd/1 /var/log/laravel-scheduler.log

This works nice, but Telescope module doesn’t like this symlink, it fails with

Failed to open stream: No such file or directory {"exception":"[object] (ErrorException(code: 0): file_get_contents(/var/www/logs/laravel-scheduler.log): Failed to open stream: No such file or directory at /var/www/vendor/laravel/telescope/src/Watchers/ScheduleWatcher.php:68)"}

Is there a way to eliminate this error?

Is there a way to unbind a route’s name with a middleware?

In Laravel 10, I’ve noticed that routes with a name that start with ‘api.’ are automatically under the ‘api’ middleware group defined in the Kernel.php file.

I need to make an API route but I don’t want to link it to the ‘api’ middleware group.

Is there a way to undo this link?

I’ve tried to change the name of the route I’m trying to make, and it didn’t get registered under the ‘api’ middleware group. However, whatever I do to the group, it doesn’t do anything and I didn’t find anyone mentioning this phenomena.

PHP MYSQL FETCH ASSOC Everytime I Refresh The Website, It Returns The Last Row Of The Database [duplicate]

So I am new at php and i am trying to send data from my form to phpmyadmin and get it back. Sending part is okay. But everytime i refresh the site, it adds the variables at the last array to where i want to show the variables to user.

It goes on like this: I add a variable from post method. It writes it down. Then i refresh the site. It writes that variable again. At the end. And again.

<?php
$connection = new mysqli($servername,$username,$password,$dbname);
$name_entry=$_POST['item_name'];
$size_entry=$_POST['item_size'];

$entry = "INSERT INTO dbitem(isim,boyut) VALUES('$name_entry','$size_entry')";
$getdata="SELECT * FROM dbitem ORDER BY id";
$datagot=$connection->query($getdata);

if($connection->connect_error){
die("ERROR"); } if($name_entry&&$size_entry&&$connection->query($entry)){}
?>

<form action="VeriDondur.php" method="post">
    <p>Eşyanın İsmi:</p>
    <input type="text" name='item_name'>
    <p>Eşyanın Boyutu:</p>
    <input type="text" name='item_size'>
    <input type="submit" name="submit" value="Yükle">
</form>
if($datagot->num_rows>0)
{ while($row = $datagot->fetch_assoc())
{ echo  $row['isim'] ." ". $row['boyut'] . "n"; } 
} 
?>

I tried to add $connection->close(); at end of the code but that didnt to anything

Configure Apache2 to host REST API

Since I want to learn more around hosting a REST API and also development of such (with PHP) I am wondering about the following:
I’ve got my API files in the path /var/myapi and configured the directory like this:

<Directory /var/myapi>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

The Virtual Host is configured like this:

<VirtualHost *:8080>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/myapi/
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

In my api directory I want to have the index.php is my router. So, the $_SERVER["REQUEST_URI"] should contain the full path the client is requesting.

Unfortunately, when accessing http://localhost:8080/books the path /books will be handled by apache which is trying to find a file in /var/msapi/books. The path “/books` will not be reflected within my routers PHP code.

I think I somehow need to change settings in Apache but do not know what to look for. Any advice?

Delete all entrys if checkbox is checked

I have created a form that displays a list of database entries. There is a checkbox for each value. When I check the checkbox, I want to delete this entry.

My form class looks like this:

//Räume auslesen
        $rooms = $DB->get_records_sql( 'SELECT LBTB.id, LBTB.datum, LBTB.roomid, LBTB.ustd, LBTB.userid, RAUM.raumname, RAUM.raumnummer FROM {bs_steinweg} LBTB
        LEFT JOIN {bs_raume} RAUM
        ON LBTB.roomid = RAUM.id
        WHERE roomid > "0"
        ');

        foreach ($rooms as $room) {
            $newdate = date( 'd.m.Y', strtotime( $room->datum ) );
            $mform->addElement('html', '<tr><th scope="row">');
            $mform->addElement('advcheckbox', 'roomid[]','','','', $room->id);
            $mform->addElement('html', '</th><td>');
            $mform->addElement("html", "$room->raumname");
            $mform->addElement('html', '</td><td>');
            $mform->addElement("html", "$newdate");
            $mform->addElement('html', '</td><td>');
            $mform->addElement("html", "$room->ustd");
            $mform->addElement('html', '</td></tr>');
            $mform->addElement('hidden', 'id', $room->id);
            $mform->setType('id', PARAM_INT);
        }

I try to delete the data like this:

if ( !empty( $fromform->delete ) ) {
        if ( !empty( $fromform->roomid ) ) {
            foreach ( $fromform->roomid as $room_id ) {
                print_r($fromform->id);
                /* $DB->delete_records( 'bs_steinweg', [ 'id' => $room_id ] ); */
            }
            /* $getDeleteCanceld = get_string( 'getDeleteCanceld', 'local_buchungssystem' );
            redirect( $CFG->wwwroot . '/local/buchungssystem/meine_fach_buchungen_sw.php', $getDeleteCanceld ); */
        } else {
            // Handle the case where no rooms were selected.
            $getDeleteCanceld = get_string( 'noRoomsSelected', 'local_buchungssystem' );
            redirect( $CFG->wwwroot . '/local/buchungssystem/meine_fach_buchungen_sw.php', $getDeleteCanceld );
        }
    }

The output with print_r($room_id) does not give me any value.

The output with print_r($fromform->id) only gives me the last value. Even if I select the first value, it always gives me the last ID.

Counting the whole thing up with a for loop also doesn’t output any value. It doesn’t matter whether I output print_r($room_id) or print_r($fromform->id):

if ( !empty( $fromform->delete ) ) {
        if ( !empty( $fromform->roomid ) ) {
            foreach ( $fromform->roomid as $room_id ) {
                for ( $i = 0; $i <= $room_id; $i++ ) {
                print_r($room_id);
                }
                /* $DB->delete_records( 'bs_steinweg', [ 'id' => $room_id ] ); */
            }
            /* $getDeleteCanceld = get_string( 'getDeleteCanceld', 'local_buchungssystem' );
            redirect( $CFG->wwwroot . '/local/buchungssystem/meine_fach_buchungen_sw.php', $getDeleteCanceld ); */
        } else {
            // Handle the case where no rooms were selected.
            $getDeleteCanceld = get_string( 'noRoomsSelected', 'local_buchungssystem' );
            redirect( $CFG->wwwroot . '/local/buchungssystem/meine_fach_buchungen_sw.php', $getDeleteCanceld );
        }
    }

PHP Swoole websocket coroutine notification server

I made coroutine-based WebSocket server https://wiki.swoole.com/en/#/coroutine/ws_server
And now i want create a notification service. While websocket server has any connected clients it check some data in DB and than send that info to clients.
But if i add some like that:

          while (!!$wsObjects) {
              sleep(1);
              $ws->push(json_encode($stmt->fetchAll()));
            }

loop stay infinite and i can`t close any connections https://wiki.swoole.com/en/#/getting_started/notice?id=the-impact-of-while-loop

How can i made notification service with swoole websocket coroutine notification server?

Show data from 2 table in laravel 11x

I can input data into 2 different tables, namely the question table and the answer table. But I have difficulty displaying the data according to each id_question. I have tried it but all the data in the answer table is displayed.

This is some example data for each Table.

question

Id question
1 The correct answer is
2 How old is Ani?

answer

Id id_question answer
1 1 give
2 1 given
3 1 gave
4 1 gain
5 2 8 years old
6 2 9 years old
7 2 10 years old
8 2 11 years old

And this is my controller:

public function question Dashboard(){
     $questions = Question::with('answers')->get();
     $answers = Answer::with('questions')->get();
     return view('admin.questionDashboard', ([`questions`=>$questions, `answers`=>$answers]));
}

Remove duplicated from multidimensional array

Have an array with this expression $products[] = $product[$category_id][$product_id]:

$products = array(
    33 => array(
        31 => array(
            'model' => 'Product 4',
            'product_id' => 31,
            'sku' => '',
            'ean' => '1234',
            'price' => '80.0000'
        ),
        8733 => array(
            'model' => 'qqq',
            'product_id' => 8733,
            'sku' => '',
            'ean' => '1000',
            'price' => '344.6281'
        )
    ),
    25 => array(
        30 => array(
            'model' => 'Product 3',
            'product_id' => 30,
            'sku' => '',
            'ean' => '250',
            'price' => '50.4132'
        ),
        31 => array(
            'model' => 'Product 4',
            'product_id' => 31,
            'sku' => '',
            'ean' => '1234',
            'price' => '80.0000'
        )
    )
);

I need remove duplicated product in php and result must be:

$products = array(
    33 => array(
        8733 => array(
            'model' => 'qqq',
            'product_id' => 8733,
            'sku' => '',
            'ean' => '1000',
            'price' => '344.6281'
        )
    ),
    25 => array(
        30 => array(
            'model' => 'Product 3',
            'product_id' => 30,
            'sku' => '',
            'ean' => '250',
            'price' => '50.4132'
        ),
        31 => array(
            'model' => 'Product 4',
            'product_id' => 31,
            'sku' => '',
            'ean' => '1234',
            'price' => '80.0000'
        ),
    )
);

I have tried this:

$cleared_products = array();

        foreach ($products as $category_id => $category_products) {
            foreach ($category_products as $product_id => $product) {
                if (isset($cleared_products[$category_id][$product_id])) {
                    
                    unset($products[$category_id][$product_id]);
                } else {
                    
                    $cleared_products[$category_id][$product_id] = $product;
                }
            }
        }

But does not work…

Laravel unit test not running as expected?

I’m trying to test an endpoint which returns the user with the most tickets.

Its failing… always returning user 20 as the popular one? I’m not understanding how user 20 even exists if I’m only making 15 tickets? Laravel is clearly doing something behind the scenes like remembering live data.

Test:

class StatisticsTest extends TestCase
{
    use RefreshDatabase;

    public function test_most_popular_user(): void
    {
        Ticket::factory()
            ->count(15)
            ->create();

        $userId = User::query()->max('id');

        Ticket::query()
            ->update(['user_id' => $userId]);

        $response = $this->get('/stats');

        error_log('OUTPUT: ' . $response->getContent());

        $response->assertStatus(200);
        $response->assertJsonIsArray('popularUser');

        $this->assertEquals($userId, $response['popularUser']['id']);
    }
}