How to prevent duplicate files in Subfolders – Laravel?

I created a add view where multiple files can be upload at same time :
View
The file path when file will be uploaded is like – Drawings/PartNumber/Type/filename.extension
How can I check in Drawing Folder any file cant not be same with extension like

  1. Drawings/PartNumber1/Type1/filename1.pdf
  2. Drawings/PartNumber2/Type2/filename1.pdf
  3. Drawings/PartNumber1/Type3/filename1.pdf
  4. Drawings/PartNumber1/filename1.pdf
  5. Drawings/filename1.pdf
    never will be accepted.

My function is :

public function AddNewPart(Request $request)
    {
if (array_key_exists('DrawingFile',$data)) {
                foreach($request->file('DrawingFile') as $key=>$file)
                {
                    if ($data['fileupload_ID'][$key]==NULL) {
                        $extension=$file->getClientOriginalExtension();
                        $file_name2 = $file->getClientOriginalName();
                        $filepath='Drawings/'.$data['PartNumber'].'/'.$data['Type'][$key].'/'.$file_name2;
                        $file->move(public_path('Drawings/'.$data['PartNumber'].'/'.$data['Type'][$key].'/'), $file_name2);
                        $DocumentData2=array('Type'=>$data['Type'][$key],'fcontent'=>$file_name2,'condpartno'=>$data['PartNumber'],'fname'=>$filepath,
                        'DrawingNo'=>$data['DrawingNo'][$key],'DocumentType'=>$data['Type'][$key]);
                        DB::table('fileupload')->insert($DocumentData2);
                    }
                }
            }
    }

How to change woocommerce catalog ordering for certain products conditionally?

I am using the following function to order woocommerce products on product category pages:

add_filter('woocommerce_get_catalog_ordering_args', function($args){

if ( !is_product_category() ) return $args;

set_query_var('meta_query',[
    'relation' => 'AND',
    'stock_status_clause' => [ 'key' => '_stock_status','type' => 'CHAR' ],
    'price_clause' => [ 'key' => '_price', 'type' => 'NUMERIC'],
    'custom_cat_rank_clause' => [ 'key' => '_custom_cat_rank', 'type' => 'NUMERIC']
  ]);
  
    
    //https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters
    $args["orderby"] = ['stock_status_clause' => 'ASC', 'price_clause' => 'ASC', 'title' => 'ASC', 'custom_cat_rank_clause' => 'ASC' ];
   
    return $args;

},100);  

On certain categories and for certain products, I want to change _custom_cat_rank value for the product. For example – if _custom_cat_rank is set as 2 for a product in wp_postmeta table, I want it to be changed to 1 on certain category pages conditionally without having to change it in the database so that the product ranking on those category pages is modified. This will enable product ranking modification conditionally on a per product basis. How to do this?

Could not find a pgsql driver when I try to run command “php artisan migrate” [duplicate]

These are my database data which are stored in .env file

DB_CONNECTION=pgsql
DB_HOST=myDB
DB_PORT=5432
DB_DATABASE=stuff
DB_USERNAME=myusername
DB_PASSWORD=mypassword

When I try to run php artisan migrate in cmd. For starter, I’ve already added extension=pgsql and extension=pgsql.so in php.ini file located in C:xamppphp. There is an error such,

could not find driver (Connection: pgsql, SQL: select * from information_schema.tables where table_catalog = myDB and table_schema = public and table_name = migrations and table_type = 'BASE TABLE')

I’ve already installed postgresql, laravel, composer, xaamp. I’ve already added extension=pgsql and extension=pgsql.so in php.ini file.

AWS Elastic Beanstalk with PHP 8.0 (64bit Amazon Linux 2/3.3.15) more than 2 mb file uploads are stopped suddenly

The application was developed in Laravel 8, One of my client applications suddenly stopped uploading more than 2 MB of files. I have checked the Nginx configuration is fine.

The client_max_body_size value is 50M.

I have used this structure to update the configuration “platform/nginx/conf.d/proxy.conf file”

And also applied the Nginx reload too.

How can I change my URL address in the WordPress site?

I have a WordPress site and the URL of the site is “http://example.com/example/”. I have used WordPress themes and pages to set the website up. But now I want to change this URL to just show the homepage as “http://example.com” and the other site pages as “http://example.com/”.

How can I achieve this in my WordPress site?

I want to change this URL to just show the homepage as “http://example.com” and the other site pages as “http://example.com/”.

How can I achieve this in my WordPress site?

undefined artisan method when testing console commands

I have a simple console command that prints ‘Hello, World!’ into the terminal. It’s like this:

<?php

namespace AppConsoleCommands;

use IlluminateConsoleCommand;

class SimpleCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:simple-command';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->line('Hello, World!');
    }
}

and I want to write a unit test for this command

<?php

namespace TestsUnitConsoleCommands;

use PHPUnitFrameworkTestCase;

class SimpleCommandTest extends TestCase
{
    /**
     * Test a console command.
     */
    public function test_console_example(): void
    {
        $this->artisan();
    }
}

But after I ran the test, I got an error says:

Call to undefined method TestsUnitConsoleCommandsSimpleCommandTest::artisan()

I’ve copied codes mostly from the documentation and suprised that they’re not working. Is there anything I’m missing? Or do I need to install some package? Or am I in the wrong namespace or something?

how to display a table from phpmyadmin from a database on an html form and perform add and delete record functions (xampp and php)

how to display a table from phpmyadmin from a database on an html form and perform add and delete record functions (xampp and php)

please write the addRec and deleteRecord in PHP as well as the parentstbl, taking into consideration the following:

  • Name of database: happykids
  • Name of table: parentstbl
  • Attributes of parentsble: ID (int), Name (varchar), Address (varchar), NameOfChild (varchar), Age (Int), Email (varchar), Password (varchar).

There is no username or password for the xampp database.

a form to display the records from the table and be able to add and delete records in the form in an html form

Deceptive site ahead laravel web application from themeforest

we just bought laravel web application from themeforest after upload to hosting, its throw error.

Deceptive site ahead
Attackers on qrsmartserve.com may trick you into doing something dangerous like installing software or revealing your personal information (for example, passwords, phone numbers or credit cards).

its hsould work fine after installing.

Reorder the posts in grid to prioritise those with assigned custom field value – WordPress, WPgridbuilder, ACF

I’m using a WPgridbuilder plugin to create a custom grid together with ACF to add custom fields to the post type.

I’ve got a grid that shows all ‘Books’ (custom post type).

I’m using ACF to add a checkbox field “promos” to the Books post type, here I’ve got a value “new”.

What I’m trying to achieve is to reorder the posts in the grid, so the grid first shows all posts with the selected value “new” and then all other posts in a random order.

This is what I currently have:

function grid_query_include_post_ids( $query_args, $grid_id ) {

    // If it matches grid id 14.
    if ( 14 === $grid_id ) {

                // The grid is also queried during Ajax requests when filtering or rendering facets.
        // So we have to get the ID of the current post/page thanks to the referer.
        $referer = wp_get_referer();
        $post_id = wp_doing_ajax() ? url_to_postid( $referer ) : get_the_ID();

        // Retrieve the 'promos' (or 'field_64c25438d2c3a') value for the current post.
        $promos = get_post_meta( $post_id, 'promos', true );

        // Check if the 'new' value exists in the 'promos' array.
        if ( in_array( 'new', (array) $promos ) ) {

            // Display posts assigned to the custom field value 'new' first.
            $query_args['meta_query'] = array(
                array(
                    'key'     => 'promos',
                    'value'   => '"new"',
                    'compare' => 'LIKE',
                ),
            );

            $query_args['orderby'] = array(
                'meta_value' => 'DESC', // Display 'new' posts first.
                'rand'       => 'ASC',  // Random order for other posts.
            );

        } else {

            // Display all posts in random order.
            $query_args['orderby'] = 'rand'; // Random order.

        }

    }

    return $query_args;
}

add_filter( 'wp_grid_builder/grid/query_args', 'grid_query_include_post_ids', 10, 2 );

The function is based on the official WPgridbuilder query docs here

I can’t seem to make it working. The posts are still showing up in random order regardless of the custom field value.

Any ideas what I’m doing wrong?

is there any solution to hide woocommerce coupon field in cart for some product?

I have problem with woocommerce coupon field. So I need to hide coupon field for some product in woocommerce cart and checkout. After search in google I find code to hide coupon field in 1 product. i Tried it, and it worked well. But for my problem , i wannt 3 or 4 product id hide coupon label too.

How can i modif this code.
Thank you.

// hide coupon field on the checkout page
 
function disable_coupon_field_on_checkout( $enabled ) {
 
    if ( is_checkout() ) {
 
        $product_id = 240790;
        $in_cart = false;
        
        foreach( WC()->cart->get_cart() as $cart_item ) {
 
           $product_in_cart = $cart_item['product_id'];
 
           if ( $product_in_cart === $product_id ) $in_cart = true;
        }
 
        if ( $in_cart === true )
        {
            $enabled = false;
        }
    }
 
    return $enabled;
}
add_filter( 'woocommerce_coupons_enabled', 'disable_coupon_field_on_checkout' );
 
// hide coupon field on the cart page
 
function disable_coupon_field_on_cart( $enabled ) {
 
    if ( is_cart() ) {
 
        $product_id = 240790;
        $in_cart = false;
        
        foreach( WC()->cart->get_cart() as $cart_item ) {
 
           $product_in_cart = $cart_item['product_id'];
 
           if ( $product_in_cart === $product_id ) $in_cart = true;
        }
 
        if ( $in_cart === true )
        {
            $enabled = false;
        }
    }
 
    return $enabled;
}
add_filter( 'woocommerce_coupons_enabled', 'disable_coupon_field_on_cart' );


PHPMySQL – Select the matched row plus next 3 rows followed

Table students has 3 columns id, name, and class.

I want to select the matched row based on the condition for example if the student’s name is Jhon, plus the next 3 rows (without any condition) followed by the match row in just one query.

After research, my code below returns only 1 row, or maybe this is not the way of doing what I want:

SELECT * FROM `students` AS `parent`

INNER JOIN `students` AS `child`

WHERE `parent`.`name` = ? AND `child`.`id` > `parent`.`id`
 
ORDER BY `child`.`id` ASC LIMIT 3

Note: I am using PHP Prepared Statements.

Binding a custom method parameter to a class property

is there any way to bind a class property to a method parameter inside that class so that there is a two way link when you click CTRL + Right click?

class Attachments extends Repository
{
    public Documents $documents;

    public function fromDocuments(callable $scope)
    {
        $this->scopeOnRepoProperty($scope, 'documents');
    }
}

I mean, that in that case second parameter documents in scopeOnRepoProperty() method should refer to property $documents.

The broader context:

The problem for me is that a large part of the code was very analogous, namely, most of the method scopeXXX/fromXXX does something like that, executes the method and sends the property repository to it as a parameter. i.e. in the example above, $scope($this->documents) is executed;
and additionally, if $this->documents is not initialized, a new instance is created.

So it’s look:

public function fromDocuments(callable $scope)
{
    if (!isset($this->documents)) {
        $this->documents = new Documents();
    }
    $scope($this->documents);
}

I wanted to save myself writing an if every time, creating a new object and calling a method, and I came up with the idea that I can do it with one method that will take a callable and the name of this property and from type reflection class name.

The code works fine, unfortunately I lost the bindings to these properties because of this.
In the previous version it was $this->documents, so the link was there, but as it is now it is not.

I am wondering if there is any way I can achieve this. Any ideas?

unexpected character at line 1 column 1 of the JSON data error

It is showing that error when i want to run the fetch-edit.php file in the localhost. It is getting the values from the table and converting it into arrays. but i dont get where could be the problem.

this is fetch-edit.php file code

<?php
include 'config.php';

// Get the record ID from the query parameter
$id = $_GET['id'];

// Use prepared statement to fetch the data based on the ID
$stmt = mysqli_prepare($conn, "SELECT id, Alias, Gruppe, Passwort, Beschreibung FROM teamviews_customers WHERE cid = ?");
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $alias, $group, $pass, $text);
// Fetch the data into an associative array
$data = array();
while (mysqli_stmt_fetch($stmt)) {
    $data = array(
        'id' => $id,
        'alias' => $alias,
        'group' => $group,
        'pass' => $pass,
        'text' => $text
    );
}

mysqli_stmt_close($stmt);
mysqli_close($conn);

// Return the data as JSON
header('Content-Type: application/json');
echo json_encode($data);
?>

and this is the fetch-data.js file code

function editRecord(id) {
    console.log(id);
    let modal_heading = document.getElementById("modal-h4");
    modal_heading.innerHTML = "";
    document.getElementById("myModal").style.display = "block";
    modal_heading.innerHTML = "User Login";
    // if (confirm("Are you sure you want to Edit the record?")) {
    edit(id);
}
// }

// ---------------Edit Record---------------------------
function edit(id) {
    document.getElementById("myForm").addEventListener("submit", function (event) {
        event.preventDefault();

        // Get form data
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;

        fetch('fetch-user.php')
            .then((response) => response.json())
            .then((data) => {
                var username_r = data.user_name;
                var password_r = data.password;
                console.log(username_r);
                console.log(password_r);
                console.log(username);
                console.log(password);

                if (username === username_r && password === password_r) {

                    // Fetch the data of the selected record using the ID (you can fetch this data from the server)
                    fetch('fetch-edit.php?id='+id)
                        .then((response) => response.json())
                        .then((data) => {
                            // Redirect to the "edit-record" page
                            // Populate the form fields with the retrieved data
                            document.getElementById('id').value = data.id;
                            document.getElementById('alias').value = data.alias;
                            document.getElementById('group').value = data.group;
                            document.getElementById('pass').value = data.pass;
                            document.getElementById('text').value = data.text;
                            window.location.href = 'edit-record.php';
                        })
                        .catch((error) => {
                            console.error('An error occurred:', error);
                        });


                } else {
                    alert("NOt Working");
                }

                // Clear the form fields
                document.getElementById("myForm").reset();
            })
            .catch((error) => {
                alert('error Cannot Fetch Data', "Cannot Fetch Data");
                console.error('An error occurred:', error);
                console.error(error.stack);
            });
    }
    )
}

i have tried to check where is the error with F12 key and also read the related text in stackoverflow, but i dont get the problem.

PHP webscraping adjustments [closed]

I have created a script to scrape a website for a school project.

In links.csv there is a overview of all the trips that are offered.”https://www.sawadee.nl/groepsrondreizen/midden-en-zuid-amerika/costa-rica/crh-vakantie-costa-rica-groepsreis/vertrekdata-en-prijzen/”

In this case I have two websites that are interacting. In cell 04-02 there is a departure code that gets added to the following link to supply the website with the number of travellers ”https://www.sawadee.nl/group_compositions/?departure_code=”.

How can I link this data and persue the following steps to complete the module.

Help is appreciated.

I

`<?php
//Require the PhpSpreadsheet library
require('autoload.php');

use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;

// Read the CSV file
$csvFile = 'links.csv';

$data = array();

if (($handle = fopen($csvFile, 'r')) !== false) {
    while (($row = fgetcsv($handle)) !== false) {
        $data[] = $row;
    }
    fclose($handle);
}

$arr = array();

// Display the array
foreach ($data as $datas => $key) {
    foreach ($key as $value) {
        if ($value == "") {

        } else {
            $arr[] = $value;
        }
    }
}

// Iterate over each link in the CSV
foreach ($arr as $url) {
    sleep(20);
    // Get the HTML content from the URL
    $html = file_get_contents($url);

    // Create a new DOMDocument object
    $dom = new DOMDocument();

    // Configure libxml to handle HTML errors
    libxml_use_internal_errors(true);

    // Load the HTML content
    $dom->loadHTML($html);

    // Clear libxml error buffer
    libxml_clear_errors();

    // Find the table element with class "responsive-table"
    $tableElements = $dom->getElementsByTagName('table');
    foreach ($tableElements as $table) {
        if ($table->getAttribute('class') === 'responsive-table') {
            // Create an array to store the table data
            $tableData = array();

            // Find all table rows
            $rows = $table->getElementsByTagName('tr');

            // Process the header row to extract column names
            $headerRow = $rows->item(0);
            $headerCells = $headerRow->getElementsByTagName('th');
            $columns = array();
            foreach ($headerCells as $headerCell) {
                $columns[] = trim($headerCell->nodeValue);
            }

            // Iterate over each row starting from the second row
            for ($i = 1; $i < $rows->length; $i++) {
                $rowData = array();
                $row = $rows->item($i);

                // Find all table cells in the row
                $cells = $row->getElementsByTagName('td');

                // Iterate over each cell and store the data
                foreach ($cells as $j => $cell) {
                    $type = $cell->getAttribute('class');
                    switch ($type) {
                        case 'cell-01':
                            $rowData[$columns[$j]] = trim(strip_tags($cell->nodeValue));
                            break;
                        case 'cell-02':
                            $rowData[$columns[$j]] = trim(strip_tags($cell->nodeValue));
                            break;
                        case 'cell-20':
                            $rowData[$columns[$j]] = trim(strip_tags($cell->nodeValue));
                            break;
                        case 'cell-03':
                            $rowData[$columns[$j]] = trim(strip_tags($cell->nodeValue));
                            break;
                        case 'cell-04-2':
                            $groupCompositionUrl = $cell->getElementsByTagName('a')->item(0)->getAttribute('href');
                            $groupComposition = file_get_contents($groupCompositionUrl);


                            // Create a new DOMDocument object for group composition
                            $groupDom = new DOMDocument();
                            $groupDom->loadHTML($groupComposition);
                            $groupDom->preserveWhiteSpace = false;

                            // Extract the number of men and women participants
                            $menCount = 0;
                            $womenCount = 0;

                            $menList = $groupDom->getElementsByTagName('ul')->item(0);
                            if ($menList) {
                                $menItems = $menList->getElementsByTagName('li');
                                foreach ($menItems as $item) {
                                    $count = intval($item->nodeValue);
                                    if ($count >= 0) {
                                        $menCount += $count;
                                    }
                                }
                            }

                            $womenList = $groupDom->getElementsByTagName('ul')->item(1);
                            if ($womenList) {
                                $womenItems = $womenList->getElementsByTagName('li');
                                foreach ($womenItems as $item) {
                                    $count = intval($item->nodeValue);
                                    if ($count >= 0) {
                                        $womenCount += $count;
                                    }
                                }
                            }

                            $rowData[$columns[$j]] = 'Men: ' . $menCount . ', Women: ' . $womenCount;
                            break;
                        case 'cell-04':
                            $rowData[$columns[$j]] = trim(strip_tags($cell->nodeValue));
                            break;
                        case 'cell-05':
                            $rowData[$columns[$j]] = trim(strip_tags($cell->nodeValue));
                            break;
                        case 'cell-06':
                            $rowData[$columns[$j]] = trim(strip_tags($cell->nodeValue));
                            break;
                    }
                }

                // Add the row data to the table data array
                $tableData[] = $rowData;
            }

            // Create a new Spreadsheet object
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            // Set the header row
            foreach ($columns as $key => $column) {
                $columnLetter = chr(65 + $key);
                $sheet->setCellValue($columnLetter . '1', $column);
            }

            // Set the data rows
            foreach ($tableData as $rowKey => $row) {
                $rowNumber = $rowKey + 2;
                foreach ($row as $columnKey => $cellValue) {
                    $columnLetter = chr(65 + (int)$columnKey);
                    $sheet->setCellValue($columnLetter . $rowNumber, $cellValue);
                }
            }

            // Generate a unique filename based on the link
            $filename = 'scraped_data_' . md5($url) . '.xlsx';

            // Save the spreadsheet to an Excel file
            $writer = new Xlsx($spreadsheet);
            $writer->save($filename);

            echo 'Data has been saved to ' . $filename . '<br>';

            break; // Stop processing further tables
        }
    }
}
?>





`

BigCommerce PHP hello world app installation error with silex

I am new to the bigcommerce development. I am trying to create a bigcommerce app in localhost. I am getting this error.

I have done making the localhost has https. created app in bigcommerce development by following this link https://github.com/bigcommerce/hello-world-app-php-silex

I am looking for the help to fix this error.

[click here for the error message] https://i.stack.imgur.com/NVfuq.png