Multidimensional array to table column instead of rows

I’m currently learning PHP and am working with multidimensional arrays. I’m trying to generate a table from a multidimensional array with two levels. But I can only output the data per row. But I would prefer to output the data per column.

$mengearray = unserialize($mengerow);
$menge = implode(', ', $mengearray);
                        
$zutatenarray = unserialize($zutatenrow);
$zutaten = implode(', ', $zutatenarray);
                        
$zutatenmenge = array (
    $mengearray,
    $zutatenarray
);

foreach($zutatenmenge as $row) {
    echo('<tr>');
    echo('<td>');
    echo(implode('</td><td>', $row));
    echo('</td>');
    echo('</tr>');
}

What I get is

Menge 1 Menge 2
Zutat 1 Zutat 2

What I want is

Menge 1 Zutat 1
Menge 2 Zutat 2

htmlentities not working correctly with php [duplicate]

I am working in php,I am trying to save editor data into database
but data is not not saving as i expected,For example after submit form my post data is

Array
(
    [title] => Lorem Ipsum dummy text
    [description] => <p><strong>Lorem Ipsum</strong> dummy text</p>
)

And here is my query

$title= // any title; 
$description = $description_front=htmlentities($_POST['description']);

$sql = "INSERT INTO sl_blogs(title,description) VALUES ('$title','$description')"; 
$this->db->query($sql);

After print query in web page i am getting following query

(INSERT INTO sl_blogs(title,description) VALUES ('Lorem Ipsum dummy text','<p><strong>Lorem Ipsum</strong> dummy text</p>') )

which is looking fine But my data in database saving like

&lt;p&gt;&lt;strong&gt;Lorem Ipsum&lt;/strong&gt; dummy text&lt;/p&gt;

i want data should save like

<p><strong>Hello</strong> <em>worldddd</em></p>

Laraavel hasManyThrough relations in relations

I have a question about hasManyThrough method of Eloquent.

So i have pages db table and page_relations db table.
Into page_relations i have page_id and parent_id.
My first page have second page in child and second page have third page in child:

  • 1
    • 2
      • 3

Almost is good, i use hasManyThrough for output child pages but i want to add level system for that.
If i use this method:

    return $this->hasManyThrough(
      Pages::class,
      PageRelation::class,
      'parent_id', // Foreign key on the PageRelation table...
      'id', // Foreign key on the Pages table...
      'id', // Local key on the Pages table...
      'page_id' // Local key on the PageRelation table...
    );

.. it output pages with his relations BUT i haven’t relations in relations (screen)
enter image description here

What i have to do for made level system? I have to do something in model or i have to do something in controller for filter it? Maybe you’ll have some idea to figure out it? I’ll very appreciate you if you get me some help or share several minutes of your attention!

PHP mail successful with empty to parameter

I am learning PHP and from what I understand the mail function has a to parameter that needs to comply with a certain string format – php doc. I have read that if I parse an empty string then the mail function will return false (not 1). However, when I try this the mail function never fails. Is there something I have missed?

Code:

<?php

if (mail('', 'mySubject', 'myMessage')) {
    echo "Success!";

} else {
    echo 'Failure!';
}

?>

The output is “Success!”

Only by removing the argument entirely gets the else statement to execute. Does the to parameter need to be of a certain string format like the documentation states and if not, then how can I get this function to fail? Thanks

How to test the first characters of a file in php?

I have a PHP code that allows me to read a csv file, insert the data into the database and move this file to another folder once the processing is finished.

This code works by default with UTF8 BOM files, I added the line fseek($handle, 3); to pass the first 3 characters.

I would like to know how I can execute the same code for UTF8 files by integrating the lines directly or in UTF8 BOM by starting after the first 3 characters?

<?php

include("connexion.php");

$dir   = '//server/d$/ftp/GET/';
$allFiles = scandir($dir);
$dest = '//server/d$/ftp/GET/COPIES/';

foreach($allFiles as $file) {

    if (!in_array($file,array(".","..")))
    { 
        $file = $dir.$file;
        $filename = basename( $file );
        
        if ( strpos( $filename, 'BI1_' ) === 0 ) 
        {
            
            if (($handle = fopen($file, "r")) !== false) 
            {
                 
                //To remove BOM in the first cell
                 fseek($handle, 3);   
                  
                     $bi1_values =  array();
                     while (($data = fgetcsv($handle, 9000000, ";")) !== false) 
                        {                                         
                                $bi1_values[] = "('$data[0]', '".str_replace("'", "''",$data[1])."','$date1','$date2','$data[2]','$data[4]','".str_replace("'", "''",$data[5])."','".str_replace("'", "''",$data[6])."')";                 
                                if (count($bi1_values) == 1000) 
                                { 
                                    $query = "insert into dbo.Sales (storenumber, storename, date, time, TransRef, stylecode, color, size) 
                                    values " . implode(',', $bi1_values);
                                    $stmt = $conn->query( $query );
                                    
                                    if (!$stmt) 
                                    { 
                                            $file1 = "D:/xampp/htdocs/errors/erreur_BI1.txt";                       
                                            file_put_contents($file1, $query . PHP_EOL, FILE_APPEND | LOCK_EX);
                                    }   
                                    $bi1_values = array();
                                } 
                        }
                        
                    fclose($handle);
                      
                    //Moving the file to another folder             
                    if(!rename($file, $dest . $filename)) 
                    { 
                        echo "error";
                    }                
                }
            }
    }
}

?>

Populate array from file PHP [closed]

I have create a simple script that ping an host in my lan and return the status of the device into a html table.

enter image description here

enter image description here

I wrote the “host ping” directly into the array in the code,

enter image description here

i want to take that information from a txt file and put in the iplist array

The info in txt file would like:

“192.168.0.15,PC1”

“10.65.0.101,Switch1”

Thanks for responding

PHP Search Broken Results [duplicate]

I’m trying to create a search system for my website that brings up the search itself and or any matching to what the user is searching.
This is my code

<?php 
  $db = mysqli_connect("localhost", "root", "", "db");
  if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  $search = $_GET['search'];
  $sql = "SELECT * FROM posts WHERE Name LIKE '%$search%'";
  $result = mysqli_query($db, $sql);
  $row = mysqli_fetch_array($result);
  $count = mysqli_num_rows($result);
  if ($count == 0) {
    echo "No results found";
  } else {
    while ($row = mysqli_fetch_array($result)) {
      echo "<div class='post'>";
      echo "<img src='images/".$row['Image']."'>";
      echo "<h1>" . $row['Name'] . "</h1>";
      echo "<a href='" . $row['Link'] . "' target='_blank' rel='noopener noreferrer'>Download</a>";
      echo "<button id='report' type='submit'>Report broken link</a>";
      echo "</div>";
    }
  }
?>

It brings up the searches fine but it displays a error “( ! ) Notice: Undefined index: search in C:wamp64wwwonlyfanssearch.php on line 32”. Removing the $search breaks the entire thing so im unsure why there is a error if it works but removing it breaks it all. The search HTML itself is just a form with a GET method and action leading to search.php

How to test web API in PHP?

Do we have any methods to test our Web API like Phpunit?
In a interview, asked me someone how do you test your API? and I answered I test my Web APIs manually by Postman.
But I forgot to ask him what is the right way?

Get current product id inside a function

I have a custom plugin to generate pdf of my products. I am calling this function inside the plugin to get all the gallery images of a product.

    function get_gallery_images(){
      $product_id = 34560;
      $product_obj = new WC_product($product_id);
      $attachment_ids = $product_obj->get_gallery_image_ids();
    }

This function works perfectly when the id of the product is fixed, but whenever I try to get the ID dynamically is stops working. My dynamic function is:

function get_images(){
  global $product;
  $attachment_ids = $product->get_gallery_image_ids();
}

It should work because I have seen people using this function but it doesn’t work for me and I am unable to identify the issue.

Dynamic Email Configuration from database in Laravel

Good evening, I just fetch my mail configuration from database to provider,
the code was like this,

    if(Schema::hasTable('email_settings')){
            
                $configuration = email_setting::first();

                if(!is_null($configuration)) {
                   $mail =  config::set('mail', [
            'driver' => $configuration->mailer,
            'host' => $configuration->host,
            'port' => $configuration->port,
            'encryption' =>  $configuration->encryption,
            'username' =>$configuration->username,
            'password' => $configuration->password,
                        'from' => [
        'address' => $configuration->sender,
        'name' => $configuration->name,
    ],
                       'pretent' => false,
                       'sendmail' => '/usr/sbin/sendmail -t -i',
                    ]);
                    
                }
        }

This work perfectly when using mailtrap.io but on live server, i always get an error which says “)” not expected. And in my laravel log i always get it as

[2022-06-18 11:46:54] local.ERROR: syntax error, unexpected token ")" {"exception":"[object] (ParseError(code: 0): syntax error, unexpected token ")" at /home/meetclan/delyninvoice/vendor/symfony/css-selector/XPath/Extension/NodeExtension.php:68)

```.
Please can anyone help me with the solution to this error.

“Target class [appHttpControllersWebScraper] does not exist.”, but it does exist

Controller(“WebScraper”):

        <?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class WebScraper extends Controller
{
    public function games(){
        include('simple_html_dom.php');
        
        $day = 1; //temporär

        $html = file_get_html('https://sport.sky.de/bundesliga-spielplan-ergebnisse-'.$day);

        echo $html-> find('title', 0)->plaintext;

        $list = $html -> find('div[class="sdc-site-fixres-wrap"]', 0);

        $list_array = $list -> find('div');

        for($i = 0; $i < sizeof($list_array); $i++){
            echo $list_array[$i]->plaintext;
            echo "<br>";
        }

        return view('home.blade.php');
    }
}

Routes:

<?php

use IlluminateSupportFacadesRoute;
use appHttpControllersWebScraper;

Route::get(‘/’, [WebScraper::class, ‘games’]);

How can I return multiple queries with Laravel?

I am making a random website(own project for uni) that stores info about recent sports games and teams(team names and player names are made up) and I’d like to find out how can I(or what is the best way) to return player names that belong to their team.
Code example from .blade

<details>
     <summary class="displayTeams"> Pueblo Thrashers </summary>
    <div class="allplayers">
    @foreach($PTh as $PTplayer)
        <p class="displayTeamsPlayer">{{$PTplayer->Name}} {{$PTplayer->LastName}} </p>
    @endforeach
    </div>
 </details>

Code example from my controller:

function showPlayers(){
    $PT = DB::table('players')->where('Team_ID', '1')->get();
    $RK = DB::table('players')->where('Team_ID', '2')->get();
return view('WHL', ['PTh' => $PT], ['RKi' => $RK]);

I have 6 more teams that I need to get players from, what’s the best possible way to do that?

How i can install snmp-module in php on Dokerfile

My problem: When i run command

docker build –no-cache -t php –progress=plain .

My container is building, but I get Error in my PHP-project:

Error Call to undefined function snmp2_real_walk()

Command install in Dockerfile is’t work… I need help!!

My Dockerfile:

FROM php:7.4-apache

# Use the default production configuration
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"

RUN if command -v a2enmod >/dev/null 2>&1; then 
a2enmod rewrite headers 
;fi

RUN apt-get update

# Install tools required for build stage
RUN apt-get install -fyqq 
    bash curl wget rsync ca-certificates openssl ssh git tzdata openntpd 
    libxrender1 fontconfig libc6 
    mariadb-client gnupg binutils-gold autoconf 
    g++ gcc gnupg libgcc1 linux-headers-amd64 make python

#RUN apt install -y libsnmp-dev      

# Install composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/bin --filename=composer 
 && chmod 755 /usr/bin/composer

# Install additional PHP libraries
RUN docker-php-ext-install bcmath pdo_mysql    
    
RUN  
apt-get update && 
apt-get install libldap2-dev -y && 
rm -rf /var/lib/apt/lists/* && 
docker-php-ext-configure ldap --with-libdir=lib/x86_64-linux-gnu/ && 
docker-php-ext-install ldap

# Install libraries for compiling GD, then build it
RUN apt-get update && apt-get install -y 
    libfreetype6 
    libfreetype6-dev 
    libjpeg62-turbo 
    libjpeg62-turbo-dev 
    libsqlite3-dev 
    libssl-dev 
    libpng-dev 
    libpng16-16 
    libcurl3-dev 
    libxml2-dev 
    libonig-dev 
    libsnmp-dev 
    snmp 
&& docker-php-ext-install mysqli  xmlrpc 
&& docker-php-ext-configure gd --with-freetype=/usr/include/ --with-jpeg=/usr/include/ 
&& docker-php-ext-install gd 
&& apt-get remove -fyqq libfreetype6-dev libpng-dev libjpeg62-turbo-dev
 
    # -------------------- Installing PHP Extension: snmp --------------------
RUN docker-php-ext-configure snmp --with-snmp 
    # Installation
    && docker-php-ext-install -j$(getconf _NPROCESSORS_ONLN) snmp 
    && true
RUN sed -i 's/;extension=snmp/extension=snmp/' php.ini-production

# Add ZIP archives support
RUN apt-get install -fyqq zip libzip-dev 
 && docker-php-ext-install zip 
 && apt-get remove -fyqq libzip-dev

# Install xdebug
RUN pecl install xdebug 
 && docker-php-ext-enable xdebug

# Enable XDebug
ADD xdebug.ini /usr/local/etc/php/conf.d/xdebug.ini

WORKDIR /app

I’ve tried a lot of options. Editing the

php.ini-production

file did not lead to the expected result. At the same time, the php.ini file also does not exist, but the command is present…