How to loop through an Array in an Object PhP

when I call this Cpanel API $result = $cPanel->execute('uapi', 'DomainInfo', 'list_domains'); to Cpanel Uapi I get the Object value stated below. To display the object, I use var_dump($result);. It works as expected. Then access main_domain values

USING

<?php echo $result->data->main_domain; ?>

I get the correct value for main_domain stated in var_dump below which is main-example.ng

The thing is, I am having trouble looping through addon_domains, subdomains and parked_domains, I tried:

<?php
foreach ($result as $key){  
?>  
<li><?php echo $key->addon_domains; ?></li>
<?php
}
?> 

AND

<?php
foreach ($result as $key){  
?>  
<li><?php echo $key->sub_domains; ?></li>
<?php
}
?> 

But it doesn’t work, I get error Array to String conversion please what am I doing wrong.

object(stdClass)#4 (5) { 
["addon_domains"]=> array(9) { 
[0]=> string(12) "example.com" 
[1]=> string(11) "example1.com" 
[2]=> string(11) "example2.com" 
[3]=> string(11) "example3.com" 
[4]=> string(15) "example4.website" 
[5]=> string(15) "example5.xyz" 
[6]=> string(12) "example6.com" 
[7]=> string(13) "example7.com" 
[8]=> string(11) "example8.com" 
} 
["cp_php_magic_include_path.conf"]=> string(1) "1" 
["main_domain"]=> string(16) "main-example.ng" 
["sub_domains"]=> array(10) { 
[0]=> string(19) "uc.example.ng" 
[1]=> string(20) "pos.example1.ng" 
[2]=> string(26) "new-example-team.example1.ng" 
[3]=> string(21) "example.example1.ng" 
[4]=> string(18) "seller.example.com" 
[5]=> string(41) "example-website-dashboard.example.website" 
[6]=> string(30) "forbidden-link.example.website" 
[7]=> string(17) "about.example.com" 
[8]=> string(18) "seller.example.com" 
[9]=> string(19) "shipper.example.com" 
} 
["parked_domains"]=> array(1) { 
[0]=> string(19) "um.example.ng" 
} 
}

Symfony – Unable to find the object manager associated with an entity of class

I am trying to set whole registration process in my Symfony 6 project following the documentation.

I come to the part where I have a form that I am populating. When submited, I get an error:

Unable to find the object manager associated with an entity of class “AppEntityUser”.

I strictly followed the example that is given in the documentation.

And in my user entity:

/**
 * @ORMTable(name="`user`")
 * @ORMEntity(repositoryClass="AppRepositoryUserRepository")
 * @UniqueEntity(fields={"email"}, message="There is already an account with this email")
 */
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
  ....

And in the doctrine.yaml file:

orm:
    auto_generate_proxy_classes: true
    naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
    auto_mapping: true
    mappings:
        App:
            is_bundle: false
            dir: '%kernel.project_dir%/src/Entity'
            prefix: 'AppEntity'
            alias: App

UserRepository:

/**


* @extends ServiceEntityRepository<User>
 *
 * @method User|null find($id, $lockMode = null, $lockVersion = null)
 * @method User|null findOneBy(array $criteria, array $orderBy = null)
 * @method User[]    findAll()
 * @method User[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class UserRepository extends ServiceEntityRepository implements PasswordUpgraderInterface
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, User::class);
    }
    ...

What am I doing wrong?

PHP 8.1 $_FILES missing type property

I am upgrading my website from PHP 7.4 to 8.1 which is causing an unusual issue with $_FILES. This cannot be regarding the file size as I’m trying to upload .txt files containing a single word.

Example of my code:

<form action="client.php" method="POST" enctype="multipart/form-data" onSubmit="javascript: return validateFile(this);">
    <div class="card-header">
        Upload Section
    </div>
    <div class="card-body">
        <div class="position-relative form-group">
            <label >Select file from local disk</label>
            <input  type="file" name="test" size="90" maxlength="500" class="form-control-file">
        </div>
        <input class="mt-1 btn btn-primary" name='Submit' type='submit' value='Upload File'>
    </div>
</form>

When the from is posted the data within $_FILES is like so

test={ name="test.txt, full_path=test.txt, type="", tmp_name="", error={int} 6, size={int} 0}

Infinite category tree that opens sideways with php

i am trying to make a menu that can be opened side by side like here.
https://prnt.sc/tztg24JdoLyB

For this, I followed a way

if ( ! function_exists('buildHomePageTreeMenu')){
    function buildHomePageTreeMenu($object, $currentParent, $url, $active ='', $currLevel = 0, $prevLevel = -1) {
        foreach ($object as $category) {
            if ($currentParent == $category->parent_id) {

                if ($currLevel > $prevLevel) {
                    if($category->parent_id != null){
                        echo "<ul class='navbar-nav u-header__navbar-nav' id='category-". $category->parent_id ."'>"; 
                    }else{
                        echo "<ul class='navbar-nav u-header__navbar-nav'>";
                    }
                }
                    
                if ($currLevel == $prevLevel) echo "</li>";

                if($category->child_category->count() > 0){
                    echo '<li class="nav-item hs-has-mega-menu u-header__nav-item" data-event="hover" data-animation-in="slideInUp" data-animation-out="fadeOut" data-position="left">
                
                    <a id="basicMegaMenu" class="nav-link u-header__nav-link u-header__nav-link-toggle" href="javascript:;" aria-haspopup="true" aria-expanded="false">'. $category->translation->name .'</a>';
                    
                                    
                }else{
                    echo '<li class="nav-item u-header__nav-item" data-event="hover" data-position="left">
                    <a class="nav-link u-header__nav-link font-weight-bold" href="'.filter_url($url ."/". $category->slug).'">'. $category->translation->name .'</a>';
                }

                if ($currLevel > $prevLevel) { 
                   $prevLevel = $currLevel; 
                }

                $currLevel++; 
                buildTreeCollapse ($object, $category->id, $url, $active,  $currLevel, $prevLevel);
                $currLevel--;   
            }
         }
        if ($currLevel == $prevLevel) echo "</li> </ul>";
    }
}

There are main categories and subcategories, but I can’t see the other category titles and the titles under them.

menu html code

<ul class="navbar-nav u-header__navbar-nav">
        <li class="nav-item hs-has-mega-menu u-header__nav-item"
            data-event="hover"
            data-animation-in="slideInUp"
            data-animation-out="fadeOut"
            data-position="left">
            <a id="basicMegaMenu" class="nav-link u-header__nav-link u-header__nav-link-toggle" href="javascript:;" aria-haspopup="true" aria-expanded="false">Computers & Accessories</a>

            <div class="hs-mega-menu vmm-tfw u-header__sub-menu" aria-labelledby="basicMegaMenu">
                <div class="vmm-bg">
                    <img class="img-fluid" src="../../assets/img/500X400/img1.png" alt="Image Description">
                </div>
                
                <div class="row u-header__mega-menu-wrapper">
                    <div class="col mb-3 mb-sm-0">
                        <span class="u-header__sub-menu-title">Computers & Accessories</span>
                        <ul class="u-header__sub-menu-nav-group mb-3">
                            <li><a class="nav-link u-header__sub-menu-nav-link" href="#">All Computers & Accessories</a></li>
                            <li><a class="nav-link u-header__sub-menu-nav-link" href="#">Laptops, Desktops & Monitors</a></li>
                            <li><a class="nav-link u-header__sub-menu-nav-link" href="#">Printers & Ink</a></li>
                            <li><a class="nav-link u-header__sub-menu-nav-link" href="#">Networking & Internet Devices</a></li>
                            <li><a class="nav-link u-header__sub-menu-nav-link" href="#">Computer Accessories</a></li>
                            <li><a class="nav-link u-header__sub-menu-nav-link" href="#">Software</a></li>
                            <li>
                                <a class="nav-link u-header__sub-menu-nav-link u-nav-divider border-top pt-2 flex-column align-items-start" href="#">
                                    <div class="">All Electronics</div>
                                    <div class="u-nav-subtext font-size-11 text-gray-30">Discover more products</div>
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </li>
    </ul>

I would appreciate it if you could help me to get an image like the example I gave.

Why do I keep getting 405 error when submitting a form to mysql database

I’m trying to submit a form into mysql database but every time I click submit on the webpage I’m getting the HHTP ERROR 405 Method not allowed. I’ve searched but I still haven’t found a solution, can anyone help? Here is my code below.

Here is the requests.html page

form action="conn.php" method="POST">

                <label for="category" id="fname">What type of request are you making?</label>
                <select id="category" name="category" required>
                  <option value="software">Software Update</option>
                  <option value="hardware">Hardware </option>
                  <option value="application">Application</option>
                  <option value="security">Security</option>
                 
                </select>

              <label for="fname" id="fname" >Full Name</label>
              <input type="text" id="fname" name="name" placeholder="Your name.." required>
          
              <label for="fname" id="fname">Summary</label>
              <input type="text" id="fname" name="summary" placeholder="Brief summary..." required>

              <label for="lname">Description</label>
              <input type="text" id="lname" name="description" placeholder="">

              <label for="fname" id="fname">Impact on server or application</label>
              <select id="category" name="server_category" required>
                <option value="sql">MySQL</option>
                <option value="web">EA Webserver </option>
                <option value="server">Oracle Server</option>
              </select>

              <label for="fname" id="fname">Impact on Department</label>
              <select id="category" name="department_category" required>
                <option value="assurance">ICT ASSURANCE SERVICE</option>
                <option value="support">ICT Support Service </option>
                <option value="network">ICT Network and infastructure</option>
              </select>

              <label for="fname">Risk</label>
              <select id="category" name="risk_category">
                <option value="high">High</option>
                <option value="moderate">Moderate</option>
                <option value="low">Low</option>
              </select>

              <!--<label for="fname">Change Start date</label>
              <input type="date" id="date" name="start_date">
              
              <label for="fname">Change Completion date</label>
              <input type="date" id="date" name="end_date">
              -->
              
          
             
            
              <input type="submit" value="Submit">
            </form>

And here is the conn.php code

<?php

$name = $_POST['name'];
$summary = $_POST['summary'];
$description = $_POST['description'];
$server = $_POST['server_category'];
$department = $_POST['department_category'];
$risk = $_POST['risk_category'];
$start = $_POST['start_date'];
$end = $_POST['end_date'];

if(!empty($name) || !empty($summary) || !empty($description) || !empty($server) || !empty($department) || !empty($risk)){


$passw = "dog1234";
   
$username = "root";

$db = "test";

$host = "localhost";

$conn = new mysqli($host, $username, $passw, $db);

if(mysqli_connect_error()){
    die('Connection error ('. mysqli_connect_errno().')'. mysqli_connect_error());
} else{
    $INSERT = "INSERT INTO request_change (employee_name, summary, req_description, req_server, department, risk) 
    VALUES (?, ?, ?, ?, ?, ?)";

    $stmt = $conn->prepare($INSERT);
    $stmt->bind_param("ssssss", $name, $summary, $description, $server, $department, $risk);
    $stmt->execute();
    echo "new record inserted";
}

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


} else{
    echo "All fields are required";
    die();
}
?>

Please can anyone let me know if my code is wrong or if there is something I’m missing out on here.

PHP: SOAP call with duplicated keys

I have the task to perform a SOAP call with multiple elements having the same name.
The SOAP envelope structure has to be like this:

<soap-env:envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://arubasignservice.arubapec.it/">
    <soap-env:body>
        <ns1:pdfsignaturev2>
            <signrequestv2>
                <binaryinput>ZmlsZUJJTg==</binaryinput>
                <certid>AS0</certid>
                <identity>
                    <otppwd>123456</otppwd>
                    <typeotpauth>xxxx</typeotpauth>
                    <user>xxxx</user>
                    <userpwd>xxxx</userpwd>
                </identity>
                <requiredmark>false</requiredmark>
                <transport>BYNARYNET</transport>
            </signrequestv2>
            <apparence>
                <imagebin>c2lnbklNRw==</imagebin>
                <imageonly>true</imageonly>
                <leftx>200</leftx>
                <lefty>200</lefty>
                <page>2</page>
                <rightx>200</rightx>
                <righty>200</righty>
                <bscalefont>true</bscalefont>
                <bshowdatetime>false</bshowdatetime>
                <resizemode>1</resizemode>
                <preservepdfa>true</preservepdfa>
            </apparence>
            <pdfprofile>PADESBES</pdfprofile>
        </ns1:pdfsignaturev2>
    </soap-env:body>
</soap-env:envelope>

The element which I’m trying to send as duplicate is <apparence>, however even trying different methods as suggested in multiple answers (here and here) I’m having always unsuccessful outcomes.

Hopeful someone can help me.
Thanks.

Best way to replace/remove a specific character when it appears between 2 character sequences

I have a php function which selects the text from a string between 2 different character sequences.

function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

$fullstring = ',""Word1, Word2""';
$parsed = get_string_between($fullstring, ',""', '""');

echo $parsed; //Result = Word1, Word2

However, I would like to extend this further to select all matches when there are multiple occurrences within the string (this is likely, since the string will be generated by a csv file with hundreds of lines and hundreds of matches.) For example:

$fullstring = ',""Word1, Word2"" and another thing ,""Word3, Word4""';

And within each substring I will need to remove certain characters. In this example, I need to remove commas.

Can anybody suggest the most straightforward way of achieving this? Thanks.

PHP exec | mysql command returns sh: -c: line 0: syntax error near unexpected token `newline’

I want to make multiple insertions into DB, but mysql command returns me:
sh: -c: line 0: syntax error near unexpected token `newline’.

Does anybody know, what this error means?

Here is my command:

mysql -h 127.0.0.1 -D db_name -u username --password=pass --debug-info true <shared/local_sql/3.sql>

Example of SQL file:

DELETE FROM table_name WHERE num = '999999';
START TRANSACTION;
INSERT INTO table_name SET key1 = 'val1', key1 = 'val1', key1 = 'val1', key1 = 'val1', key1 = 'val1', key1 = 'val1', key1 = 'val1', key1 = '', key1 = '', key1 = 'val1', num = '999999';
INSERT INTO table_name SET key1 = 'val2', key1 = 'val2', key1 = 'val2', key1 = 'val2', key1 = 'val2', key1 = 'val2', key1 = 'val2', key1 = '', key1 = '', key1 = 'val2', num = '999999';
COMMIT;
UPDATE table_name SET num = '999998' WHERE num = '2';
UPDATE table_name SET num = '2' WHERE num = '999999';
DELETE FROM table_name WHERE num = '999998' OR num = '999999';

Uncaught TypeError: mysqli_connect(): Argument #5 ($port) must be of type ?int, [closed]

Error:

Fatal error: Uncaught TypeError: mysqli_connect(): Argument #5 ($port)
must be of type ?int, string given in
C:xampphtdocsproj-phpconnections.php:10 Stack trace: #0
C:xampphtdocsproj-phpconnections.php(10):
mysqli_connect(‘localhost’, ‘root’, ’email;’, ”,
‘login_register_…’) #1 C:xampphtdocsproj-phpregister.php(6):
include(‘C:xampphtdocs…’) #2 {main} thrown in
C:xampphtdocsproj-phpconnections.php on line 10

enter image description here

php code:
enter image description here

automatically change data returns from the model in CodeIgniter 4

I want to change automatically the data returns from the model in CodeIgniter 4.
That’s what comes to my mind, but it’s not works:

class UserModel extends Model {
    protected $afterFind = ['getImage'];
        
    protected function getImage(array $data) {
            if ($data['user_image'] == 0) {
                    $data['user_image'] = "New Value";
            }
            return $data;
        
    }
}

Anyone have an idea how to do that?
Thanks.

Change a php value with button click

I have a WordPress query and want to filter it with a value for the “categroy_name”:

$value="2021";
<a href="<?php echo esc_url( add_query_arg('category_name',$value) ); ?>">2021</a>
$args = array(
    'category_name' => $value
);

So I have a button which sends the value, but how can I add more buttons with other values like “2020” and “2019”?

Return value must be instance of mixed int returned

In this code

<?php declare(strict_types=1);

namespace Persist;


trait IteratorTrait {
  /* #region Iterator */
  /** @var bool $valid true if a valid object */
  private bool $valid = false;
  
    public function current ( ): object { return $this; }
    public function key ( ): mixed  { return $this-> {$this->getPrimaryKey()} ; }
    public function valid ( ): bool { return $this-> valid; }
    public function next ( ): void { $this-> findNext(); }
    public function rewind ( ): void { $this-> findFirst(); }
  /* #endregion */
};

I get an error (on php 7.5) in an class that uses the trait: AH01071: Got error 'PHP message: PHP Fatal error: Uncaught TypeError: Return value of NameSpace\test::key() must be an instance of mixed, int returned in...

If remove the :mixed on key I get an error on PHP 8.1: PHP Deprecated: Return type of NameSpacetest::key() should either be compatible with Iterator::key(): mixed, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in ...

What I read here confuses me.

If I add this to the trait I get Fatal error: Attribute "ReturnTypeWillChange" cannot target property (allowed targets: method) in IteratorTrait.php on line 10

EDIT: This error occured because there was a property defined before the key() method.

Where should I change what to get this working on both 7.x and 8.x?

array_push fails on 10th iteration with identical code?

I am stymied by this and no SO posts mention this so I’m asking for some thoughts here. In essence, I have a evaluation survey with 13 questions and the data are stored on a single row using 13 columns (q1-q13). I extract the row and then iterate through each column looking for responses matching 3 or 2 or 1. When found, I write a row into an array using array_push. This works perfectly for columns 1-9 but it fails on the 10th. I copied/paste each line of code and made simple edits so, technically, each line of code is identical so I see no reason why it should fail. What am I missing here?

function get_POTENTIAL_List($sc_id) {
    global $dbc;

    $pot_list = [];

    $sql = "SELECT q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13 FROM worksheetA WHERE emp_id = ?";
    $stmt = prepared_query($dbc, $sql, [$sc_id]);
    $row = $stmt->get_result()->fetch_assoc();

Then I use this code to build the aray:

if($row['q1'] == "3" || $row['q1'] == "2" || $row['q1'] == "1") {
        $pot_info = array('id' => "1", 'category_title' => "INTRAPERSONAL/INTERPERSONAL", 'scale' => $row['q1'], 'scale_def' => "Scale Definition here.");
        array_push($pot_list, $pot_info);
    }
    if($row['q2'] == "3" || $row['q2'] == "2" || $row['q2'] == "1") {
        $pot_info = array('id' => "2", 'category_title' => "INTRAPERSONAL/INTERPERSONAL", 'scale' => $row['q2'], 'scale_def' => "Scale Definition here.");
        array_push($pot_list, $pot_info);
    }

and so on through (successfully) to 9:

if($row['q9'] == "3" || $row['q9'] == "2" || $row['q9'] == "1") {
        $pot_info = array('id' => "9", 'category_title' => "INTRAPERSONAL/INTERPERSONAL", 'scale' => $row['q9'], 'scale_def' => "Scale Definition here.");
        array_push($pot_list, $pot_info);
    }

And then, on the 10th column it stops working with a

“Uncaught SyntaxError: Unexpected end of JSON input”

error.

if($row['q10'] == "3" || $row['q10'] == "2" || $row['q10'] == "1") {
        $pot_info = array('id' => "10", 'category_title' => "INTRAPERSONAL/INTERPERSONAL", 'scale' => $row['q10'], 'scale_def' => "Scale Definition here.");
        array_push($pot_list, $pot_info);
    }

JS PHP automatic return to previous page when if is false

i am sending some data to a mysql db.
when the primary key is already in use, it should give an alert and then go back to the previous page with all input already filled as before.

It is working fine, but when the primary key is already in use, i got both alerts.
First the else alert and then always the other alert too.

what am i missing?

thx

            if($wert_vorher != $wert_nachher )
            {
                echo '<script>alert("Daten wurden eingefügt")</script>';
                exit(1);        
            }           
            else 
            {
                echo '<script>alert("Daten schon vorhanden")</script>';
                echo '<script language="javascript">
                            javascript:history.back()
                            </script>'; 
                exit(1);            
            }

Twitter api returning html response as error

    /*My code *
    $connection         = new TwitterOAuth(SOCIOMATIC_HFW_API_KEY, SOCIOMATIC_HFW_API_SECRET);
    $connection->setTimeouts(1000, 1000);
    
    $request_token      = $connection->oauth("oauth/request_token", array("oauth_callback" => 'env('TWITTER_CALLBACK_URL')'));

/* Response in html */
AbrahamTwitterOAuthTwitterOAuthException

Twitter / ?