Laravel – code optimization for selecting column differences within 7 days

I have this code. Finally, the player is returned with the levelDifference attribute for every day 7 days back. Could this be optimized to one sql query instead of looping and doing 7 queries?

Also, I would like to know if you can omit withMin and withMax and just get the difference between the smallest and the largest lvl on a given day?

$days = collect();

        foreach (range(1, 7) as $dayNumber) {
            $data = $game->players()
                ->withMin(
                    ['statistics' => fn ($query) => $query->whereDate('created_at', '=', now()->subDays($dayNumber))],
                    'level'
                )
                ->withMax(
                    ['statistics' => fn ($query) => $query->whereDate('created_at', '=', now()->subDays($dayNumber))],
                    'level'
                )
                ->get();

            $filtered = $data->filter(function ($item) {
                return $item->statistics_min_level && $item->statistics_max_level;
            });

            $dayStats= $filtered->values()->map(function ($item) {
                $item->levelDifference = $item->statistics_max_level - $item->statistics_min_level;

                return $item;
            });

            $days->put(
                $dayNumber,
                $dayStats
            );
        }

        return $days;

How to increment time from a date by x minutes to an end date excluding y breaks

Am new to php loops and need some advise on how to approach this:

I am looking for a way to echo/show incremented time slots, excluding break times. Here are the variables am going to be working with,

$Startdate=2022-09-1;
$EndDate=2022-09-02;

$Starttime=10:00;
$Endtime=18:00;

$TimeSlot_duration=30minutes;

$Breaktimestart=12:00;
$BreaktimeEnds=14:00;

I would want to be able to echo theses time slots and their count. Something like:

24 available slots:  
2022-09-1,10:00 
2022-09-1,10:30 
2022-09-1,11:00 
2022-09-1,11:30 
2022-09-1,14:00 
2022-09-1,14:30 
...etc

Any advise would be appreciated.

PHP validate if age input into registration form is over 18 [duplicate]

I’m trying to check if the birthday the user inputs in my html form is over 18 years.

function validate_form() {
    $errors = array(); 
    $insert = array();

    # stores date of birth.
    $insert['bday'] = array_key_exists('bday', $_REQUEST) ? $_REQUEST['bday'] : null;

    # this is line 66
    if  (date('Y') - $insert['bday'] <= 18)  {
        $errors[] = "<p> You need to be 18 years or older to create an account.</p>n";
    }

If for example the user chooses 2003 and below, the form submits successfully. if the user selects 2005 and above the error message displays as it should. However if i select 09/01/2004 (which was more than 18 years ago now) i still get the error message.

I also get this warning when the error page displays:

Warning: A non-numeric value encountered in C:xampphtdocsfilnamefilenamepagename.php on line 66

Moving icon after the text

I have this function to add an icon before the heading. I want to show the icon after the heading. Tried a lot of things didn’t work.

    public static function add_anchors($text)
    {

        // Search for headlines.
        $pattern = '#<h([1-6])(?: [^>]+)?>(.+?)</h1>#is';
        preg_match_all($pattern, $text, $headlines, PREG_OFFSET_CAPTURE);

        $offset = 0;

        if ($headlines) {
            foreach ($headlines[2] as $match) {
                list($headline, $pos) = $match;

                if (strlen($headline)) {
                    $anchor = sanitize_title($headline);
                    $icon = '<a href="#' . $anchor . '" aria-hidden="true" class="aal_anchor" id="' . $anchor . '"><svg aria-hidden="true" class="aal_svg" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>';

                    $text    = substr_replace($text, $icon, $offset + $pos, 0); // Insert after H tag.
                    $offset += strlen($icon);
                }
            }
        }

        return $text;
    }
}

Pull all data for specific username in DB table [duplicate]

I have a mysql DB table called ‘user_order_token’ with the values

`id`, `username`, `token_value`, `token_amount`, `amount`, `reminder_status`, `amount_received`, `address`, `network`, `label`, `status`, `created_by`, `created_at`, `updated_by`, `updated_at

I am trying to pull the values for the user who is logged in, but i cant even pull data for a static user “test”.

<?php 
$data = mysql_query("SELECT * 
                    FROM 'user_order_token' 
                    WHERE 'username' ='test'"); 
$info = mysql_fetch_array( $data );
?>


My Stakes

<?php echo $info; ?>

Currently the code above hides “My Stakes” and dont seem to be pulling any information from my DB, what am i doing wrong! 🙁

oci_fetch_assoc it returns only the first row of the table

I am new to OCI and PHP and I am trying to print the data from an oracle table but I am getting an error. The error is that when printing the data of a table there is the oci_fetch_assoc function that only prints the first row of this table and I don’t really understand why. This is the code block where I try to print the data:

 <?php
    include("../controllers/conexion.php");
    $db_connection = oci_connect($db_esquema, $db_password, $db_instance);
    $stid = oci_parse($db_connection, 'SELECT * FROM PRODUCTOS ');
    oci_execute($stid);
                                  
    while ($fila = oci_fetch_assoc($stid)) {
         
         echo "<tr data-id=" . $fila['IDPRODUCTO'].">";
            echo "<td>". $fila['NOMBRE']."</td>";
            echo "<td>". $fila['PRECIO']."</td>";
            echo "<td>". $fila['DESCRIPCION']."</td>";
            echo "<td>"."<a href=".'"eliminarProducto.php?id='. $fila['IDPRODUCTO'].'" class="btn btn-danger" > <i class="fas fa-trash-alt"></i></a><a href="modificarProducto.php?id=' .$fila['IDPRODUCTO'].'" class="btn btn-secondary"><i class="fas fa-marker"></i></a></td>';
         echo "</tr>";
     }
   oci_free_statement($stid);                                        
   oci_close($db_connection);

   
 ?>

This is the output but, there is much more data in the table:
enter image description here

Get Image file system location in Drupal

I have some custom code to display some images, the method used is somethign like this

$image_url = ImageStyle::load('del_photo')->buildUrl('private://del-photos-cropped/Haglewhit_Feb22_1.jpg');

This produces a url like this

"https://mywebsite.url/system/files/styles/del_photo/private/del-photos/Haglewhit_Feb22_1.jpg?itok=ie69Z5G4"

However, when I do something like this, I get false indicating it can’t find the file.

Drupal::service('file_system')->realpath('private://del-photos-cropped/Haglewhit_Feb22_1.jpg')

What am I missing here, I’m a newbie to drupal so any help or guidance would be appreciated

PHP Disable Option when its Active on Database

I have a database where there is responders and a eventstatus. my responders has options Team A and Team B and my eventstatus is pending active and complete

if event is Active and for example responder it = Team A i wanted it to be disabled in the option here is my code

            <select class="form-select text-capitalize" aria-label="Default select example" name="eRes">
          <?php
          $sql1 = "SELECT responders FROM tbemergency WHERE eventstatus='Active'";
          $result1 = $con->query($sql1); 
          if ($result1->num_rows > 0) {
            $result_fetch = mysqli_fetch_assoc($result1);
            if($result_fetch['responders'] == 'Team A'){ ?>
              <option value="Team A" disabled>Team A</option>
            <?php }else { ?>
              <option value="Team A" >Team A</option>
            <?php } ?>
          <?php 
            if($result_fetch['responders'] == 'Team B'){ ?>
              <option value="Team B" disabled>Team B</option>
            <?php }else { ?>
              <option value="Team B" >Team B</option>
            <?php }
          } ?>

this is my code that i am using and whats happening is only Team A is disabled where i also have an active eventstatus with team b

json_encode returns false while return data from array,,

I am using php version 7.1.3 with the symfony version 4.2.12
here is the array data

$json = [
                'totalVehicle' => $totalVehicle,
                'totalPrice' => $totalPrice,
                'vehicles' => $xvehicles,
                'toDateTime' => $toDateTime,
                'fromDateTime' => $fromDateTime,
                'distanceMile' => $distanceMile,
                'toCity' => $toCity,
                'fromCity' => $trip->getFromPlace(),
                'trip' => $trip,
                'adaAssistance' => $request->get('ada', false),
                'vehiclesCount' => $vehiclesCount,
                'pageCurrent' => $request->get('page', 0),
                'uri' => $uri,
                'maxPage' => floor($vehiclesCount / 15),
                'isSubscribed' => $isSubscribed,
            ];

when i use dd($json) it returns the actual array,

dd($json);

enter image description here

when i want to return it in json format by using json_encode it return false,

$json = json_encode($json,0,512);

dd($json) after json_encode
enter image description here

I tried to change the depth upto 1024 but the result is same with false return,
Please help me out to solve this,

What’s wrong with PHP8 mysql / mysqli client?

It says there is a problem with SQL, but to me it is good + if i put it in the phpmyadmin it is executed without problems.

INSERT INTO `searches` 
            (`anagram`,`q`,`ip`,`min`,`max`,`game`) 
    VALUES ('anagrams','WORD','1.1.1.1',2,15,'game')

“You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near ”anagrams’,…………”

Also if i try to execute it in solo command like below and put the quoted query in $q_ it seems to work

$db->query($q_);

So basically it works at some place of app and doesn’t work at other place but the sql is same…

How to use select values for form action

I am trying to pass the select values for form action URL for wordpress,

    $args_shortcode = shortcode_atts(array(
    
        'category_name' => ''
    
    ), $attr);
    $condition = "";
    if(isset($_POST['Collateral_services'])){
      $condition = "/?Collateral_services=".$_POST['Collateral_services'];
    }
    $action_url = site_url() . "/category/" . $args_shortcode['category_name'] . $condition;

As you can see, the action url will redirect user to a different page which is getting fetched from shortcode attribute, so $_POST['Collateral_services'] is not fetching any data because it needs to be on search result page,

But the action URL needs to be based on selected option of the form, so I am not getting how can I change values in url after "/category/" using javascript or jQuery ?

form:

<form method="POST" action="<?php echo $action_url; ?>">

      <div class="form-group">
        <div class="col-xs-12 col-sm-12">
          <select name="Collateral_services" class="custom-select-input">
          <option value="" disabled selected>All Services</option>
            <?php
            foreach ($terms_ser as $term_ser) {
            ?>
              <option value="<?php echo $term_ser->slug; ?>"><?php echo $term_ser->name; ?></option>
            <?php } ?>
          </select>
        </div>
      </div>
<div class="custom-search-button-align">
        <input type="submit" value="Filter" class="custom-search">
      </div>
    </form>

Get the dates that fall under that week number

So I came up with a situation where I want to retrieve the dates that fall under a specific week number. I tried some methods but unfortunately, they did not work out.

So first I am getting the week number of the date that I have/selected/inputed.

$week_number = date('W', strtotime(23/08/2022)) //Will output 34

What I tried to do… But the dates that are being returned are random and not what I am expecting

$dates = array();
for($i = 1; $i <=7; $i++){
$dates[$i] = date('Y-m-d', strtotime($selected_date . ' -' . ($week_number) . ' days +' . 
$i . ' days'));
}

What I am expecting:

[1] => 2022-08-22
[2] => 2022-08-23
[3] => 2022-08-24
[4] => 2022-08-25
[5] => 2022-08-26
[6] => 2022-08-27
[7] => 2022-08-28

I don’t know if this is a duplicate question but I cannot find what I am looking for.

SyntaxError: “[object Object]” is not valid JSON

I have a problem with the follwoing code. console.log output is:

My requestedt URL via javascript ajax request is the “login.php”:

 <?php include('init.php');
    use LoginLoginService;

    #include(__DIR__.'/Login/LoginService.php');
    
    global $pdo;
    session_start();
    
    $username = $_POST['username'];
    $pass = $_POST['password'];
    if (!empty($username)) {
        $test = new LoginService();
        $user = $test->getUsersLogin($username);
        if (!empty($user) && $user[0]['login'] == $username) {
            $json = json_encode(array("success" => 1));
            echo $json;
        } else {
            $json = json_encode(array("success" => 0));
            echo $json;
        }
    }
    ?>

my ajax request via js:

$(() => {
    $('.login-form').on('submit', function (e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            dataType: "json",
            timeout: 500,
            url: '/src/login.php',
            data: $(this).serialize(),

            success: (data) => {
                try {
                    var jso = JSON.parse(data);
                    console.log(jso);
                } catch (e) {
                    console.log(e);
                    return false;
                }
            },
            error: (data) => {
                console.log(JSON.parse(data));
            }
        });
    });
});

Why the response from the php {"success":1} is not right? What is the problem?

SyntaxError: “[object Object]” is not valid JSON

How can i automatically HREF the articles of my MongoDB database to each article specific page?

Hello everyone i’m working on a site which is more a DB project that anything else currently i mainly use my mongoDB database to show the previews of those articles after querring them with these functions (which are in 2 different files)


//this one is from the functions file which i load in all the various pages of the site
function article_recordset(){
   

require 'vendor/autoload.php';

$client = new MongoDBClient("mongodb://localhost:27017");
$i = 0;
$SiteArticles = $client->SiteArticles;
$articoli=$SiteArticles->Articles;
$cursor = $articoli->find();
return $cursor;

    foreach ($cursor as $articolo) {      
        $recordset = array(
            $i=$i+1 => array(
                "title" => $articolo["title"],
                "description" => $articolo["content"],
                "article" => "",
            )
        );
    }

}    

//this is the index.php file so the homepage where i display the articles which i stored into an array and then i display with an echo later


include("funzioni.inc.php");//name of the functions file

$ARR_articles = article_recordset();

$STR_article = NULL;

foreach($ARR_articles as $index => $article){
    $STR_article .= get_article_item_html(
        $img_path = "img/article/".$index.".jpg", 
        $title = $article["title"], 
        $description = $article["content"]
    );
}

The display works fine and all but what i’m trying to do is to HREF each displayed article preview to their own article page

So article 1 is displayed and is linked to the page of localhost/folder/article1.php for exhample

now the href i want to do is somewhat automatic so it links to each article page which i manually created already just like it does the foreach for the query of all the article contents

so like it’s gonna store each article in the array which i display later while also like setting an href to each one

eg

Query article 1, store into array, display that array content for article 1 and href it to it’s own page
and so on for each article

Note: I want to “”automatize”” just the HREF of each querried article not automatise the article page creation since i have those pages already created and it’s for a small project and nothing too serious

How to get linked orders in Laravel

I am actually working on a multivendor order system. Here is my order table.

+----+--------+--------------+------------+-----------------+
| id | userid | bookstore_id | payment_at | parent_order_id |
+----+--------+--------------+------------+-----------------+
|  1 |      1 |            2 |   null     | null            |
|  2 |      1 |            3 |   null     | 1               |
|  3 |      1 |            1 |   null     | 1               |
+----+--------+--------------+------------+-----------------+

Now, whenever a user places an order with the same bookstore, the quantity is updated, and when a user creates an order with a different bookstore, the new order is created. Now what I want here is to link child orders with parents’ orders, so for that I have added parent_order_id column where I can put the order id of the parent order. Basically, when I view the details of order id 1, then I want to show the order with id 2,3 in linked order, and when I view order 2, then order 1,2 like that.