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']);
    }
}

I get an error Unparenthesized `a ? b : c ? d : e` [duplicate]

I get an error on one of my WordPress plugins, I know it is a php version related error, but I am not able to find the solution, tried many variant but with no luck

value="<?php isset($results->value) && !empty($results->value) ? print_r($results->value) : '' ?>" <?php isset($results->value) && !empty($results->value) ? '' : !empty($results->id) ? print_r('disabled="disabled"') : ''; ?>/> 

Unparenthesized a ? b : c ? d : e is not supported. Use either (a ? b : c) ? d : e or a ? b : (c ? d : e)

Can you help me figure it out?
Thanks!

AMPHP async Function Not Working as Expected in WordPress Plugin

I am developing a WordPress plugin and attempting to use the AmpPHP library to handle asynchronous tasks. I have set up my plugin with the following code:

require_once plugin_dir_path(__FILE__) . 'SMSService.php';
require_once plugin_dir_path(__FILE__) . 'EmailService.php';
require_once plugin_dir_path(__FILE__) . '/../libraries/Amp/vendor/autoload.php';

use function Ampasync;
use function Ampdelay;

class MessageService
{
    public $smsService;
    public $emailService;

    public function __construct()
    {
    }

    public function sendSMS($to, $body, $from = null)
    {
        $this->smsService = new SMSService();
        async(function () use ($to, $body, $from) {
            $this->smsService->handle($to, $body, $from);
        });
    }
}

In my implementation, I call the sendSMS method, but the asynchronous code inside async does not seem to execute.

I installed the AmpPHP library using composer require amphp/amp. After calling the sendSMS method, I also attempted to run EventLoop::run() to process the asynchronous tasks. However, despite this, the sendSMS method executes synchronously.

I expected the asynchronous function to run separately and not block the execution of subsequent code. Could someone help me understand why the async function is not working as expected in this setup?

How to play a video in this PHP player code to use in a mobile app using an embed link [closed]

I found a player (SE player) coded through PHP, and it’s working if I use it on my mobile app using this embed link: “https://mywebsite.com/player.php?video_id=imdb_id.” I just want to ask how this PHP code is used on other video streaming APIs such as vidsrc, soap2day, 123movies, and others using an IMDB link or embed link.

<?php
////////////////////////// PLAYER SETTINGS ///////////////////////////////////////////////

$player_font = "Poppins";

$player_bg_color = "000000";
$player_font_color = "ffffff";
$player_primary_color = "34cfeb";
$player_secondary_color = "6900e0";

$player_loader = 1;

// preferred server - you can choose server that will be on top of the list and open after
// clicking play button, works only for quality >= 720p
// options are: vidlox = 7, fembed = 11, mixdrop = 12, upstream = 17, videobin = 18,
// doodstream = 21, streamtape = 25, streamsb = 26, voe = 29, ninjastream = 33
$preferred_server = 0; // paste only server number, leave 0 for no preference

$player_sources_toggle_type = 2;

//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
if (isset($_GET['video_id'])) {
  $video_id = $_GET['video_id'];
  $is_tmdb = 0;
  $season = 0;
  $episode = 0;
  $player_url = "";
  if (isset($_GET['tmdb'])) {
    $is_tmdb = $_GET['tmdb'];
  }
  if (isset($_GET['season'])) {
    $season = $_GET['season'];
  } else if (isset($_GET['s'])) {
    $season = $_GET['s'];
  }
  if (isset($_GET['episode'])) {
    $episode = $_GET['episode'];
  } else if (isset($_GET['e'])) {
    $episode = $_GET['e'];
  }
  if (!empty(trim($video_id))) {
    $request_url = "https://getsuperembed.link/?video_id=$video_id&tmdb=$is_tmdb&season=$season&episode=$episode&player_font=$player_font&player_bg_color=$player_bg_color&player_font_color=$player_font_color&player_primary_color=$player_primary_color&player_secondary_color=$player_secondary_color&player_loader=$player_loader&preferred_server=$preferred_server&player_sources_toggle_type=$player_sources_toggle_type";
    if (function_exists('curl_version')) {
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $request_url);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($curl, CURLOPT_TIMEOUT, 7);
      curl_setopt($curl, CURLOPT_HEADER, false);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
      $player_url = curl_exec($curl);
      curl_close($curl);
    } else {
      $player_url = file_get_contents($request_url);
    }
    if (!empty($player_url)) {
      if (strpos($player_url, "https://") !== false) {
        header("Location: $player_url");
      } else {
        echo "<span style='color:red'>$player_url</span>";
      }
    } else {
      echo "Request server didn't respond";
    }
  } else {
    echo "Missing video_id";
  }
} else {
  echo "Missing video_id";
}
?>

I tried to change this “https://getsuperembed.link/?video_id=” to this “https://vidsrc.io/embed/movie?imdb=” for example in vidsrc, but the link is not working or didn’t play on my mobile app. Is there other way to used the code in other streaming using embed link that play on my mobile app using a player from PHP code. By the way, my mobile is connected to my wordpress data that all my movies and anime can access on my mobile app.

Rates and Transit Times API is giving 400 Bad Request error if I change the account number using codeigniter 4

I am working with program where we need to fetch details from fedex Rates and Transit API, the API works fine with the account number which is linked to API project in developers portal but once I try to change another account number the API returns “file_get_contents(https://apis.fedex.com/rate/v1/rates/quotes): Failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request” error ..
can’t find the enough information on API documentation and in search.

Qustion 1: I want to confirm is there any restriction on API end that we can fetch data from only those accounts which are linked? or we need to change our parametes?

Question 2: I’ve used try catch block to handle error but this errors still crash the application, any way to handle this?

public function callAPI()
{

    $this->accountNumber->set_value('11111111');


    //set shipper postalcode and country code 
    $this->shipper->set_postalCode(12345);
    $this->shipper->set_countryCode('US');
    $this->shipper->set_residential(false);



    //set recipient postalcode and country code 
    $this->recipient->set_postalCode(456789);
    $this->recipient->set_countryCode('US');
    $this->recipient->set_residential(true);


    //set weight and units 
    $this->weight->set_units('LB');
    $this->weight->set_value(26);



   $this->requestedShipment->set_shipper(['address' => $this->shipper]);
   $this->requestedShipment->set_recipient(['address' => $this->recipient]);
   $this->requestedShipment->set_requestedPackageLineItems(array(['weight' => $this->weight]));


    //set pickup type 
    //types: "CONTACT_FEDEX_TO_SCHEDULE", "DROPOFF_AT_FEDEX_LOCATION", "USE_SCHEDULED_PICKUP"
    $this->requestedShipment->set_pickupType("USE_SCHEDULED_PICKUP");

    // set type of rate to be returned 
    //types: "LIST", "INCENTIVE", "ACCOUNT", "PREFERRED" (see documentation for explanations)
    $this->requestedShipment->set_rateRequestType(['ACCOUNT']);


    //set shipment date 
    $this->requestedShipment->set_shipDateStamp("2023-08-17");


  $this->rateRequestControlParameters->set_return_tranist(true);
    $accountNumberJSON = json_encode($this->accountNumber);
    $requestedShipmentJSON = json_encode($this->requestedShipment);

     $url = "https://apis.fedex.com/oauth/token";


    //client id is api key and client secret is secret key
    $data = [
        'grant_type' => 'client_credentials',
        'client_id' => 'my_clinet_id',
        'client_secret' => 'my_clinet_secret'
    ];

    $options = array(
        'http' => array(
            'header' => "Content-type: application/x-www-form-urlencoded",
            'method' => 'POST',
            'content' => http_build_query($data)
        )
    );

    $context = stream_context_create($options);
    $resp = file_get_contents($url, false, $context);
    $response_data = json_decode($resp);
    $access_token = $response_data->access_token;
    
    //calls function if token is working (token changes every minute)
    if (isset($access_token)) {
        echo $this->get_rates($access_token, $this->accountNumber, $this->requestedShipment, $this->rateRequestControlParameters); 
    }
}

function get_rates($token, $acct, $ship, $rateReqCtrlPara)
{
    $url = "https://apis.fedex.com/rate/v1/rates/quotes";

    $data = ['accountNumber' => $acct, 'requestedShipment' => $ship, 'rateRequestControlParameters' => $rateReqCtrlPara, 'carrierCodes' => array('FDXG') ];
    $options = array(
        'http' => array(
            'header' => [
                "Content-type: application/json",
                "Authorization: Bearer {$token}",
                "X-locale: en_US"
            ],
            'method' => 'POST',
            'content' => json_encode($data)
        )
    );

    $context = stream_context_create($options);
    try{ 
            $resp_data = file_get_contents($url, false, $context); //error here
    }
    catch (exception $e) { echo $e; }
  return $resp_data;
}

Error “WebAssetManager is locked, you came late” in Joomla

I’m using Joomla 4.4, and this code to load a module to display it in a plugin.

echo JHtml::_('content.prepare', '{loadmoduleid 16}');

error

But the website say error WebAssetManager is locked, you came late

If I use {loadmoduleid 16} in a Joomla article it still working fine. I don’t sure what’s wrong?

Please help.

Thanks

WebAssetManager is locked, you came late

Savsoft correct_answer

after creating and starting the quiz, how can I create a session variable that for each answer I give, the application evaluates whether it is a correct answer and displays in the header the total number of correct answers each time the button is chosen NEXT?

I tried to initialize a session variable $_SESSION[‘counter’] in the quiz.php controller in the saved_answer method, but it is not incremented.

What is the best way to validate an uploaded file in drupal 10

I’m very new to drupal and it has been one hell of a ride already.

I’m creating a custom module where people can fill out a form to apply for a job. Of course I want to implement form validation but it goes wrong when I want to validate the uploaded file.

I can’t seem to find a clear way to validate uploaded files, like anywhere. I’m trying to rely on my php knowledge but of course it is not entirly te same when it comes down to drupal.

I’m providing you guys with something I had now, which clearly doesn’t work, but I would like to ask what you would say is the best way to validate uploaded files? And without installing third party modules..

What I tried:

// Validate the uploaded file
$validators = ['file_validate_extensions' => ['docx doc pdf jpg jpeg png']];
$file = file_save_upload('cv', $validators, FALSE, 0);

if (!$file) {
    // Add error message if the file isn't validated
    $form_state->setErrorByName('cv', $this->t('Uw CV heeft een niet-toegestane extensie. Probeer het opnieuw.'));
} else {
    // Set the correct file in the form state
    $form_state->setValue('cv', $file);
}

Unfortunately, file_save_upload is not recognized because it’s deprecated and drupals documentation is a bit confusing to me..

Thanks in advance!

Remote Xdebug and 504 on lost connection

I set up a remote Xdebug to work through the SSH tunnel. Everything works perfectly, but if I eventually drop the SSH connection (lost internet connection, switch VPNs or just close the laptop screen) my remote website drops into 504 error. Restarting nginx and php-fpm doesn’t help. The website simply wakes up on its own after 15-20 min.

Seems that there is a kind of timeout somewhere? Can you help where? And what can I do to prevent the site dropping into 504?

php.ini:

zend_extension=xdebug
xdebug.mode=debug
xdebug.client_host=127.0.0.1
xdebug.client_port=9093
xdebug.start_with_request=yes
xdebug.remote_handler = dbgp
xdebug.idekey=PHPSTORM

(yes, I use port 9093 for Xdebug and it works)

To create SSH tunnel I use putty:

enter image description here