How to Compare two multidimensional associative arrays with differen items count

I have two multidimensional associative arrays with differen items count.
Important is that I don’t know which aray will have more elements (A or B)

First array (A):

    [0] => Array
        (
            [catID] => 65
            [discount] => 10
            [productID] => Array
                (
                    [0] => 10887
                    [1] => 8508
                    [2] => 8350
                )

            [startDate] => 05/12/2022 12:00 am
            [endDate] => 10/12/2022 12:00 am
        )
   [1] => Array
        (
            [catID] => 66
            [discount] => 10
            [productID] => Array
                (
                    [0] => 13184
                    [1] => 10707
                    [2] => 8350
                )

            [startDate] => 10/12/2022 12:00 am
            [endDate] => 15/12/2022 12:00 am
        )

Second array (B):

[0] => Array
    (
        [catID] => 72
        [discount] => 15
        [productID] => Array
            (
                [0] => 16239
                [1] => 16236
                [2] => 10887
                [3] => 13184
                [4] => 8524
                [5] => 13314
            )
        [startDate] => 12/12/2022 12:00 am
        [endDate] => 15/12/2022 12:00 am
    )

After compare these arrays (A, B) I’d like to retrive something like that:

Array A(remove elements if exists in array B):

    [0] => Array
        (
            [catID] => 65
            [discount] => 10
            [productID] => Array
                (
                    [1] => 8508
                    [2] => 8350
                )
            [startDate] => 05/12/2022 12:00 am
            [endDate] => 10/12/2022 12:00 am
        )
   [1] => Array
        (
            [catID] => 66
            [discount] => 10
            [productID] => Array
                (
                    [0] => 10707
                )
            [startDate] => 10/12/2022 12:00 am
            [endDate] => 15/12/2022 12:00 am
        )

Array B(no changes):

[0] => Array
    (
        [catID] => 72
        [discount] => 15
        [productID] => Array
            (
                [0] => 16239
                [1] => 16236
                [2] => 10887
                [3] => 13184
                [4] => 8524
                [5] => 13314
            )
        [startDate] => 12/12/2022 12:00 am
        [endDate] => 15/12/2022 12:00 am
    )

Create a table of all invoices from Stripe API in PHP

I am trying to create a table in PHP of all invoices in the table with the Stripe API.

This is my code so far:

$result = $stripe->invoices->all(['limit' => 100]);

echo $result;

I don’t know how I can just display the invoice id, customer name and amount in a table. This is my first time working with Stripe and API’s.

Why Curl POST request is not working while sending single parameter?

I am trying to send a cURL request but it is not working at all, I am using PHP 5.4 version because of code legacy. cURL extension is installed and working. I have tried by var_dump(extension_loaded('curl')); and this returns true. also, I have used headers

I am trying to send a single parameter clientid which has value in variable $client_id

header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');

In update.php

print_r($_POST);
var_dump ($_POST);

This below code is not working –

        $ch =curl_init('https://beta.mymains.in/service/update.php');
       
        $data = array('clientid' => $client_id); 
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HEADER, 0);
         curl_exec($ch);

         curl_close($ch);

And I tried this code, and this works I mean this is hitting the url?

         $ch = curl_init("http://www.google.com/");
         $fp = fopen("google_homepage.txt", "w");
         curl_setopt($ch, CURLOPT_FILE, $fp);
         curl_setopt($ch, CURLOPT_HEADER, 0);
         curl_exec($ch);
         curl_close($ch);
         fclose($fp);
         curl_exec($ch);
         curl_close($ch); 

What is the best way to generate pages using PHP based on matching a value in the URL with values in a database?

I have a database that contains every UK town and city, as well as local phone dialling codes.

Here is an example of what my database looks like:

id towncity region country firstnumber secondnumber thirdnumber content
1 Aberdeen Aberdeenshire Scotland 01234 567890 11234 567890 21234 567890 some content
2 Leeds West Yorkshire England 31234 567890 41234 567890 51234 567890 some content
3 Cardiff South Glamorgan Wales 61234 567890 71234 567890 81234 567890 some content
4 Southampton Hampshire England 91234 567890 01234 567891 01234 567892 some content
5 Gloucester Gloucestershire England 01234 567893 01234 567894 01234 567895 some content

I have connected this database to my website through PHP and basically, I want it so that if someone visits my website through a Google ad, a destination page could be https://my.website.com/aberdeen but technically that page does not physically exist (I don’t want to have to manually create a page for every single database record, that would be both time-consuming, and not ideal to manage should I need to change anything site-wide in the future, nor would it be ideal if I need to add more records in bulk).

I want the value after ‘.com/’ (for exmaple, ‘aberdeen’ in the link above) to be searched for in my database, if it’s found display the values in the same row as ‘aberdeen’, if there’s no match redirect to my 404 page.

Some notes:

  • I’m not worried about duplicate content as the pages are only going to be used for adverts on Google – they won’t be used organically.
  • I will only ever want pages generated under the ‘towncity’ column in the database. The rest of the data will be used for content on the corresponding page.
  • I will however, want there to be subpages for each record. For example, if someone were to visit https://my.website.com/aberdeen/subpage through an ad, I want that subpage to display the data in the same row as ‘aberdeen’ in the database.

How can I achieve this easily? Or, is what I currently have (see attached code below) the best solution?

I’m afraid my PHP knowledge isn’t the greatest, so I’m not entirely sure how to describe my current solution, so I will attach the code instead:

  • config/config.php establishes a connection to my database.
  • libraries/Database.php:
<?php

class Database
{
    private $DB_Name = DB_NAME;
    private $DB_Host = DB_HOST;
    private $DB_User = DB_USER;
    private $DB_Pass = DB_PASS;
    private $link;
    private $error;
    public function __construct()
    {
        $this->connection();
    }
    private function connection()
    {
        $this->link = new mysqli($this->DB_Host, $this->DB_User, $this->DB_Pass, $this->DB_Name)
            or die("Sorry No DataBase Connection ");
    }
    public function getData($query)
    {
        $result = $this->link->query($query) or die($this->link->error);
        if ($result) {
            if ($result->num_rows > 0) {
                return $result;
            } else {
                return false;
            }
        }
    }
    public function insertData($query)
    {
        $result = $this->link->query($query) or die($this->link->error);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
    public function deleteData($query)
    {
        $result = $this->link->query($query) or die($this->link->error);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
}
?>
  • .htaccess:
RewriteEngine On
RewriteBase /


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST}      ^[A-Z]{3,}s+/(.*).phps+ [NC]
RewriteRule ^                   /router.php?get=%1 [L,QSA]


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST}      ^[A-Z]{3,}s+/([^/]+)/([^/]+)/?s+ [NC]
RewriteRule ^                   /%2.php?get=%1 [L,QSA]


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST}      ^[A-Z]{3,}s+/([^/]+)/s+ [NC]
RewriteRule ^                   /%1 [L,R=301,QSA]


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST}      ^[A-Z]{3,}s+/([^/]+)/?s+ [NC]
RewriteRule ^                   /router.php?get=%1 [L,QSA]
  • includes/dynamic.php:
<?php
session_start();
?>

<?php
include_once "config/config.php";
?>
<?php
include_once "libraries/Database.php";
?>

<?php
$database = new Database();
$data = $_GET['get'];
$data = explode('?', $data);
$data = $data[0];

// if (strpos($_SERVER['QUERY_STRING'], '&test') !== false) {
//  $data = stristr($_SERVER['QUERY_STRING'], '?get=');
//  $data = ltrim($data, '?get');
//  $data = strstr($data, '&test', true);
//  $data = str_replace('=', '', $data);
// }

$data = addslashes(str_replace('-', ' ', $data));

$town_result = $database->getData("select * from townstable where towncity = '$data'");

if (is_object($town_result)) {
    $area = $town_result->fetch_assoc();
} else {
    $town_result = $database->getData("select * from townstable where region = '$data'");
    if (is_object($town_result)) {
        $area = $town_result->fetch_assoc();
        $area['towncity'] = $area['region'];
    }
}
?>

The router.php page is a duplicate of index.php, it just include()s includes/dynamic.php

Redirect user after login

0

I am trying to redirect my users to the last visited page after they logged in on my custom login page, but after users logged in they stay on the login page, and I think it is because of my redirect I have added on my custom login page. Can someone please advise on this? Thank you.

This is my Login redirect on all pages to go to the login page:


function admin_redirect() {

    if ( !is_user_logged_in() ) {
        wp_redirect( home_url('member-login') );
        exit;
     }
};
add_action('get_header', 'admin_redirect');








And this is my function I try to redirect to last visited page, if users click on a article for example, to view it if they login. But it is still going to the 'member-login':


function admin_default_page($attributes) {
$attributes = isset($_SERVER[‘HTTP_REFERER’]) ? $_SERVER[‘HTTP_REFERER’] : ‘/member-login’;
return $attributes;
}

add_filter(‘login_redirect’, ‘admin_default_page’);



PHP: preg_match numbers after equal sign [duplicate]

I got this string: 1497=3&1498=41&1499=52&1496=21&1500=6

And i have to extract the number after the equal sign.

I have tried it with:

preg_match('/1498=(S)/', '1497=311&1498=41&1499=52&1496=21&1500=6', $matches);

But i only get the first number 4 and not 41.

Array
(
    [0] => 1498=4
    [1] => 4
)

And i don’t need Match 1 ([0] => 1498=4). So i only need 41 as output.

Thanks a lot.

unable to read PHP cURL result. var_dump works, but unable to pass it to variable

I have cURL function which reads remote json data. It works with many servers just fine, but now I need to use it on one specific website and it does not pass data to variable. I can still var_dump it or just simply echo it and it sends me to that website.

this is my remote server side code (simple just for here):

<?php echo json_encode(['test'=>'test']);?> 

this is my receiving end:

<?php    
        $ch = curl_init();
        $curlConfig = array(
            CURLOPT_URL            => 'http://binance99.unaux.com/index.php',
            CURLOPT_RETURNTRANSFER => true
        );
        curl_setopt_array($ch, $curlConfig);
        $r = curl_exec($ch);
        curl_close($ch);
        print_r(json_decode($r));
?>

there is nothing in $r, if I var_dump($r) it redirects me to the http://binance99.unaux.com/index.php,

I tried CURLOPT_HEADER => false, also I tried SSL version of my remote website, no luck.

I also tried file_get_contents() with same results.

Any help would be appreciated!

Read/Write data from/to PHP database and displaying data

I hope you are all doing well.

I have run into a few problems and can’t seem to find the answer online in an applicable way to my scenario. I am coding in Kotlin.

  1. I have a login activity with a username and password field, and a login button. I have managed to verify the login details by setting specific credentials but I now have a database, SQL, linked to my android app. How do I verify the login credentials the user input against the database and check if the user is active?

Name: Bobby <— just a random name
Database Host: sql99.dbn7.host-h.net <— just a random host
Database Name: JimmysWorldDB <— just a random db name
Driver Source: Built-in library

The tables used here are as follows:

1. UserLogins
    Column 1 : UserID
    Column 2 : FullName
    Column 3 : Username
    Column 4 : Password
    Column 5 : HasAccess

2. LoginRecords
    Column 1 : RecordID
    Column 2 : Date
    Column 3 : Logon     <--- This is a time field
    Column 4 : Logoff    <--- This is a time field
    Column 5 : Username
  1. So basically I would like to know how to make the app check the verify the Username and Password and only if the member HasAccess = true then have a successful login. <— All from UserLogins table

Then if the user has logged in successfully, save a LoginRecord where it puts the date, login time and the username.

My code is as follows below.

LoginActivity.kt
name of the button is button_login

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.jimmysworld.MainActivity
import com.jimmysworld.R
import com.jimmysworld.databinding.ActivityLoginBinding

class LoginActivity : AppCompatActivity() {

    private lateinit var loginViewModel: LoginViewModel
    private lateinit var binding: ActivityLoginBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val username = binding.username
        val password = binding.password
        val login = binding.login
        val loading = binding.loading

        loginViewModel = ViewModelProvider(this, LoginViewModelFactory())[LoginViewModel::class.java]

        loginViewModel.loginFormState.observe(this@LoginActivity, Observer {
            val loginState = it ?: return@Observer

            // disable login button unless both username / password is valid
            login.isEnabled = loginState.isDataValid

            if (loginState.usernameError != null) {
                username.error = getString(loginState.usernameError)
            }
            if (loginState.passwordError != null) {
                password.error = getString(loginState.passwordError)
            }
        })

        loginViewModel.loginResult.observe(this@LoginActivity, Observer {
            val loginResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (loginResult.error != null) {
                showLoginFailed(loginResult.error)
            }
            if (loginResult.success != null) {
                updateUiWithUser(loginResult.success)
            }
            setResult(Activity.RESULT_OK)

            //Complete and destroy login activity once successful
            finish()
        })

        username.afterTextChanged {
            loginViewModel.loginDataChanged(
                username.text.toString(),
                password.text.toString()
            )
        }

        password.apply {
            afterTextChanged {
                loginViewModel.loginDataChanged(
                    username.text.toString(),
                    password.text.toString()
                )
            }

            setOnEditorActionListener { _, actionId, _ ->
                when (actionId) {
                    EditorInfo.IME_ACTION_DONE ->
                        loginViewModel.login(
                            username.text.toString(),
                            password.text.toString()
                        )
                }
                false
            }

            login.setOnClickListener {
                loading.visibility = View.VISIBLE
                loginViewModel.login(username.text.toString(), password.text.toString())
            }
        }
    }

    private fun updateUiWithUser(model: LoggedInUserView) {
        val welcome = getString(R.string.welcome)
        val displayName = model.displayName
        // TODO : initiate successful logged in experience
        Toast.makeText(
            applicationContext,
            "$welcome $displayName",
            Toast.LENGTH_LONG
        ).show()
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
    }

    private fun showLoginFailed(@StringRes errorString: Int) {
        Toast.makeText(applicationContext, errorString, Toast.LENGTH_SHORT).show()
    }
}

LoginViewModel.kt

import android.util.Patterns
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.jimmysworld.R
import com.jimmysworld.data.LoginRepository
import com.jimmysworld.data.Result


class LoginViewModel(private val loginRepository: LoginRepository) : ViewModel() {

    private val _loginForm = MutableLiveData<LoginFormState>()
    val loginFormState: LiveData<LoginFormState> = _loginForm

    private val _loginResult = MutableLiveData<LoginResult>()
    val loginResult: LiveData<LoginResult> = _loginResult

    fun login(username: String, password: String) {
        // can be launched in a separate asynchronous job
        val result = loginRepository.login(username, password)
        val user = "Admin"
        val pass = "1234567"


        if (username.toString() == user && password.toString() == pass) {
            if (result is Result.Success) {
                _loginResult.value =
                    LoginResult(success = LoggedInUserView(displayName = result.data.displayName))
            }
        } else {
            _loginResult.value = LoginResult(error = R.string.login_failed)
        }
    }

    fun loginDataChanged(username: String, password: String) {
        if (!isUserNameValid(username)) {
            _loginForm.value = LoginFormState(usernameError = R.string.invalid_username)
        } else if (!isPasswordValid(password)) {
            _loginForm.value = LoginFormState(passwordError = R.string.invalid_password)
        } else {
            _loginForm.value = LoginFormState(isDataValid = true)
        }
    }

    // A placeholder username validation check
    private fun isUserNameValid(username: String): Boolean {
        return if (username.contains('@')) {
            Patterns.EMAIL_ADDRESS.matcher(username).matches()
        } else {
            username.isNotBlank()
        }
    }

    // A placeholder password validation check
    private fun isPasswordValid(password: String): Boolean {
        return password.length > 7
    }
}

LoggedInUser

import com.jimmysworld.data.model.LoggedInUser

class LoginRepository(val dataSource: LoginDataSource) {

    var user: LoggedInUser? = null
        private set

    val isLoggedIn: Boolean
        get() = user != null

    init {
        user = null
    }

    fun logout() {
        user = null
        dataSource.logout()
    }

    fun login(username: String, password: String): Result<LoggedInUser> {
        // handle login
        val result = dataSource.login(username, password)

        if (result is Result.Success) {
            setLoggedInUser(result.data)
        }

        return result
    }

    private fun setLoggedInUser(loggedInUser: LoggedInUser) {
        this.user = loggedInUser
    }
}

LoginViewModelFactory.kt

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.jimmysworld.data.LoginDataSource
import com.jimmysworld.data.LoginRepository


class LoginViewModelFactory : ViewModelProvider.Factory {

    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(LoginViewModel::class.java)) {
            return LoginViewModel(
                loginRepository = LoginRepository(
                    dataSource = LoginDataSource()
                )
            ) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

I am sorry for it being so long winded and appreciate any help I can get.
Thanks in advance.

How to use MongoDB in Laravel Testing

I have laravel project, which I’m using two database: relational PostgresSQL and MongoDB.

I have to write feature tests to database but. I don’t know how to create connection with mongo from laravel testing.

My phpunit.xml fragment file

<php>
        <env name="MONGO_DB_CONNECTION" value="mongodb"/>
        <env name="MONGO_DB_DSN" value="mongodb://localhost:27017"/>
        <env name="MONGO_DB_DATABASE" value="test"/>
        <env name="APP_ENV" value="testing"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="DB_CONNECTION" value="sqlite"/>
        <env name="DB_DATABASE" value=":memory:"/>
        <env name="MAIL_MAILER" value="array"/>
        <env name="QUEUE_CONNECTION" value="sync"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="TELESCOPE_ENABLED" value="false"/>
    </php>

config/database.php

'mongodb' => [
        'driver' => 'mongodb',
        'dsn' => env('MONGO_DB_DSN'),
        'database' => env('MONGO_DB_DATABASE', 'homestead'),
    ],

When I run test I got message:

MongoDBDriverExceptionConnectionTimeoutException : No suitable
servers found (serverSelectionTryOnce set): [connection refused
calling hello on ‘localhost:27017’]

Can I use MongoDB on memory like env name ‘DB_DATABASE’ variable

Display swagger on api route on Slim

I just started with php and Slim framework. My main goal is to generate a RESTful API where I have a /swagger route where I show the API documentation using swagger ui.

This are the steps I followed:

  • Install last version php
  • Install composer
  • Install required dependecies:
    • composer require slim/slim:”4.*”
    • composer require zircote/swagger-php
  • Create API project (composer create-project slim/slim-skeleton testAPI)
  • Anotate involved elements in my API
  • Generate swagger file (.vendorbinopenapi -output .swagger.json .src)
  • Add new route to my API:

use OpenApiGenerator as OpenApiGenerator;

/**
* @OAGet(
*     path="/openapi",
*     tags={"documentation"},
*     summary="OpenAPI JSON File that describes the API",
*     @OAResponse(response="200", description="OpenAPI Description File"),
* )
*/

    $app->get('/swagger', function ($request, $response, $args) {
        $swagger = OpenApiGenerator::scan(['../swagger.json']);
        $response->getBody()->write(json_encode($swagger));
        return $response->withHeader('Content-Type', 'application/json');
    });};

But when I go and run the api and check /swagger route this is what I get:

{
    "statusCode": 500,
    "error": {
        "type": "SERVER_ERROR",
        "description": "WARNING: Required @OA\PathItem() not found"
    }
}

Have I missed something? Or my OpenApiGenerator::scan([‘../swagger.json’]) does not make sense? I have seen people doing OpenApiGenerator::scan([‘.’]) but that gives me the exact same output.

run wordpress function – update_post_meta() inside ajax

I have ajax script to send form, I want to additionally run update_post_meta() function if success. I assume I can do this in ajax_response.php file, but this is not wordpress file, so wordpress functions don’t work there.
Which way is better to run this script, inside this ajax script (below), or somehow in ajax_response.php (but how initialize wordpress in this file?)
Script below is inside wordpress page.

$('#postForm').submit(function(e) {
           e.preventDefault();
           grecaptcha.ready(function () {
               grecaptcha.execute('6Lcg9l8jAAAAAAp4KIczCJ8N_xkOezJt7LngYVgu', { action: 'submit' }).then(function (token) {

            $("#googleResponse").val(token);
        
           $.ajax({
                   url: '/wp-content/themes/zaproszenie/ajax_response.php',
                   type: 'post',
                   data: $('#postForm').serialize(),
                   dataType: 'json',
                   success: function(data){
                       if(data.response == 'success')
                       {
                            $("#response").css('border','1px solid green');
                            $("#response").css('background','#ffffff');
                            $("#response").text(data.msg);
                       }
                       else
                       {
                           $("#response").css('border','1px solid red');
                           $("#response").css('background','#ffffff');
                           $("#response").text(data.msg);
                       }
                   }
            });
        });
    });
});

Symfony – AbstractFormLoginAuthenticator problem

I am building a very simple login page using Symfony framework.
I added

use SymfonyComponentSecurityGuardAuthenticatorAbstractFormLoginAuthenticator;

and called it as:

class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface

in my LoginFormAuthenticator.php but when I go to localhost, it says :

Attempted to load class “AbstractFormLoginAuthenticator” from namespace “SymfonyComponentSecurityGuardAuthenticator”.
Did you forget a “use” statement for another namespace?

What can be a problem here knowing that I called right class from right namespace, as it is declared in Symfony documentation?

Thank you in advance.

I expected to view my login page as everything is done regarding to Symfony documentation. Instead of that I am getting very bad error.
Screenshot

Unable to connect to server following phpMyAdmin upgrade from 5.1 to 5.2

Not sure to post on the right StackExchange forum. If not, let me know!

Working environment:

  • OpenSUSE Leap 15.4
  • MariaDB : mariadb Ver 15.1 Distrib 10.7.7-MariaDB
  • PHP 8.0.25 (cli) (built: Oct 31 2022 12:00:00) ( NTS )

Based on phpinfo(), PHP ini file is: /etc/php8/cli/php.ini.

phpMyAdmin 5.1 is working well. Installation directory is: /usr/share/phpMyAdmin (default directory created when installing via zypper install phpMyAdmin command).
The “famous” option $cfg['Servers'][$i]['host'] from /etc/phpMyAdmin/config.inc.php file is set to localhost (and it does work!).

I have then upgraded phpMyAdmin version this way:

srv-bla:~ # mv /usr/share/phpMyAdmin /usr/share/phpMyAdmin.old
srv-bla:~ # mkdir /usr/share/phpMyAdmin
srv-bla:~ # wget https://files.phpmyadmin.net/phpMyAdmin/5.2.0/phpMyAdmin-5.2.0-all-languages.tar.gz
srv-bla:~ # tar -xzf phpMyAdmin-5.2.0-all-languages.tar.gz
srv-bla:~ # mv phpMyAdmin-5.2.0-all-languages/* /usr/share/phpMyAdmin/

I then restart daemons and test the connection:

srv-bla:~ # systemctl restart mysqld mariadb apache2

The connection page is showing right. I then enter my credentials and I get stuck with this bloody message:

Impossible to connect to server.
mysqli::real_connect(): (HY000/2002): No such file or directory

I have wandered for a while on numerous webpages. Many of them suggest to modify the config.inc.php file and to set $cfg['Servers'][$i]['host'] option to 127.0.0.1 instead of localhost. Unfortunately, this does not fix the problem for me…

Am I editing the right config.inc.php file? Actually, I can find only one on the server:

srv-bla:~ # updatedb
srv-bla:~ # locate config.inc.php
/etc/phpMyAdmin/config.inc.php
/etc/phpMyAdmin/config.inc.php.rpmnew
/etc/phpMyAdmin/config.inc.php.rpmsave

Apache logs are not friendly either. Access logs returns 200 codes only, which seems normal to me (the phpMyAdmin webpage is served properly). Error logs are empty…
Mysql logs are empty also (/var/log/mysql/mysqld.log).

Or course, I have check that mysqld service (same as mariadb service) is running.

Any help or ideas would be much appreciated!


EDIT

The socket file from MariaDB point of view is:

srv-bla:~ # mariadb -u root -p
Enter password:
MariaDB [(none)]> s
[...]
UNIX socket: /var/lib/mysql/mysql.sock
[...]

The php.ini file is configured the same way:

srv-bla:~ # cat /etc/php8/cli/php.ini | grep mysqli.default_socket
mysqli.default_socket = /var/lib/mysql/mysql.sock

To me, there is no socket issue…

PHP Object Array – Strip Previous Declared Records

I have a bit of strange question, hopefully it makes sense.

So I have the following array of objects

$users_array[] = (object) array('name' => 'Vicky', 'attend' => 'X1 - on');
$users_array[] = (object) array('name' => 'Brian', 'attend' => 'X1 - off');
$users_array[] = (object) array('name' => 'Nick', 'attend' => 'X1 - on');
$users_array[] = (object) array('name' => 'Sarah', 'attend' => 'X2 - off');
$users_array[] = (object) array('name' => 'Vicky', 'attend' => 'X2 - on');
$users_array[] = (object) array('name' => 'Doan', 'attend' => 'X2 - on');
$users_array[] = (object) array('name' => 'Harry', 'attend' => 'X1 - off');
$users_array[] = (object) array('name' => 'Sarah', 'attend' => 'X1 - on');
$users_array[] = (object) array('name' => 'David', 'attend' => 'X2 - on');

Sometimes I only have a couple of objects, but I can have up to 200 in some cases.

If I run

foreach($users_array as $user) :
    echo 'Name: ' . $user->name;
    echo ' | ';
    echo 'In: ' . $user->attend;
    echo '<br>';
endforeach;

I get the following

1. Name: Vicky | In: X1 - on
2. Name: Brian | In: X1 - off
3. Name: Nick | In: X1 - on
4. Name: Sarah | In: X2 - off
5. Name: Vicky | In: X2 - on
6. Name: Doan | In: X2 - on
7. Name: Harry | In: X1 - off
8. Name: Sarah | In: X1 - on
9. Name: David | In: X2 - on

which is great

You will see I have markers titled “X1″ and X2”, so what I want to do is strip any previously declared values, unless a new marker comes into play

So with the above it would return

1. Name: Vicky | In: X1 - on
2. Name: Brian | In: X1 - off
4. Name: Sarah | In: X2 - off
5. Name: Vicky | In: X2 - on
7. Name: Harry | In: X1 - off
8. Name: Sarah | In: X1 - on
9. Name: David | In: X2 - on

So it would strip row 3 because it was already declared on row 1, and it would strip row 6 as it was already declared on row 5

Is this possible?

Thanks so much

The controller is not callable

Hello all I’m migrating symfony to version 5.4 and I’m having a problem with a controller:

The controller for URI "/api/resetting/tokentest/reset.json" is not callable: Controller "WOODUserBundleControllerResettingRESTController" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?

As specified in the documentation, I added the controller.service_arguments tag but the problem still occurs. Do you have an idea please?

# Form factory WOODUserBundleControllerResettingRESTController: '@fos_user.profile.form.factory' tags: ['controller.service_arguments']