php array unique with a condition

i got arrays that needs to be unique and i need to have a condition to check if value dis is in ANSWERED status , if yes then keep it and remove the one that is in NO ANSWER status

this is my full array

Array
(
    [0] => Array
        (
            [dest] => 960
            [dis] => ANSWERED
        )

    [1] => Array
        (
            [dest] => 596
            [dis] => NO ANSWER
        )

    [2] => Array
        (
            [dest] => 596
            [dis] => ANSWERED
        )

    [3] => Array
        (
            [dest] => 595
            [dis] => NO ANSWER
        )

    [4] => Array
        (
            [dest] => 595
            [dis] => NO ANSWER
        )

)

after removing duplicates :

Array
(
    [dest] => 960
    [dis] => ANSWERED
)
Array
(
    [dest] => 596
    [dis] => NO ANSWER
)
Array
(
    [dest] => 596
    [dis] => ANSWERED
)
Array
(
    [dest] => 595
    [dis] => NO ANSWER
)

with this code :
foreach(array_unique($testArr, SORT_REGULAR) as $doc)
{
    print_r($doc);
}

what i need to do now is remove array[1] that is NO ANSWER because array[2] with key : dis is ANSWERED

thanks for any help

I would like to view the products by category on the home page

I would like to view the products by category on the home page.
I have two category and products tables.
I tried to create the select categories first and after that of the products in the while.
The problem is that for each category I always get all the products.
How can I make sure that only the corresponding product is displayed for each category?
Sorry but I’m just starting out.

Scheme:

1 Category

corresponding product, corresponding product

2 Category

corresponding product

3 Category

corresponding product, corresponding product, corresponding product

Here is my query:

<?php
$sql_cat = "SELECT  category_id,category_name FROM category WHERE status='A' order by category_id ASC"; 
$result_cat = mysqli_query($conn, $sql_cat);
if (mysqli_num_rows($result_cat) > 0) {
    // output data of each row
    while($row_cat = mysqli_fetch_assoc($result_cat)) {
        $categoryid=$row_cat["category_id"];
        $category_name=$row_cat["category_name"];
        echo''.$category_name.'<br>';
        $sql = "SELECT * FROM product WHERE status='A' and category='$categoryid' Order by category ASC"; 
        $resultSet = mysqli_query($conn, $sql);
        while($row = mysqli_fetch_assoc($resultSet)) {
            $nameproduct=ucfirst(html_entity_decode($row['product_name'], ENT_QUOTES));
            echo''.$nameproduct.'';
        }   
    }   
}  

Work log and generate a PDF everys X days

I have created my first php system, it basically is a list of customers which the user can select and log work for which generates a PDF work record.

I want to extend it to generate an invoice every Thursday midnight and send it to the business, eg:

User 1 has worked:
Customer a – 1 hour
Customer c – 2 hours
Customer D – 4 hours

Total 7 hours at (Chargeable rate).

Now in my head it seems pretty straight forward but I want to sense check it with people it possible:

When the PDF is generated I need to store the information in a new table, User ID, Customer name, Hours worked, Time & date. Then each Thursday I need a script to run which will transfer the entries from the database (over the past X days – could I say from ID X which was the last ID to be ran in the previous pdf?) to a PDF, save the pdf to the server and email it to me.

A few questions:
Would It be beneficial to clear this data after X day so the DB doesn’t get too big?

What is the best way to ensure that an entry doesn’t get missed? I will most likely run the script every thursday at midnight, but I’m guessing theres room for error there if somebody submits an entry at the same time? (slim chance but possible)

I’ll be using mPDF for the invoice generation which I already use.

Magento 2 – Type error: require is not a function for admin grid in custom page with custom tab

I am trying to load a grid to a tab on a custom page in Mangento 2 admin. The grid is rendered beautifully but js seems to be uninitialized after the ajax reload fetches it from controller. The grid is not responsive at all. Browser console displays “Type Error: require is not a function”, but I don’t understand how to initialize js for the grid after ajax.

My code (skipping boilerplate e.g. registration.php, composer.json, etc/module.xml, etc/adminhtml/routes.xml):

/Vendor/Module/Controller/Adminhtml/Offers/Edit.php

<?php
  namespace VendorModuleControllerAdminhtmlOffers;

  class Edit extends MagentoBackendAppAction{
    
    protected $resultPageFactory;

    public function __construct(
        MagentoBackendAppActionContext $context,
        MagentoFrameworkViewResultPageFactory $resultPageFactory
    ) {
         parent::__construct($context);
         $this->resultPageFactory = $resultPageFactory;
    }

    public function execute()
    {
         return  $resultPage = $this->resultPageFactory->create();
    }
  }
?>

/Vendor/Module/view/adminhtml/layouts/module_offers_edit.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <title>
            Angebot
        </title>
    </head>
    <body>
        <referenceContainer name="left">
            <block class="VendorModuleBlockAdminhtmlOfferEditTabs"
                name="vendor_module_offer.edit.tabs"/>
        </referenceContainer>
        <referenceContainer name="content">
            <block class="VendorModuleBlockAdminhtmlOfferEdit"
                name="vendor_module_offer.edit"/>
        </referenceContainer>
    </body>
</page>

/Vendor/Module/Block/Adminhtml/Offer/Edit.php

<?php
namespace VendorModuleBlockAdminhtmlOffer;

use MagentoBackendBlockWidgetFormContainer;

class Edit extends Container{

    protected $_coreRegistry = null;

    public function __construct(
        MagentoBackendBlockWidgetContext $context,
        MagentoFrameworkRegistry $registry,
        array $data = []
    ) {
        $this->_coreRegistry = $registry;
        parent::__construct($context, $data);
    }
    protected function _construct()
    {
        $this->_objectId = 'module_offer_id';
        $this->_blockGroup = 'Vendor_Module';
        $this->_controller = 'adminhtml_offer';
        parent::_construct();
        $this->buttonList->remove('save');
    }

    public function getHeaderText()
    {
        return __('Offer');
    }

    protected function _isAllowedAction($resourceId)
    {
        return $this->_authorization->isAllowed($resourceId);
    }

}

/Vendor/Module/Block/Adminhtml/Offer/Edit/Tabs.php

<?php
   namespace VendorModuleBlockAdminhtmlOfferEdit;

   use MagentoBackendBlockWidgetTabs as WidgetTabs;

   class Tabs extends WidgetTabs{

    protected function _construct()
    {
        parent::_construct();
        $this->setId('offer_edit_tabs');
        $this->setDestElementId('edit_form');
        $this->setTitle(__('Angebot'));
    }

    protected function _beforeToHtml()
    {
        $this->addTab(
            'Produkte',
            [
                'label' => __('Products'),
                'url' => $this->getUrl('module/*/products', ['_current' => true]),
                'class' => 'ajax'
            ]
        );
        return parent::_beforeToHtml();
    }
}

This is all just setup for the tabs to display on the page with path .../admin/module/offers/edit/ID. Now, to fill the tab with products I load the grid with this:

/Vendor/Module/Controller/Adminhtml/Offers/Products.php

<?php
  namespace VendorModuleControllerAdminhtmlOffers;

  class Products extends MagentoBackendAppAction{
    protected $resultPageFactory;

    public function __construct(
        MagentoBackendAppActionContext $context,
        MagentoFrameworkViewResultPageFactory $resultPageFactory
    ) {
         parent::__construct($context);
         $this->resultPageFactory = $resultPageFactory;
    }

    public function execute()
    {
         return  $resultPage = $this->resultPageFactory->create();
    }
  }
?>

/Vendor/Module/view/adminhtml/layout/module_offers_products.xml

<?xml version="1.0"?>
<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/layout_generic.xsd">
    <container name="root" label="Root">
        <block class="VendorModuleBlockAdminhtmlOfferEditTabViewProducts" name="offer.edit.tab.product"/>
    </container>
</layout>

/Vendor/Module/Block/Adminhtml/Offer/Edit/Tab/View/Products.php

<?php
namespace VendorModuleBlockAdminhtmlOfferEditTabView;

use MagentoCustomerControllerRegistryConstants;

class Products extends MagentoBackendBlockWidgetGridExtended
{

    protected $_coreRegistry = null;

    protected $_collectionFactory;

    public function __construct(
        MagentoBackendBlockTemplateContext $context,
        MagentoBackendHelperData $backendHelper,
        VendorModuleModelOfferItemFactory $collectionFactory,
        MagentoFrameworkRegistry $coreRegistry,
        PsrLogLoggerInterface $logger,
        array $data = []
    ) {
         $this->_logger = $logger;
        $this->_coreRegistry = $coreRegistry;
        $this->_collectionFactory = $collectionFactory;
        parent::__construct($context, $backendHelper, $data);
    }

    protected function _construct()
    {
        parent::_construct();
        $this->setId('offer_view_products_grid');
        $this->setDefaultSort('offer_item_stock_id', 'desc');
        $this->setSortable(true);
        $this->setPagerVisibility(true);
        $this->setFilterVisibility(true);
    }

    protected function _preparePage()
    {
        $this->getCollection()->setPageSize(5)->setCurPage(1);
    }

    protected function _prepareCollection()
    {
        $collection = $this->_collectionFactory->create()->getCollection();
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('offer_item_stock_id');
        $this->getMassactionBlock()->setFormFieldName('stock_ids');
        $this->getMassactionBlock()->addItem(
            'customize',
            [
                'label' => __('Anpassen (ToDo)'),
                'url' => $this->getUrl('test/test/test')
            ]
        );
        return $this;
    }
     protected function _prepareColumns()
    {
        $this->addColumn(
            'offer_item_stock_id',
            ['header' => __('Stock ID'), 'index' => 'offer_item_stock_id', 'type' => 'number', 'width' => '50px']
        );
        return parent::_prepareColumns();
    }

    public function getHeadersVisibility()
    {
        return $this->getCollection()->getSize() >= 0;
    }

    public function getRowUrl($row)
    {
        return $this->getUrl('test/test/test');
    }
}

So my question is how to initialize js for the grid after ajax load.

Showing 403 forbidden error on removing members of discord server in laravel php

 $discord = new DiscordClient(['token' => 'OTIzMDg2MTgzNDg2MDYyNjQz.YcK5AA.HfoDRu-6sKDUPnneA29m3eHQtT4']);
 $users = $discord->guild->listGuildMembers(['guild.id' =>923083706934120448, 'limit' => 25]);
 $discord->guild->removeGuildMember(['guild.id'=>923083706934120448,'user.id'=>894299782481334302]);

There was an error executing the removeGuildMember command: Client error: DELETE https://discord.com/api/v6/guilds/923083706934120448/members/894299782481334302 resulted in a 403 Forbidden response:

When I am kicking a member from server it is giving me forbidden error
I have use Restcord library in this I have fetched the members through
it ,And it is working prperly but when i am removing member it is
giing me forbidden error I have given permission to my bot through
oath url generator but still it is givig me this error if you any idea
about this i can explain more you can ask me?

How to get changed value using array_diff in laravel?

public function changeData(Request $request)
{
     $product = Product::where('_id', '=', $request->product['_id'])->first()->toArray();

        //result product : 
        // array(4) {
        //     ["_id"]=>
        //     string(24) "5fffc00df116005c724859f2"
        //     ["name"]=>
        //     string(6) "iphone"
        //     ["slug"]=>
        //     string(14) "product-iphone"
        //     ["status"]=>
        //     string(14) "1"
        // }


        // result $request->product :
        // array(4) {
        //     ["_id"]=>
        //     string(24) "5fffc00df116005c724859f2"
        //     ["name"]=>
        //     string(7) "samsung"
        //     ["slug"]=>
        //     string(15) "product-samsung"
        //     ["status"]=>
        //     string(14) "1"
        // }

        $diff = array_diff($request->product, $product);
        var_dump($diff);
}

ERROR: ‘Array to string conversion’

If I use the :

$diff = array_diff(array_map('serialize',$request->product), array_map('serialize',$product));

Then it will return the following result:

 array(2) {
        ["name"]=>
        string(15) "s:6:"samsung";"
        ["slug"]=>
        string(25) "s:15:"product-samsung";"
      }

The results above are correct for what I need. But it shows "s:6: and "s:15: inside the result. Is there a way for these two to not appear. I just want to get the correct result eg name is samsung. Thank you.

PHP mail stops after changing host [duplicate]

Years ago someone made this PHP script for me. I use it on dozens of web pages.
Recently my hoster was taken over by another company and my script stopped working after that.
The helpdesk of the new hoster gave me a tip to look at:

How to send an HTML email using SMTP in PHP

You can use the hostname below in the article above:
$host = “mail.argewebhosting.nl”;

However, I am not a php specialist and I would like to be able to modify it myself. Can someone tell me what I can do to get the script working again?

==========================================================

<?php
if (!isset($_POST['naam_inzender']) || !isset($_POST['emailadres_inzender']) || !isset($_POST['opmerkingen'])) {
echo 'U heeft niet alle velden ingevuld!';
exit;

}

$naam = htmlspecialchars($_POST['naam_inzender']);
$email = htmlspecialchars($_POST['emailadres_inzender']);
$bericht = htmlspecialchars($_POST['opmerkingen']);
$organisatie= htmlspecialchars($_POST['organisatie']);
$plaats_organisatie= htmlspecialchars($_POST['plaats_organisatie']);
$email_onderwerp= htmlspecialchars($_POST['email_onderwerp']);
$auteur= htmlspecialchars($_POST['auteuradres']);
$header = "From: ".$naam."<$email>rn";
$header .= "BCC: [email protected]";
$tijd = time();
$datum = strftime('%d/%m/%y %H:%M', $tijd);
$ip = getenv('REMOTE_ADDR');
$message = $naam.' -'.$organisatie.'-'.$plaats_organisatie.'- met het e-mailadres '.$email.' en het IP '.$ip.' stuurde op '.$datum.' het volgende bericht:

____________________________________

'.$bericht.'

------------------------------------';

if(mail($auteur, $email_onderwerp, $message, $header))
header("Location: https://www.webkwestie.nl/bedankt_voor_opmerkingen.htm");
else
echo 'Niet verstuurd';
?>

===========================================================================

anchor tag download is not working on live laravel project

I am using this code to download the pdf files which are placed in main directory “public/download/ca/”
CODE:

      <a download="" class="download" target="_blank" href="{{ asset('download/ca/'.$doc>
              file_name) }}">
      </a>

It is working perfectly on my local server project also downloads the files but it is not working on my live server project, its showing “failed – Server Problem”.

Solution for admin authentication received from the user

I am trying to build a website for my college in which I have to take in the achievements obtained by the user and display on the front end…. but in order to be remove any bogus data received from the students I want to have an admin which will look at the data and once approved it must be visible to all users on the front end main page.
For more clarity on what I am trying to do:

  1. A registered user has access to post information of his/her achievements.
  2. The info must be present on the admin page and has to review it.
  3. Once reviewed, the admin must have the access to post it on to the front end for every user to see.

Can you help me on the preferred tech stack I must be knowing or the functionalities i must be knowing to do so?

I want to click answer button to answer the qustion

[enter image description here][1]


<?php require_once('connection.php');  
session_start();


if (isset($_POST['Submit']))
{  
   $answ = $_POST['answ'];      
   $email = $_SESSION['email']; 


   $insert = "INSERT INTO `id18159895_adproject`.`que` (answ,queID,email) SELECT que.queID FROM que   " ;
   $result = mysqli_query($con, $insert);

   if (!$result) {
       echo "<script>alert('ERROR !!!!! '); location='qna.php';</script>";
   }
   else {
       echo "<script>alert('Successful Post'); location='qna.php'; </script>";
   }

}
?>

how can add the answer to the current question with my logged email?

Add [title] to fillable property to allow mass assignment on [AppModelsResume]

estoy empezando con Laravel (PHP) y me he encontrado con este error El error es este: Add [title] to fillable property to allow mass assignment on [AppModelsResume].

El código del ResumeController que me da error es este:


public function store(Request $request)
    {
        $user = auth()->user();
        $resume = $user->resumes()->create([
            'title' => $request['title'],
            'name' => $user->name,
            'email' => $user->email,
        ]);

        return response("Created resume $resume->id");
    }

El cual resumes() me lo marca vscode como que no es encontrada la función, cuando la tengo hecha en el archivo Resume.php y en el User.php

Este es el código de las funciones:
(Resume.php)

    public function user(){
       return $this->belongsTo(User::class);
    }

(User.php)

    public function resumes() {
        return $this->hasMany(Resume::class);
    }

¡Muchas gracias de ante mano!

Undefined index: REQUEST_URI and HTTP_HOST

How can I get rid of this errors.

Line 8 : define('CURRENT_PAGE', basename($_SERVER['REQUEST_URI']));
Line 15: define('READ_PATH', $_SERVER['HTTP_HOST'].'/read.php?id=');

errors:

Undefined index: REQUEST_URI in ......... on line 8
Undefined index: HTTP_HOST in ....... on line 15

Laravel Eloquent Relationship Join

carts:-

id product_name price

ratings:-

id product_id user_id

I have these two table. And i have defined a relationship in product model for geting rating of particular product. and output of the code is this:-
“data”: [
{
“id”: 4200,
“name”: “Anti gravity Beer Cake”,
“modal”: “”,
“price”: 1800,
“discount”: 0,
“quantity”: 20,
“discription”: “Good Quality Product!”,
“p_status”: “active”,
“m_id”: 664,
“product_link”: “anti-gravity-beer-cake–6040c2b317894”,
“product_picture”: ” “,
“weight”: 0,
“weight_type”: “Kilogram”,
“rating”: {
“id”: 4,
“u_id”: 1,
“product_id”: 4200,
“subject”: null,
“ratings”: 4,
“review”: null,
“type”: “rating”
}
},
{
“id”: 4200,
“name”: “Anti gravity Beer Cake”,
“modal”: “”,
“price”: 1800,
“discount”: 0,
“quantity”: 20,
“discription”: “Good Quality Product!”,
“p_status”: “active”,
“m_id”: 664,
“product_link”: “anti-gravity-beer-cake–6040c2b317894”,
“product_picture”: ” “,
“weight”: 0,
“weight_type”: “Kilogram”,
“rating”: {
“id”: 5,
“u_id”: 1,
“product_id”: 4200,
“subject”: null,
“ratings”: 5,
“review”: null,
“type”: “rating”
}
}

But i want product having high rating first. How i an do it?
product model:-

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class product extends Model
{
use HasFactory;

public function rating(){
    return $this->hasOne(ratings_and_review::class)->orderBy('ratings','DESC');
}

}