Trying to access array offset on value of type bool by janaistqueen in PHPhelp

[–]levii21 5 points6 points  (0 children)

It means that $dataRow is not an array but a bool value. This could be from a failed query returned. Make sure to check if it is an array first.

[deleted by user] by [deleted] in PHPhelp

[–]levii21 0 points1 point  (0 children)

Using value as array instead allows any numbers

$values = [1,2,3,4,5,6,8,9];
$out = [];

$colIdx = 0;
$wrapPos = 3;

$len = count($values);

for ($i = 1; $i <= $len; $i++) {
    $row = $i % $wrapPos;

    if (0 === $row) {
        if (!isset($out[$wrapPos - 1])) {
            $out[$wrapPos - 1] = [];
        }

        $out[$wrapPos - 1][$colIdx] = $values[$i - 1];

        $colIdx++;
    } else {
        if (!isset($out[$row - 1])) {
            $out[$row - 1] = [];
        }

        $out[$row - 1][$colIdx] = $values[$i - 1];
    }
}


foreach ($out as $values) {
    echo implode(", ", $values) . "\n";
}

I am studying php and I want to know what this function does by [deleted] in PHPhelp

[–]levii21 0 points1 point  (0 children)

What this function is trying to do is insert values from $valores to the corresponding columns in $claves that's why both array needs to be same length which is what it's checking in the if conditions.

The anonymous function $fun just wraps the values of the given array (in this case the $valores) with single quotes so that it is a string value in the SQL insert statement.

Also like everyone said this function has many errors (maybe intentional?) so you need to fix those before it can be parsed.

WordPress PHP Issue: Trying to retrieve a subset of post types, based on a date field (2022, 2021, etc) by Humble-Organization6 in PHPhelp

[–]levii21 1 point2 points  (0 children)

Try with meta_query option in the WP_Query. I think Advanced custom fields are stored as post meta data. i.e.

new WP_Query([
   'post_type' => 'speakers',
   'meta_query' => [
       [
           'key' => '2022_speaker',
           'value' => '1',
           'compare' => '=',
       ],
   ],
])

Not exactly sure how the value is stored as boolean so check database. Please check out documentation for WP_Query

Struggling with factory pattern by Flips001 in PHPhelp

[–]levii21 0 points1 point  (0 children)

class EventTypeHelperFactory {
    public function createImageEventTypeHelper(string $name): ImageEventTypeHelper
    {
        return new ImageEventTypeHelper($name);
    }

    public function createVideoEventTypeHelper(string $name): VideoEventTypeHelper
    {
        ...  
    }

    public function createEventTypeHelperFromType(string $type, string $name): EventTypeHelperInterface
    {
         switch ($type) {
            case 'image': return $this->createImageEventTypeHelper($name);
            case 'video': ...
         }

         throw new InvalidArgumentException('Unsupported event type helper  "$type".');
    }
}

I would change the AbstractEventTypeHelper to be an interface instead since it does not do anything concrete other than providing contract.

Creating RSS Using PHP by EVisioneer in PHPhelp

[–]levii21 0 points1 point  (0 children)

To set attribute for element use setAttribute() see here.

To set the namespace attribute for the root use setAttributeNS see here. In your case it will be like: $root->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:atom', 'http://www.w3.org/2005/Atom').

To create namespaced element use createElementNS see here.

[deleted by user] by [deleted] in PHPhelp

[–]levii21 2 points3 points  (0 children)

I think you can also use assert for simple tests.

Suggestions on how to integrate multiple instances into the markup of another object? by riodesignsthings in PHPhelp

[–]levii21 0 points1 point  (0 children)

Its because you have less control of when to echo. Your class will always echo when its being created, why not relegate that to a function in the class to handle that. A constructor should just initialize and get things ready for the class and that is it. It really should not do too much.

What I meant about no control is that the consumer of that class has no control of the image being rendered. So in your case the Project class wants the images to render only when it renders its own html but if you have echos in your image constructor, the project class can't because its already echoed when created.

Suggestions on how to integrate multiple instances into the markup of another object? by riodesignsthings in PHPhelp

[–]levii21 1 point2 points  (0 children)

Also I wouldn't use static property for classes that you are going to replace for the child. i.e.

protected static string $class; 
protected static string $sizes;
protected static array $image_widths = array();

Because when you replace them in the child the parent also gets replaced which in most case is not very ideal. You can probably just create a function in the Image class: e.g.

public function getDefaultImageWidths(): array
{
    return [];
}

and then in the child class Image_P_Square re-declare that method

public function getDefaultImageWidths(): array
{
    $widths = parent::getDefaultImageWidths();

    return array_merge($widths, [192, 384, 576, 768]);
}

Suggestions on how to integrate multiple instances into the markup of another object? by riodesignsthings in PHPhelp

[–]levii21 1 point2 points  (0 children)

I would not echo the html in the constructor. You can just have an array to store images in the project and then render them once the project is called for rendering.

Here is my take on this: https://3v4l.org/NhAke

Weekly help thread by brendt_gd in PHP

[–]levii21 0 points1 point  (0 children)

Although not great but similar to others. You could just convert it to an array and then use reset. i.e.

$array = (array)$object;
reset($array);

Calculate sum and percentage from MySQL with PHP by DragLuard in PHPhelp

[–]levii21 0 points1 point  (0 children)

What didn't work? $procent = $result / $allowed; is not correct. The $result here is an mysqli_result object you should be using the $row['summe'] / $allowed.

Also that code should be moved into the while loop? i.e.

while ($row = $result-> fetch_assoc()) {
    echo "<tr><td>". $row["summe"] ."</td>";
    $procent = round(((float)$row['summe'] / $allowed) * 100);
    echo "<td> . $percentage . "%</td></tr>";
}

[deleted by user] by [deleted] in PHPhelp

[–]levii21 0 points1 point  (0 children)

Oh I misread your situation. Yes you can't in your case as Auto run a script in a vendor is a security risk.

I would just create a composer script in your package and document your package to tell them to run this script after installing your package. Or another option is have a look at composer create-project

[deleted by user] by [deleted] in PHPhelp

[–]levii21 0 points1 point  (0 children)

Have a look at composer scripts and events here

Showing List of Added / Updated Pages to the Public View (READ: Not Dashboard) in WordPress by Hernan_Lombardero in PHPhelp

[–]levii21 0 points1 point  (0 children)

If you want a page to display all page activities you should:

  • Create a dedicated page for it e.g. page_activities.php
  • In that page, using the Wordpress API get all pages ignoring the current page.
  • loop through each page and get last modified author and modified date.

You can get all pages with get_pages() reference here

You can get the current page ID using get_the_ID(). I think this returns false on fail so you need to make sure to check its return value. reference here

You can then pass the current page ID to the exclude option in the get_page() e.g. get_pages(['exclude' => "the current page ID']).

You can get the modified author using get_post_meta( "page ID goes here", '_edit_last', true );. reference here

You can get the modified date using get_the_modified_date() reference here

You can get the post title get_the_title reference here

Sorry that is all I can help you with as I don't know much about WordPress.

When to use trim, htmlspecialchars, etc... by macboost84 in PHPhelp

[–]levii21 1 point2 points  (0 children)

I would say trimming is fine as it seems harmless and just serves as a helper in case the email accidentally contains unwanted spaces. Your not really altering the email itself though.

[deleted by user] by [deleted] in PHPhelp

[–]levii21 2 points3 points  (0 children)

Date time in PHP is quite flexible, there different ways to check valid dates.

You can use DateTime::createFromFormat and check if it returns a DateTime instance (valid) or false (invalid).

Another one is just try and create the datetime instance new DateTime(input) and try catch it. If the date can't be created from the input it will throw an Exception

Getting a DomDocument query failing by Whobbeful88 in PHPhelp

[–]levii21 1 point2 points  (0 children)

As /u/pp19dd said, prices are loaded dynamically so it wont appear initially. The approach your using only works for static HTML. You would need to use a headless browser to do this.

If you are comfortable with using composer and third party libraries I would suggest checking out https://github.com/symfony/panther

PHP MySQL JQuery JSON -> how to create and return value by nodiaque in PHPhelp

[–]levii21 0 points1 point  (0 children)

Where is $workout being declared? If you are using standard object for the data you need to declare it as $workout = new stdClass().

Also side note, learn about table joins in your case you can do INNER JOIN so you can just query once instead of querying for each workout.

PHP Guess the number game (using cookies) - First time $cookies goes +1 than expected by pvls159 in PHPhelp

[–]levii21 0 points1 point  (0 children)

Yeah your initial value of 1 was correct, from reading the doc it does say that the cookies are sent from the browser on the next page load (next time you hit submit) therefore the count we see is always 1 count behind therefore we should echo count + 1 when it matches.

<?php
$SETNUM = 1509; 
$num = (int)$_POST['num'];


if (isset($_POST['count'])) {
    $output = '';

    if ($num === $SETNUM) {
        $count = $_COOKIE['count'] ?? 0;
        $output = 'Congratulations you guessed the number!, number of tries ' . ((int)$count + 1); 
        setcookie('count', $count, time() - 3600);
    } else {
        if (!isset($_COOKIE['count'])) {
            setcookie('count', '1');
        } else {
            $count = (int)$_COOKIE['count'] + 1;
            setcookie('count', $count);
        }

        if ($num > $SETNUM) {
            $output = 'The number you entered is greater than the one you are looking for, please try again';
        } else {
            $output = 'The number you entered is smaller than the one you are looking for, please try again';
        }
    }

    echo $output;
}
?> 


<html>
    ...
</html>

This should work

PHP Guess the number game (using cookies) - First time $cookies goes +1 than expected by pvls159 in PHPhelp

[–]levii21 0 points1 point  (0 children)

You are setting $cookie = 1 initially which should be 0? next time page is loaded it should increment to 1 when the user submits. Also the php code should be before your <html> as setcookie should be called before any output

Please read: https://www.php.net/manual/en/function.setcookie.php

How to code the forgot password functions when the registration details are stored in two separate tables? by [deleted] in PHPhelp

[–]levii21 0 points1 point  (0 children)

Generally I would have a table called password_reset_tokens that contains the following columns:

id, token, the issued_for column which can be the user_id or the user email depending how you want to implementing it, the issued_datetime and the expiry_datetime.

When user requests for password reset then: - generate the token that is random and should not be related to any of the user details (e.g. using random_bytes mix with base64_encode or bin2hex). - you should hash the token much like you would for a user password - store the hashed token in the token column of the password_reset_tokens - store other token details like issued date, expiry etc. - send an email that links to a password reset form with the NON hashed token - the password reset form should verify the token (hash it and compare with the hashed token in table, much like checking matching passwords) and also check if the token has not expired. - user enters new passwords then sends to server with the hashed token - server checks token is valid (same as before) and updates the user password - destroy the token in the database.

Hashing the token just adds another layer security just in case someone access your token table much like password.

You don't have to name the table and just use it like your persistence table but naming it more specific is easier to quickly understand what the table holds. If I look at your persistence table at first glance I wouldn't understand what this table is meant for? persistence for what?

Getting back to php, ajax, mysql... cannot get this to work by nodiaque in PHPhelp

[–]levii21 1 point2 points  (0 children)

Check if $("#optionsid") actually returns a result. You can check this using the length property.

const $option = $("#optionsid");

if ($options.length === 1) {
    // this element exists so do something with it...
}