Sort wp_query results by parent page title

I’m trying to sort an array alphabetically based on the parent page title. I have a query that retrieves all pages with a specific page template. When outputting the retrieved pages I need to sort them by the title of the parent page and not the title of the retrieved page itself.

What I have so far:

$opnamePages = new WP_Query(array(
    'post_type'         => 'page',
    'posts_per_page'    => -1,
    'post_status'       => 'publish',
    'orderby'           => 'title',
    'order'             => 'DESC',
    'meta_key'          => '_wp_page_template',
    'meta_value'        => 'templates/dienst-sub-opname-page.php'
));

if($opnamePages->have_posts()){
    echo "<div class='subNavigationDropdown'>";
        echo "<div class='dropdown'>";
            while($opnamePages->have_posts()){
                $opnamePages->the_post();
                $parentPage = wp_get_post_parent_id(get_the_ID());

                    echo "<a href='".get_permalink()."' title='Ga naar ".get_the_title()."'>".get_the_title($parentPage)."</a>";
            }
        echo "</div>";
    echo "</div>";
wp_reset_postdata();

}

How do I get the path of the current php file relative to the web root folder and not to the system root folder?

Some years ago I developed a web app which contained the following code in a php file located in the root folder of the app:

define('APP_ROOT', dirname(__FILE__) . DIR_SEP);

This was to allow the app to be installed in any sub directory of the web docs folder and not necessarily directly in the web root itself, so that the app had a base path from which to dynamically calculate any other paths used in the app.

My test system back then was an Xampp installation running on Windows 7. I no longer have that system, but I believe the path to the htdocs folder was C:xampphtdocs and my app was contained in C:xampphtdocstimesheets. On that system, the value of APP_ROOT was timesheets/, exactly as I wanted.

I know that the customer ran the app on a Linux server and I believe the app was installed in /var/www/timesheets/. So the value of APP_ROOT was timesheets/. I know this worked correctly because he never needed to modify my code.

I am now trying to use the same code again, but my test system is Ubuntu 20.04 with Apache 2.4 and PHP 7.4. The value I am getting in APP_ROOT is /var/www/html/timesheets/, which is causing all my dynamic path calculations to be wrong.

I have tried setting doc_root and open_basedir in php.ini, but I am still getting the full absolute path. I think this must be to do with the server or php configuration, but I have searched the web and cannot find how to correct it.

PHP query to delete a camp from a specific row not working

So, i’m doing a little CRUD as a project to train PHP so I can move on an learn symfony. To give context, it’s a school managing system, with teachers, classes, students, etc. In this page i’m trying to delete the class, which works, however I want it to set the class to NULL in all students which were part of that class. For example:

jake - 11 years -  classA 
*classA deleted*
jake - 11 years - NULL

There’s also another query in the code which does the same thing, but to a specefic relation table between classes and students, which only has the student id and the class name.

Here’s the code below

<?php

if(isset($_POST["id_turma"]) && !empty($_POST["id_turma"])){

    $turma=trim($_GET["turma"]);
    echo $turma;
    // Include config file
    require_once "config.php";
    
    // Prepare a delete statement
    $sql = "DELETE FROM turmas WHERE id_turma = ?";
    
    $sql2 = "UPDATE alunos SET turma = 'NULL' WHERE turma = ".$turma;
    mysqli_query($link,$sql2);

    $sql3 = "DELETE FROM turmaalunos WHERE turma =".$turma;
    mysqli_query($link,$sql3);
    if($stmt = mysqli_prepare($link, $sql)){
        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($stmt, "i", $param_id);
        
        // Set parameters
        $param_id = trim($_POST["id_turma"]);
        
        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt)){
            // Records deleted successfully. Redirect to landing page
            header("location: turmas.php");
            exit();
        } else{
            echo "Oops! Something went wrong. Please try again later.";
        }
    }
     
    // Close statement
    mysqli_stmt_close($stmt);
    
    // Close connection
    mysqli_close($link);
} else{
    // Check existence of id parameter
    if(empty(trim($_GET["id_turma"]))){
        // URL doesn't contain id parameter. Redirect to error page
        header("location: error.php");
        exit();
    }
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Delete Record</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
    <style>
        .wrapper{
            width: 600px;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <h2 class="mt-5 mb-3">Delete Record</h2>
                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>" method="post">
                        <div class="alert alert-danger">
                            <input type="hidden" name="id_turma" value="<?php echo trim($_GET["id_turma"]); ?>"/>
                            <p>Tem mesmo a certeza que deseja eliminar a informação desta turma?</p>
                            <p>
                                <input type="submit" value="Yes" class="btn btn-danger">
                                <a href="index.php" class="btn btn-secondary">No</a>
                            </p>
                        </div>
                    </form>
                </div>
            </div>        
        </div>
    </div>
</body>
</html>

PHP Error on IIS 10: No input file specified

I’m running a site on a dev. machine with the following features:

  • Operating System: Windows 11 (21H2, 22000.739)
  • Internet Information Server (IIS): 10.0.22000.739
  • PHP: 8.0.21 (and some others), Non-thread-safe, x64

Whenever I try to access a PHP file, for instance via http://localhost/test-php/index.php, I get a response:

No input file specified.

The website is running, because a flat HTML file (http://localhost/test-php/index.html) can be viewed without problem.

No errors are recorded in the PHP log file.


The machine in which this happens had been working with PHP with no problems previously. As we do not use it very often for PHP development, I cannot really tell what was installed or upgraded between the moment where it was working and now. Most probably: a number of Windows Updates + installation of Visual Studio 2022.


We have tried all kind of tests, as suggested by various posts on stack overflow and some other places. These include:

  • Making sure there are no file permissions problems (setting all permissions to “everyone” for all folders and files involved).

  • PHP.ini: set to value/set to blank/comment out: doc_root

  • PHP.ini: set to value/set to blank/comment out: open_basedir

  • PHP.ini: set cgi.force_redirect = 0 and cgi.force_redirect = 1

  • PHP.ini: leave completely empry

  • PHP.ini: minimalistic: include only recommendations from PHP Manager (cgi.force_redirect = 0, cgi.fix_pathinfo = 1, fastcgi.impersonate = 1, etc.)

  • PHP.ini: copy one from a machine where IIS+PHP is working as expected

  • Install several versions of PHP (7.4, 8.0.21, 8.1.latest)

  • Install PHP by using different methods: download .ZIP and install “by hand”, use Microsoft Web Platform Installer, use PHP Tools for Visual Studio.

  • Set up PHP under IIS via PHP Manager (version 2.7)

  • Set up PHP under IIS manually (create handler mapping and FastCGI settings from IIS Manager)

  • Completely uninstall and reinstall IIS from the machine.

Current settings in web.config are:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="php-8.0.21" path="*.php" verb="GET,HEAD,POST" modules="FastCgiModule" scriptProcessor="C:PHP80php-cgi.exe" resourceType="Either" requireAccess="Script" />
        </handlers>
        <defaultDocument>
            <files>
                <clear />
                <add value="index.php" />
                <add value="index.html" />
            </files>
        </defaultDocument>
    </system.webServer>
</configuration>

Current PHP.ini (minimalistic):

[PHP]
extension_dir = "C:PHP80ext"
log_errors = On
error_log = "C:WINDOWSTempphp-8.0.21_errors.log"
upload_tmp_dir = "C:WINDOWSTemp"
cgi.force_redirect = 0
cgi.fix_pathinfo = 1
fastcgi.impersonate = 1

[Session]
session.save_path = "C:WINDOWSTemp"

[Date]
date.timezone = "Europe/Paris"

Current C:WindowsSystem32inetsrvconfig

<fastCgi>
    <application fullPath="C:PHP80php-cgi.exe" monitorChangesTo="C:PHP80php.ini" activityTimeout="300" requestTimeout="300" instanceMaxRequests="10000">
        <environmentVariables>
            <environmentVariable name="PHPRC" value="C:PHP80" />
            <environmentVariable name="PHP_FCGI_MAX_REQUESTS" value="10000" />
        </environmentVariables>
    </application>
</fastCgi>

What we’ve already checked (with no success)

Frustratingly enough, all the changes we’ve made up until now have had no success at all; nor a hint in how to solve the problem. The fact that the machine used to work seems to indicate that the problem might be related to either:

  • Installing something “incompatible” that broke ALL existing PHP installations and all existing PHP websites.
  • Updating something (maybe some component of Microsoft IIS itself) that broke hell loose.

Any help will be greatly appreciated

PHP: Can I use stream_socket_server to get free tcp port of the server

When you specify port to 0 stream_socket_server(“tcp://xx.xx.xx.xx:0“), you can get the unused port. It works perfectly when I pass localhost as an IP, but when I try to get an unused port of a remote server I keep getting Unable to connect to tcp://xx.xx.xx.xx:0 (Cannot assign requested address).

Is there something am I missing? Is it even possible to use it in such a way?

change the parameter depending on the connection location

I have a code that protects against spam the send link to the mail

@if(filter_var($email, FILTER_VALIDATE_EMAIL))
@php

$split = explode('@', $email);
$first = $split[0];
$second = $split[1];

@endphp
<a data-first="{{ $first }}" data-second="{{ $second }}" class="js-combaine-email"></a>
@endif

It is used in two places on the site. And I want to add gtag to this link on click

<a onclick="gtag('event', 'email_click', {
  'event_category' : 'website_clicks',
  'event_label' : 'location_email'
});" data-first="{{ $first }}" data-second="{{ $second }}" class="js-combaine-email"></a>

But I want the event_label to change depending on the location it is in, let’s say for one 'event_label' : 'location1_email' and for another 'event_label' : 'location2_email'

I think I need to somehow add the eventLabel parameter and pass it depending on the connection location

But how can I implement all this, please tell me

`wire:model` not letting selected value to be selected

A select element with a pre-selected value does not render correctly, if I do not add wire:model to the element, it works well and shows the selected value in the select element.
But I need to add wire:model to save user-updated data

@foreach ($this->result as $data)
<select wire:model="list_session_picker.{{ $data->id }}" wire:key="{{ $data->id }}">
       <option value="" disabled hidden>Select Session</option>
       @foreach ($sessionData as $session)
       <option value="{{ $session->id }}">{{ $data->user_session_id == $session->id ? 'selected' : '' }} {{ $session->session }}</option>                                                               
        @endforeach
</select>
@endforeach

It works if I remove wire:model, so how could I show the selected value while using wire:model or is there any other way ?

I found this solution, but how to apply it in my case

How to loop out all names and ID’s from a database table (php memchached)

How can we loop and print out all the names and ID’s from the table?

<?php
$memtest = new Memcached();
$memtest->addServer("127.0.0.1", 11211);
$conn = mysql_connect("localhost", "tzvsqktpzm", "XWwgPDZ52R") or die(mysql_error());
mysql_select_db("tzvsqktpzm") or die(mysql_error());
$query = "SELECT ID FROM sample_data WHERE name = 'some_data'";
$retval = mysql_query( $query, $conn );
$result = mysql_fetch_array($retval, MYSQL_ASSOC);
$querykey = "KEY" . md5($query);
$memtest->set($querykey, $result);
$result2 = $memtest->get($querykey);
if ($result2) {
print "<p>Data was: " . $result2['ID'] . "</p>";
print "<p>Caching success!</p><p>Retrieved data from memcached!</p>";
}
?>

SQLSTATE[HY000]: General error: 1364 Field ‘debit_limit’ does

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 1364 Field ‘debit_limit’ doesn’t have a default value in /home/maneyao/public_html/controller/panel/signup.php:95 Stack trace: #0 /home/maneyao/public_html/controller/panel/signup.php(95): PDOStatement->execute(Array) #1 /home/maneyao/public_html/ProffessorwithAST.php(178): require(‘/home/maneyao/p…’) #2 /home/maneyao/public_html/index.php(10): require_once(‘/home/maneyao/p…’) #3 {main} thrown in /home/maneyao/public_html/controller/panel/signup.php on line 95

Information not updating to database after deselecting a checkbox

I am having issues when I untick a checkbox and leave it blank and update my PHP / MySQL form, the data is not saved in the database. Updates text / date fields are working fine.

Code

$learning_opportunities = isset($_POST['learning_opportunities']) ? $_POST['learning_opportunities'] : $contact['learning_opportunities'];

  $stmt = $pdo->prepare('UPDATE contacts SET current_living_situation=?, personal_strengths=?, skills_training=?, currently_spend_time=?,personal_goals=?,housing_situation_transport_childcare=?,
   learning_actual_end_date=?, partcipant_complete_course=?, withdrawal_reason=?,participant_intended_learning=?,pcp_education=?,
   coursestart_date=?,education_provider_name=?,course_title=?,course_level=?,planned_glh=?,in_paid_employment=?,in_paid_employment_start_date=?,
   in_paid_employer_name_address=?,in_paid_job_title=?,in_paid_contracted_hour=?,not_in_paid_employment=?,pcp_gap_year=?, 
   pcp_others=?,pcp_voluntary_work=?,destination_progression_date=?,destination_progression_collection_date=?,project_officer_name=?,
   project_officer_signature=?,project_officer_date=?,participant__name=?,participant__signature=?,participant__date=?,
   final_assessment_progress_you_made=?,final_assessment_progress_your_goal=?,final_assessment_progress_your_reach_goal=?,
   final_assessment_progress_overall=?,final_assessment_participat_name=?,final_assessment_participat_signature=?,
   final_assessment_participat_date=?,final_assessment_project_worker_name=?,final_assessment_project_worker_signature=?,
   final_assessment_project_worker_date=?,learning_opportunities=?,contact_for_other_purposes=?,empowering_communities=?,empowering_communities_name=?,empowering_communities_sign=?,empowering_communities_date=?,
   participant_enrolled_onto=?,participant_moved_another_provider=?,participant_eligible_free_school=?,british_passport=?,
   eec_passport=?,euss_via_home=?,preferred_evidence=?,provide_preferred_evidence=?,option_adoption_vertificate=?,option_driving_licence=?,
   option_non_eu_passport=?,option_biometric_immigration=?,option_current_immigration=?,option_marriage_civil_partnership=?,
   option_other_evidence=?,option_nine=?,details_evidence_provided=?,dwp_job_centre_letter=?,confirmation_relevant_organisation=?,self_certification_evidence=?,
   partcipant_told_support=?,participant_file_completed_remotly=?,declaration_name_please_print=?,declaration_job_title=?,declaration_organisation=?,
   declaration_signature_date=?,declaration_signature=? where id = ?');
  
  $result = $stmt->execute([$current_living_situation,$personal_strengths,$skills_training,$currently_spend_time,$personal_goals,
  $housing_situation_transport_childcare,$learning_actual_end_date,$partcipant_complete_course,$withdrawal_reason,$participant_intended_learning,$pcp_education,
  $coursestart_date,$education_provider_name,$course_title,$course_level,$planned_glh,$in_paid_employment,$in_paid_employment_start_date,
  $in_paid_employer_name_address,$in_paid_job_title,$in_paid_contracted_hour,$not_in_paid_employment,$pcp_gap_year,$pcp_others,
  $pcp_voluntary_work,$destination_progression_date,$destination_progression_collection_date,$project_officer_name,$project_officer_signature,
  $project_officer_date,$participant__name,$participant__signature,$participant__date,$final_assessment_progress_you_made,
  $final_assessment_progress_your_goal,$final_assessment_progress_your_reach_goal,$final_assessment_progress_overall,$final_assessment_participat_name,
  $final_assessment_participat_signature,$final_assessment_participat_date,$final_assessment_project_worker_name,$final_assessment_project_worker_signature,
  $final_assessment_project_worker_date,$learning_opportunities,$contact_for_other_purposes,$empowering_communities,$empowering_communities_name,$empowering_communities_sign,$empowering_communities_date,
  $participant_enrolled_onto,$participant_moved_another_provider,$participant_eligible_free_school,$british_passport,
  $eec_passport,$euss_via_home,$preferred_evidence,$provide_preferred_evidence,$option_adoption_vertificate,$option_driving_licence,
  $option_non_eu_passport,$option_biometric_immigration,$option_current_immigration,$option_marriage_civil_partnership,$option_other_evidence,$option_nine,
  $details_evidence_provided,$dwp_job_centre_letter,$confirmation_relevant_organisation,$self_certification_evidence,$partcipant_told_support,
  $participant_file_completed_remotly,$declaration_name_please_print,$declaration_job_title,$declaration_organisation,$declaration_signature_date,
  $declaration_signature, $_POST['id']]);
  
  if($result == true){
      $details = "<b>All Data Updated</b>";
      // Insert new record into the contacts table
          $stmt = $pdo->prepare('INSERT IGNORE INTO client_activity (id,client_id,date,time,details,username) VALUES (?,?,?,?,?,?)');
        $client_activity = $stmt->execute([ null,$_POST['id'],date("Y/m/d"),date("H:i:s"),$details,$_SESSION['name'] ]);
        if($client_activity == true){
          $msg = 'Updated Successfully!';

Form code

<input type="checkbox" name="learning_opportunities" value="learning_opportunities" <?php if($contact['learning_opportunities']=="Yes"){ echo 'checked'; } ?>> About courses or learning opportunities.<br>

I have read countless articles and tutorials and can’t get it to update the data.

How to get Google reviews for a business without specific address and placeId?

Right now, we have a flow, where we import Google reviews on sign up and then update them daily. We get the user’s company name and location address:

$requestUri = 'https://maps.googleapis.com/maps/api/place/autocomplete/json?key={key}&input=A+Closer+Look+Residential+Inspections%2C+LLC%2C+9230+Fowler+Ln%2C+Lanham%2C+MD+20706%2C+United+States';

From autocomplete we can get placeId and search for reviews by placeId:

$requestUri = 'https://maps.googleapis.com/maps/api/place/details/json?key={key}&place_id=ChIJmyUG8bfBt4kRqqn8jPZYhDo';

And this worked fine.

Issue
We have a new user which dont have location address, so we can’t get placeId. The user has reviews on Google if to search for them in the search bar.

Company name is: “Westside Home Inspections Inc.”. Google Map shows that they works in whole LA (not address, but area). Then i tried to get a placeId here: https://developers.google.com/maps/documentation/places/web-service/place-id . But with no luck.

Question:
Is this possible to get Google reviews only by company name?

How to call function from another class in the widget array?

I have a yii application. And I am using the

widget('bootstrap.widgets.TbGridView

and in the column value of the widget I have this function:

<div class="row-fluid">
    <div class="span12">
        <?php $this->widget('bootstrap.widgets.TbGridView', [
            'id' => 'result-grid',
            'type' => 'striped bordered condensed hover',
            'pagerCssClass' => "pagination viewpager",
            'template' => "{summary}{items}n{pager}",
            'dataProvider' => $result,
            'columns' => [
                [
                    'class' => 'bootstrap.widgets.TbButtonColumn',
                    'template' => '{Link}',
                    'buttons' => [
                        'Link' => [
                            'options' => ['class' => "btn-block viewEntry", 'target' => '_blank'],
                            'url' => function (Result $result) {
                                return $result->page_link;
                            },
                        ],
                    ],
                ],
                [
                    'htmlOptions' => ['style' => 'width: 150px'],
                    'name' => 'coc_number',
                    'value' =>  function(Result $result){

                       return $result -> kvknumber($result);

                    }                  
                ],              
            
        ]); ?>

  </div>
</div>

And the model Resul looks like this:


class Result extends CActiveRecord
{
    protected function getProductPageUrl()
    {
        return '<a href="' . $this->page_link . '" target="_blank"> ' . '<i class="fa fa-globe"></i>' . '</a>';
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'scrape_result';
    }

    public  function kvknumber(Result $result)
    {
        $requestString = Google::GOOGLE_BASE_URL . 'key=' . Google::GOOGLE_API_KEY .
            '&cx=' . Google::GOOGLE_CX . '&q=' . $result->page_url .
            '"kvk"' . '&lr=lang_nl';


        $clear = GuzzleHttpjson_decode((new Client)->request('GET', $requestString)->getBody()->getContents());
        

        if (property_exists($clear, 'items')) {
            foreach ($clear->items as $item) {
                if (property_exists($item, 'snippet')) {
                    if (strpos(($item->snippet), 'KvK') !== false) {

                        //      echo 'snippet' . $item->snippet;
                        preg_match('/[0-9]{8}/', $item->snippet, $match);

                        //  echo ('match' . $match[0]);

                        if (isset($match[0])) {
                            $result->coc_number = $match[0];
                            $result->save();
                        }
                        sleep(4);
                    }
                }
            }
        }      

        return $result->coc_number;
    }
}

But when I load the page I get this error:

Fatal error: Maximum execution time of 120 seconds exceeded in C:xampphtdocswebScraperprotectedmodulesscrapemodelsResult.php on line 57

So my question is. How to resolve this?

I created this php to display the products when I select different filters. I managed in color and size but for the price I don’t know how I could

This is my code and I want only products with that size to appear when I select a size. in color and size I succeeded but at the price I do not know how I could do.

                $culoare ="";
                $marime ="";
                $price ="";
                if(isset($_POST['submit'])) {
                    echo "";
                    if(isset($_POST['colorfilter'])) {
                        $culoare = $_POST['colorfilter'];
                    }
                    if(isset($_POST['sizefilter'])) {
                        $marime = $_POST['sizefilter'];
                            
                    }
                    
                    }
            ?>
            


            <div class="container">
                <div class="filters">
                    <form action = "container.php" method = "POST">
                    
                    <h1>Price</h1>
                    <div class>
                        <input type = "radio" name = "price" id = ">=200" value = "1" >
                        <label for=">=200">>= 200</label>
                        <input type = "radio" name = "price" id = "<price" value = "2">
                        <label for="<price">< 200</label>
                    </div>
                        <input type = "submit" value = "Submit" name="submit">
                    </form>
                </div>

axios delete method to php pdo [closed]

        <tbody>
            <tr v-for="build in building" :key="build.building_id">
                <td>{{build.building_id}}</td>
                <td>{{build.building_name}}</td>

                <td class="p-1 mx-auto">
                    <button class="btn btn-warning">Edit Data</button>
                    <button @click="deleteData(build.building_id)" class="btn btn-danger">Remove Data</button></td>
            </tr>
        </tbody>
<script>
import axios from 'axios'
export default {
    name: "tableDataBuilding",
    data() {
        return {
            title: "Table building",
            building: [],
            building_id: {}
        }
    },
    methods: {
        deleteData(id) {
            let URL = 'http://127.0.0.1/api_apartment/room/delete/delete_build.php/${id}'
                axios.delete(URL)
                .then((resp) => {
                    console.log(resp);
                    this.building = resp.data;
                });
        }
    }

</script>