Shortcode content not visible

I have this code that creates a dynamic TOC inside single.php at the top of the page. But I would like to use it in a shortcode.

I tried using add_shortcode('toc_content', 'create_toc'); but it does not display anything. Any idea what am I doing wrong?

function create_toc($html) {
  $toc = '';
  if (is_single()) {
      if (!$html) return $html;
      $dom = new DOMDocument();
      
      libxml_use_internal_errors(true);
      $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
      libxml_clear_errors();
      $toc = '<div class="toc-bound">
          <div class="toc-ctr">
              table of contents
          </div>
          <ul class="toc">';
      $h2_status = 0;          
      $i = 1;     

      $xpath = new DOMXpath($dom);
      $expression = '//*[contains(concat(" ", normalize-space(@class), " "), " toc-item ")]';
     
      foreach ($xpath->evaluate($expression) as $element) {              
          if($h2_status){
            $toc .= '</li>';
            $h2_status = 0;
          }
          $h2_status = 1;
          $toc .= '<li><a href="' . get_the_permalink() . '#toc-' . $i . '">' . $element->textContent . '</a>';
          $element->setAttribute('id', 'toc-' . $i);
          $i++;          
      }
      
      if($h2_status){
          $toc .= '</li>';
      }
      $toc .= '</ul></div>';
      $html = $dom->saveHTML();
  }
  return $toc . $html;
}
add_filter('the_content', 'create_toc');    
//add_shortcode('toc_content', 'create_toc'); does not work

Follow unfollow working only first row php while loop

I’m working on a follow and unfollow system project but there seems to be a problem with my code

The follow unfollow button only work for the first row.
How can i get it to work for different rows
I have tried different ways but none seem to be working
Here is my Php while loop code and J’s code below

 $check_following_or_not = mysqli_query($db,"select * from follow_and_unfollow_activity where page_owners_emails = '{$_SESSION["username"]}'");  
        while($de=mysqli_fetch_array($check_following_or_not)) {      
         $page_owner=$de['followers_emails'; 
       if(mysqli_num_rows($check_following_or_not) > 0)

      {?>
    <span hidden data-src="loading.gif"></span>

                    <span  style="background:purple;color:white;opacity:0.6"  class="button actions__btn text-uppercase font-900 " id="following" onClick="follow_or_unfollow('<?php echo $page_owner; ?>','<?php echo $_SESSION["username"]; ?>','following');"><b>Following    <?php echo $page_owner;?> </b> <i class="fa fa-check"></i></span>
     <? if(!isset($_SESSION['username']))
{echo'<a href="/ver/dist">';}?>
    <button style="display:none;background-color:" class="actions__btn actions__btn--active follow" id="follow" onClick="follow_or_unfollow('<?php echo $page_owner; ?>','<?php echo $_SESSION["username"]; ?>','follow');">
<font color="">Follow    <?php echo $page_owner;?>     </font></button>
            
    <? if(!isset($_SESSION['username'])){echo'</a>';}?>
      <?php} 

else{<? if(!isset($_SESSION['username'])){echo'<a href="/ver/dist">';}?>
                    
    <span hidden data-src="loading.gif"></span>
     <button class="actions__btn actions__btn--active follow " id="follow" onClick="follow_or_unfollow('<?php echo $page_owner; ?>','<?php echo $_SESSION["username"]; ?>','follow');" <? if(!isset($_SESSION['username'])){

     echo'';}?>>Follow <?php echo $page_owner;?> </button>
     <? if(!isset($_SESSION['username']))
{echo'</a>';}?>
     <span   style="display:none;background:purple;color:white;opacity:0.6" class="button actions__btn text-uppercase font-900" id="following" onClick="follow_or_unfollow('<?php echo $page_owner; ?>','<?php echo $_SESSION["username"]; ?>','following');"><b>Following     <?php echo $page_owner;?> </b> <i class="fa fa-check"></i></span>

     <?
      }?>
     <?}?>

Here is my My Js code

$(document).ready(function(){     $('.following').hover(function()
{                 $(this).text("Unfollow");},function()
{                  $(this).text("Following");
  });
 });
             
        
    function follow_or_unfollow(page_owner,follower,action)
    {
        var dataString = "page_owner=" + page_owner + "&follower=" + follower;
        $.ajax({  
            type: "POST",  
            url: "follow_or_unfollow.php",  
            data: dataString,
            cache: false,
            beforeSend: function() 
            {
                if ( action == "following" )
                {
                    $("#following").hide();
                    $("#loading").html('<img src="images/loading.gif" align="absmiddle" alt="Loading...">');
                }
                else if ( action == "follow" )
                {
                    $("#follow").hide();
                    $("#loading").html('<img src="images/loading.gif" align="absmiddle" alt="Loading...">');
                }
                else { }
            },  
            success: function(response)
            {
                if ( action == "following" )
                {
                    $("#loading").html('');
                    $("#follow").show();
                    
                }
                else if ( action == "follow" )
                {
                    $("#loading").html('');
                    $("#following").show();
                }
                else { }
            }
        }); 
    }

Undefined variable by using eloquent relationships

Here is the error returned by Laravel :

ErrorException compact(): Undefined variable $lists

I am trying to join multiples tables like :
Tops has many Lists and Lists has many Medias

I have this code in my TopController :

 $tops = Top::with(
                    'user:id,name,email',
                    'lists:id',
                    'categories:title,slug'
                )->paginate(20); 

I have no problem for retrieve user and categories datas but the lists variable seems to be undefined and I do not understand why.

Here is the Liste.php Model :

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


      public function tops()
    {
        return $this->belongsToMany(Top::class);
    }



      public function medias()
    {
        return $this->belongsToMany(Medias::class);
    }

Thank you for your help.

https://pastebin.com/Anv4AhVe

display a warning message when deleting a client that has an active user

i want to display a warning when deleting a client with an active user. so that the client cannot be deleted if there is an active user with the client. what’s the solution? I need solution as soon as possible, thanks.

I’m using Laravel 8, with PHP 8.1

here’s my code:

ClientController.php

    /**
 * Remove the client, with CLIENT_ID
 *
 * @param  integer $CLIENT_ID
 * @return IlluminateHttpResponse
 */
public function destroy($CLIENT_ID)
{
    $clientName = Client::where('CLIENT_ID',$CLIENT_ID)->first();

    $deleted = $this->clientRepo->delete($CLIENT_ID);

    return $deleted ? redirect()->route('client')->with('alert-success', trans('validation.success_delete', ['name' => 'Client with name '.$clientName["COMPANY_NAME"]])) : back()->withInput()->withErrors([trans('validation.failed_delete', ['name' => 'Client'])]);
}

UserController

/**
 * Activate or Deactivate User, with USER_ID
 *
 * @param  integer $USER_ID
 * @return IlluminateHttpResponse
 */
public function changeActiveStatus($USER_ID,$ADAPT)
{
    $userName = ApiUser::where('USER_ID',$USER_ID)->first();

    $changeStatus = $this->apiUserRepo->changeStatus($USER_ID,$userName["ACTIVE"]);

    if (!empty($ADAPT)){
        return $changeStatus
            ? redirect()->route('user.detail_edit',['USER_ID' => $USER_ID])->with('alert-success', trans('validation.success_change_status', ['name' => 'User status with name '.$userName["USER_NAME"]])): back()->withInput()->withErrors([trans('validation.failed_change_status', ['name' => 'User'])]);
    }

    return $changeStatus
            ? redirect()->route('user')->with('alert-success', trans('validation.success_change_status', ['name' => 'User status with name '.$userName["USER_NAME"]])): back()->withInput()->withErrors([trans('validation.failed_change_status', ['name' => 'User'])]);
}

Examples

  1. I create a Client named PT. Gudang Garam
  2. I create a User with Client at #1, User is Active status
  3. if the client #1 is deleted, it will display an alert if there is an active user, and the client cannot be deleted

urlencode with mailto auto generated url and topic in phpbb

how is the best way to encode {CURRENT_URL}
this is auto generated in phpbb, thanks in advance

really just need to encode the body {CURRENT_URL} as gmail on android phone and tablet cuts off the end of phpbb url (=20)
should i use rawencode or urlencode ? and help would be appreciated

$_SESSION empty after redirecting back from external site despite resuming with the same ID based on cookie

I have one script that saves data received from a form in session and then sends a request to an external site. The site then redirects to a thank you page on the same server as the first script. session_start() on the thank you page returns true and session_id() returns the same ID as in the first script but the $_SESSION array is empty.

index.php

<?php
session_start();

if ($_GET['submit-payment'] ?? false) {
    if (($_POST['CREDIT_ACCT_CODE'] ?? false) && ($_POST['AMT'] ?? false)) {
        foreach($_POST as $key => $value) {
            $_SESSION[$key] = $value;
        }
        // if I dump $_SESSION here all the data is there
        session_write_close();
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head></head>
    <body onload="submit();">
        <form action="<URL TO EXTERNAL SITE>" method="post" name="paymentForm">
            <input type="hidden" name="UPAY_SITE_ID" value="3" />
            <input type="hidden" name="CREDIT_ACCT_CODE" value="<?= $_POST['CREDIT_ACCT_CODE'] ?>" />
            <input type="hidden" name="AMT" value="<?= $_POST['AMT'] ?>" />
        </form>
    </body>
</html>

<script type="text/javascript">
    function submit() {
        console.log('<?= session_id() ?>');
        document.paymentForm.submit();
    }
</script>

<?php
    } else {
        throw new Exception('CREDIT_ACCT_CODE or AMT parameter missing from POST data, could not submit payment form');
    }
die;
}

?>

thankyou.php

<?php
session_start();
var_dump(session_id(), $_SESSION, $_COOKIE);
//session ID is the same as the one logged in index.php, $_SESSION is an empty array and $_COOKIE contains a PHPSESSID cookie with the ID
?>

The session resumes with the same ID but no session data is present.

Images not saving to path folder but getting updated in the table

Images are not getting saved in the specified path. But it is showing in the table.

<?php
    include("dbconfig.php");
    $date=$_POST['date'];
    $type=$_POST['type'];
    $name=$_POST['fname'];
    $filename=md5(time()).$_FILES['photo']['name'];
    $tmpname=$_FILES['photo']['tmp_name'];
    move_uploaded_file($tmpname,"myphoto/".$filename);
    $sql="insert into eventmay2022(date,type,fname,photo)
    values('$date','$type','$name','$filename')";
    mysqli_query($conn,$sql);
    header("location:index.php");
?>



<tr><td class="user-entry">Upload your photo</td><td class="user-entry"><input type="file" name="photo" value="file"></td></tr>
            <tr><td></td><td class="user-entry"><button id="submit" type="submit">Submit</button><button onclick="event.preventDefault();" id="cancel">Cancel</button></td></tr>

enter image description here

enter image description here

Your valuable support would be greatly appreciated.

Api-Platform : Filter and inheritance issue

I’ve two classes with a custom filter:

/**
 * @ORMEntity()
 * @ORMInheritanceType("SINGLE_TABLE")
 * @ORMDiscriminatorColumn(name="type", type="string")
 * @ORMDiscriminatorMap({"store" = "Store", "book_store" = "BookStore"})
 * @ApiResource(normalizationContext = {"groups" = {"api_read"}}, collectionOperations = {"GET"}, itemOperations = {"GET"})
 * @ApiFilter(OrSearchFilter::class, properties={"title", "text"})
 */

class Store
{
  ...
}

/**
 * @ORMEntity
 * @ApiResource(normalizationContext = {"groups" = {"api_book_read", "api_read"}}, collectionOperations = {"GET"}, itemOperations = {"GET"})
 * @ApiFilter(OrSearchFilter::class, properties={"title", "text", "book.book.authors.title", "book.book.theme.title"})
 */
class BookStore extends Store {
  ...
}

When I try to filter on my entity ‘BookStore’, my filter ‘OrSearchFilter’ is called twice: the first SQL query is for ‘BookStore’ and the second for ‘Store’. So, if I try to filter on ‘book.book.authors.title’, I have no result because Api-Platform calls my ‘OrSearchFilter’ of my entity ‘Store’.

How to make my filter only be called once for my entity ‘BookStore’?

Form is submitting after refresh page in Php [duplicate]

I have two two “submit buttons”(multiple/displaying using loop) (inside form tag) but my problem is, form is submtting after refresh page instead of “click on submit”
I dont know where i am wrong ? Here is my code

<td class="project-state">
                       <form method="POST" name="status" action="" >
                           <input type="hidden" name="projectId" value="<?php echo $projectId; ?>">
                           <input type="hidden" name="UserId" value="<?php echo $projectId; ?>">
                           <input type="hidden" name="status" value="<?php echo "accept"; ?>">
                           <input type="submit" name="submit" value="Accept" class="btn btn-success">
                           </form>
  </td>
  <td class="project-actions text-right">
                <form method="POST" name="reject" action="" >
                           <input type="hidden" name="projectId" value="<?php echo $projectId; ?>">
                           <input type="hidden" name="UserId" value="<?php echo $projectId; ?>">
                           <input type="hidden" name="status" value="<?php echo "reject"; ?>">
                           <input type="submit" name="reject" value="Reject" class="btn btn-danger btn-sm">
                           </form>
 </td>

Here is my php code, but once i click on reject (showing in loop) then if i refresh page form submitting automatically instead of click on “reject”,How can i fix this ?

if(isset($_POST['reject']) && !empty($_POST['reject'])) {
                            echo "<pre>";print_R($_POST);
                         exit;
}  

Laravel : Hasmany relationship returning empty results

i have 3 tables

  1. shops
  2. packages
  3. shop_packages

as below

Shops

enter image description here

Packages

enter image description here

Shop Packages
enter image description here

i am using following relationship in Shop Model

 public  function  packages(){
    return $this->belongsToMany(Package::class,'shop_packages','shop_id','package_id');
 }

and below in Package Model

 public  function  shop(){
     return $this->belongsToMany(Shop::class,'shop_packages','package_id','shop_id');
 }

when i try to get

 Package::with('shop')->get();

it returns me packages but shops remain empty can someone please guide me how can i fix this

Laravel update query error using query builder with comma separeted values

I am getting the below error in the laravel controller when I update 4 columns with comma-separated values without quotes which are coming from the request

Request payload:
column1 : one,two,three
column2 : six,seven
column3 : eight,nine

 <?PHP
   function run(Request $request){
     $column1 = $request->get('column1');
     $column2 = $request->get('column2');
     $column3 = $request->get('column3');
     $save = DB::table('tableone')->where('primaryclm', '1')->update(['column1' => $column1,'column2' => $column2,'column3' => $column3]);
   }
 ?>

Error:
 SQL error (SQL: update `tableone` set `column1` = one,two,three 
,`column2` = four,five,six
,`column3` = seven,eight
 where `primaryclm` = 1)

Kindly help with this issue.

preg_replace for a time string

We are using a preg_replace to get a well formated time string. The result should look like this:

mo-sa9:00-20:00uhr => mo-sa 09:00-20:00uhr

The regex is:

preg_replace('=[^d](d{1})[.:](d{2})=U', ' 0${1}:${2}', $norm)

The result is: mo-s 09:00-20:00uhr

After many attempts, I found that I couldn’t seem to find a pattern that correctly formatted the time string.

The replacement seems to be the problem or am I looking at it wrong?

Can you implement a class onto existing object

Heylo,

Let’s say we have an object $var come to us from a source we cannot edit, is it possible to add an implemented class to that existing stdClass?

I know we could remap the existing $var properties onto a new class we create, but this could lose any methods that exist in the old object.

        $var = (object) ["prop" => "value"]; 
        // somehow implement ArrayAccess on existing stdClass $var
        echo $var["prop"]; // should work
        echo $var->prop; // should also work 

A WP Query for Posts and Pages but only returns 1 posts/pages

I’m trying to create a wp query that goes through posts and pages and only returns one (the most recent, being a post or a page). So far, I have this:

$conteudo_complexo = new WP_Query(array(
   'post_type'        => array('post', 'page'),
   'posts_per_page'   => 1,
   'orderby'          => 'date',
   'order'            => 'DESC',
   'meta_key'         => 'tipo_de_destaque_homepage',
   'meta_value'       => 'topoeditorial'
));

This is returning multiple pages…

What I’m looking for is something like: go through posts and pages and return only one post or page with that meta_value, whichever is the most recent one.

Note: The meta_key and meta_value is for custom fields.