data cant be save in database

i have a registration form and i want to store the information (gender and phone included) but it didnt store in the database even the register is successful but the column for gender and phone_number are blank
– I had tried to change my structure of gender from ENUM “MALE”, “FEMALE” to varchr(50) also not work

  • when ENUM, it shows empty

  • when varchar, it shows 0

    also my phone number also stated blank

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `full_name` varchar(100) NOT NULL,
  `nickname` varchar(50) NOT NULL,
  `user_id` varchar(50) NOT NULL,
  `gender` varchar(50) NOT NULL,
  `age` int(11) NOT NULL,
  `address` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phone_number` varchar(20) NOT NULL,
  `country` varchar(50) NOT NULL,
  `user_type` varchar(50) NOT NULL,
  `program` varchar(100) NOT NULL,
  `department` varchar(50) DEFAULT NULL,
  `password` varchar(255) NOT NULL,
  `avatar_url` varchar(255) DEFAULT NULL,
  `registration_date` timestamp NOT NULL DEFAULT current_timestamp()
) 
20, 'AFLRED', 'CEO of MDIS', 'DCT-1151', '', 69, '54,Jalan Impian 20', '[email protected]', '', 'MY', 'STAFF', '', 'OFFICE OF THE REGISTER', '$2y$10$JJZVYp5DQ7QC6SMT0zYQC.Eq84gJtW8ATwhBxTWExE1xW5EQ.nVTG', './uploads/MDIS-badge.png', '2024-07-23 17:04:20'),

my phone number and gender are not being record

<?php
session_start();
$conn = new mysqli("localhost", "root", "", "forum");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$avatar_url = null; // Initialize $avatar_url

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and validate inputs
    $full_name = $conn->real_escape_string($_POST['full_name']);
    $nickname = $conn->real_escape_string($_POST['nickname']);
    $user_id = $conn->real_escape_string($_POST['user_id']);
    $gender = $conn->real_escape_string($_POST['gender']);
    $age = (int)$_POST['age'];
    $address = $conn->real_escape_string($_POST['address']);
    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ? $_POST['email'] : "";
    $phone_number = preg_match("/^[0-9]{10,15}$/", $_POST['phone_number']) ? $_POST['phone_number'] : "";
    $country = $conn->real_escape_string($_POST['country']);
    $user_type = $conn->real_escape_string($_POST['user_type']);
    $program = $conn->real_escape_string($_POST['program']);
    $department = $conn->real_escape_string($_POST['department'] ?? '');
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    
    // Handle file upload
    if (isset($_FILES['avatar_url']) && $_FILES['avatar_url']['error'] == UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES['avatar_url']['tmp_name'];
        $fileName = $_FILES['avatar_url']['name'];
        $fileSize = $_FILES['avatar_url']['size'];
        $fileType = $_FILES['avatar_url']['type'];
        $fileNameCmps = explode(".", $fileName);
        $fileExtension = strtolower(end($fileNameCmps));

        // Set allowed file extensions
        $allowedExts = array('jpg', 'jpeg', 'png', 'gif');
        if (in_array($fileExtension, $allowedExts)) {
            // Move file to destination directory
            $uploadFileDir = './uploads/';
            $dest_path = $uploadFileDir . $fileName;

            if (move_uploaded_file($fileTmpPath, $dest_path)) {
                // Store file path in $avatar_url
                $avatar_url = $dest_path;
            } else {
                $_SESSION['error'] = 'Error moving the file.';
                header("Location: register page.php");
                exit();
            }
        } else {
            $_SESSION['error'] = 'Invalid file type.';
            header("Location: register page.php");
            exit();
        }
    }
    
    // Check password match
    if ($password !== $confirm_password) {
        $_SESSION['error'] = 'Passwords do not match.';
        header("Location: register page.php");
        exit();
    }

    // Hash the password
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Prepare and execute statement to check if user_id already exists
    $stmt = $conn->prepare("SELECT COUNT(*) FROM users WHERE user_id = ?");
    $stmt->bind_param("s", $user_id);
    $stmt->execute();
    $stmt->bind_result($count);
    $stmt->fetch();
    $stmt->close();

    if ($count > 0) {
        $_SESSION['error'] = 'ID already exists. Please use a different ID.';
        header("Location: register page.php");
    } else {
        // Prepare and execute statement to insert user data
        $stmt = $conn->prepare("INSERT INTO users (full_name, nickname, user_id, gender, age, address, email, phone_number, country, user_type, program, department, password, avatar_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssissssssssss", $full_name, $nickname, $user_id, $gender, $age, $address, $email, $phone_number, $country, $user_type, $program, $department, $hashed_password, $avatar_url);

        // Execute the statement
        if ($stmt->execute()) {
            header("Location: index.html");
            exit();
        } else {
            $_SESSION['error'] = "Error: " . $stmt->error;
            header("Location: register page.php");
        }

        $stmt->close();
    }

    $conn->close();
}
?>

i want my gender can be display either male or female in database and the phone_number also can be display in varchar

MySQL data to OneDrive [closed]

We are using windows server and scheduled phpscript to extract MYSQL data and load into csv file, then upload it to Onedrive. However this process in the recent days seems to be troublesome.

We are trying to find an alternative without using windows server.

Is there anyway please?

Thanks

How to make doctrine autofill generated values to model?

I have model that allows only to read property CreatedAt. This field is generated by SQL.

/**
   * @ORMId
   * @ORMColumn(type="integer")
   * @ORMGeneratedValue
   */
  private $Id;

...
/**
   * @ORMColumn(type="datetime", insertable=false, updatable=false)
   */
  private $CreatedAt;

It works fine exept 1 case: I can’t get that field upon creation:

$newObject = NewClassName();
$this->entityManager->persist($newObject);
$this->entityManager->flush();

$newObject->getId(); \ = 1234 (some generated integer)
$newObject->getCreatedAt(); \ = null

So question is: how to meke doctrine to autofill this field upon creation like it happens to $Id field

I’ve tried adding @GeneratedValue – does not work;

For now I use detach and getting it from DB after creation:

$newObject = NewClassName();
$this->entityManager->persist($newObject);
$this->entityManager->flush();
if ($newObject->getId()) {
      $this->entityManager->detach($newObject);
      $newObject = $this->entityManager->getRepository(NewClassName::class)->find($newObject->getId());


$newObject->getCreated(); \ = DateTime object

But I guess there is a better way. Thanks forahead!

Laravel BadMethodCall Exception

I’m running a website on server using php-fpm, nginx. It is using Laravel Framework. Randomly server stopped working and start giving me BadMethodCall Exception. But there is no method listed in there.

/var/www/site/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:71
Call to undefined method IlluminateDatabaseQueryJoinClause::()

I checked the memory on server and have 30 gb of free memory.

Complete stacktrace of earlier instance. Everytime it is form different place.

{
    "message": "Call to undefined method Illuminate\Database\Query\Builder::()",
    "exception": "BadMethodCallException",
    "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php",
    "line": 71,
    "trace": [
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php",
            "line": 3538,
            "function": "throwBadMethodCallException",
            "class": "Illuminate\Database\Query\Builder",
            "type": "::"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php",
            "line": 23,
            "function": "__call",
            "class": "Illuminate\Database\Query\Builder",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php",
            "line": 1660,
            "function": "forwardCallTo",
            "class": "Illuminate\Database\Eloquent\Builder",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php",
            "line": 23,
            "function": "__call",
            "class": "Illuminate\Database\Eloquent\Builder",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php",
            "line": 2132,
            "function": "forwardCallTo",
            "class": "Illuminate\Database\Eloquent\Model",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php",
            "line": 87,
            "function": "__call",
            "class": "Illuminate\Database\Eloquent\Model",
            "type": "->"
        },
        {
            "file": "/var/www/site/app/Models/Device/Device.php",
            "line": 52,
            "function": "hasOne",
            "class": "Illuminate\Database\Eloquent\Model",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php",
            "line": 539,
            "function": "site",
            "class": "App\Models\Device\Device",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php",
            "line": 491,
            "function": "getRelationshipFromMethod",
            "class": "Illuminate\Database\Eloquent\Model",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php",
            "line": 440,
            "function": "getRelationValue",
            "class": "Illuminate\Database\Eloquent\Model",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php",
            "line": 2029,
            "function": "getAttribute",
            "class": "Illuminate\Database\Eloquent\Model",
            "type": "->"
        },
        {
            "file": "/var/www/site/app/Http/Controllers/Api/V1/AuthController.php",
            "line": 107,
            "function": "__get",
            "class": "Illuminate\Database\Eloquent\Model",
            "type": "->"
        },
        {
            "file": "/var/www/site/app/Http/Controllers/Api/V1/AuthController.php",
            "line": 102,
            "function": "checkDeviceIsOrphan",
            "class": "App\Http\Controllers\Api\V1\AuthController",
            "type": "->"
        },
        {
            "file": "/var/www/site/app/Http/Controllers/Api/V1/AuthController.php",
            "line": 89,
            "function": "checkDeviceIsActive",
            "class": "App\Http\Controllers\Api\V1\AuthController",
            "type": "->"
        },
        {
            "file": "/var/www/site/app/Http/Controllers/Api/V1/AuthController.php",
            "line": 55,
            "function": "checkDevice",
            "class": "App\Http\Controllers\Api\V1\AuthController",
            "type": "->"
        },
        {
            "file": "/var/www/site/app/Http/Controllers/Api/V1/AuthController.php",
            "line": 38,
            "function": "validateDevice",
            "class": "App\Http\Controllers\Api\V1\AuthController",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Routing/Controller.php",
            "line": 54,
            "function": "validation",
            "class": "App\Http\Controllers\Api\V1\AuthController",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php",
            "line": 45,
            "function": "callAction",
            "class": "Illuminate\Routing\Controller",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Routing/Route.php",
            "line": 262,
            "function": "dispatch",
            "class": "Illuminate\Routing\ControllerDispatcher",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Routing/Route.php",
            "line": 205,
            "function": "runController",
            "class": "Illuminate\Routing\Route",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
            "line": 721,
            "function": "run",
            "class": "Illuminate\Routing\Route",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 128,
            "function": "Illuminate\Routing\{closure}",
            "class": "Illuminate\Routing\Router",
            "type": "->"
        },
        {
            "file": "/var/www/site/app/Http/Middleware/RedirectIfAuthenticated.php",
            "line": 24,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "App\Http\Middleware\RedirectIfAuthenticated",
            "type": "->"
        },
        {
            "file": "/var/www/site/app/Http/Middleware/ApiSetLocale.php",
            "line": 29,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "App\Http\Middleware\ApiSetLocale",
            "type": "->"
        },
        {
            "file": "/var/www/site/app/Http/Middleware/ApiDataLogger.php",
            "line": 49,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "App\Http\Middleware\ApiDataLogger",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php",
            "line": 50,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Routing\Middleware\SubstituteBindings",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php",
            "line": 127,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php",
            "line": 63,
            "function": "handleRequest",
            "class": "Illuminate\Routing\Middleware\ThrottleRequests",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Routing\Middleware\ThrottleRequests",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 103,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
            "line": 723,
            "function": "then",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
            "line": 698,
            "function": "runRouteWithinStack",
            "class": "Illuminate\Routing\Router",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
            "line": 662,
            "function": "runRoute",
            "class": "Illuminate\Routing\Router",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
            "line": 651,
            "function": "dispatchToRoute",
            "class": "Illuminate\Routing\Router",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
            "line": 167,
            "function": "dispatch",
            "class": "Illuminate\Routing\Router",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 128,
            "function": "Illuminate\Foundation\Http\{closure}",
            "class": "Illuminate\Foundation\Http\Kernel",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php",
            "line": 21,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php",
            "line": 31,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php",
            "line": 21,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php",
            "line": 40,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\TrimStrings",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php",
            "line": 27,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\ValidatePostSize",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php",
            "line": 86,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/fideloper/proxy/src/TrustProxies.php",
            "line": 57,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 167,
            "function": "handle",
            "class": "Fideloper\Proxy\TrustProxies",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
            "line": 103,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
            "line": 142,
            "function": "then",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "/var/www/site/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
            "line": 111,
            "function": "sendRequestThroughRouter",
            "class": "Illuminate\Foundation\Http\Kernel",
            "type": "->"
        },
        {
            "file": "/var/www/site/public/index.php",
            "line": 55,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Kernel",
            "type": "->"
        }
    ]
}

Device.php

<?php
/**
 * 
 * 
 * 
 * 
 **/
namespace AppModelsDevice;

use AppModelsLookupsCountry;
use AppModelsLookupsLanguage;
use AppModelsSiteSite;
use IlluminateFoundationAuthUser as Authenticatable;
use LaravelPassportHasApiTokens;

class Device extends Authenticatable
{
    use HasApiTokens;

    /**
     * The table associated with the model.
     *
     * @varstring
     */
    // 

    /**
     * The primary key associated with the table.
     *
     * @varstring
     */
    // 

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = true;

    const CREATED_AT = 'dt_created_at';
    const UPDATED_AT = 'dt_updated_at';

    protected $dateFormat = 'Y-m-d H:i:sO';

    protected $fillable = [
        //
    ];

    public function site()
    {
        return $this->hasOne(Site::class, 'cid', 'cid');
    }

    public function language()
    {
        return $this->hasOne(Language::class);
    }

    public function country()
    {
        return $this->hasOne(Country::class);
    }

    //
    // 
}

Problem connecting to SQL with PHP – This extension requires the Microsoft ODBC Driver for SQL Server to communicate with SQL Server [duplicate]

I’m on a shared hosting platform with Krystal running Ubuntu, trying to connect to an SQL database in house with PHP but I’m getting the error:

Caught PDO exception:

SQLSTATE[IMSSP]: This extension requires the Microsoft ODBC Driver for SQL Server to communicate with SQL Server. Access the following URL to download the ODBC Driver for SQL Server for x64: https://go.microsoft.com/fwlink/?LinkId=163712

Yet looking at phpinfo – the driver looks like it’s running…

Here’s my code

<?php

try {
    $serverName = "server***";
    $databaseName = "db***";
    $uid = "uid***";
    $pwd = "pwd***";

    $conn = new PDO("sqlsrv:server = $serverName; Database = $databaseName;", $uid, $pwd);

    // Select Query
    $tsql = "SELECT @@Version AS SQL_VERSION";

    // Executes the query
    $stmt = $conn->query($tsql);
} catch (PDOException $exception1) {
    echo "<h1>Caught PDO exception:</h1>";
    echo $exception1->getMessage() . PHP_EOL;
    echo "<h1>PHP Info for troubleshooting</h1>";
    phpinfo();
}

?>

<h1> Success Results : </h1>

<?php
try {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo $row['SQL_VERSION'] . PHP_EOL;
    }
} catch (PDOException $exception2) {
    // Display errors
    echo "<h1>Caught PDO exception:</h1>";
    echo $exception2->getMessage() . PHP_EOL;
}

unset($stmt);
unset($conn);
?>

I’ve Googled the hell out of this – everything points to the driver missing but looking at phpinfo, if I’m reading it correctly, everything is there – any ideas?

PHP Info
enter image description here

php, using require_once() properly

I have a page with a variable and a function:

test.php

<?php
  $myVar = "myVar";
  
  function myFunc() {
    echo "myFunc()";
  }
?>

The first page that includes it, can see the variable value.

<?php
  echo "page1";
  require_once("include/test.php");
  print_r($myVar);

function GoTo2() {
  $urlSite = "page2.php";
  include($urlSite); 
  exit();
}

GoTo2();
?>

but the second page, cannot see the variable.

<?php
  echo "page2n";
  require_once("include/test.php");
  print_r($myVar);
?>

it generates PHP Warning: Undefined variable $myVar in .../page2.php on line 4

I cannot use require() in the second page, because it generates an error – PHP Fatal error: Cannot redeclare myFunc() (previously declared in .../include/test.php) in .../include/test.php ...

What is the proper php way that both pages can see the variable and also can use the function?

EDIT:

  • this is a simplified of my real pages. I just discovered that page2 cannot see the variable when the site was upgraded to php8, and I recieved all “Undefined variable” warnings.
  • page1 is a “dispatcher” page
  • suppose I inherited this code from another developper, what is the best solution to solve the problem?

Symfony not existing routes after cache update

This is the first time I’ve encountered this, after the bin/console cache:clear non-existent routes appeared, physically such methods no longer exist in the controller, and accordingly it doesn’t see new ones either…
Symfony 5.4

Маршруты проверяю:
bin/console debug:router
When viewing the route in detail,
bin/console debug:router nameroute
it shows that it found a method in the controller!?!

Even completely manually deleting the contents of the cache folder did not produce results. I can’t understand where he gets the old routes from.
After the command bin/console cache:clear, all files are created new in the cache folder.

enter image description here

Correct email validations in PHP laravel Livewire

I want to validate emails correctly , the correct email must adhere to the following validation rules

(a) email must end with either .com , .gov , got , co , .uk , etc

(b)email must be unique

public $email = '';
    
        protected $rules = [
            'email' => 'required|email|min:3|unique:subscribers,email|regex:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-z]{2,3}$/',
        ];
    
        protected $messages = [
            'email.required' => 'The email field is required.',
            'email.email' => 'Please provide a valid email address.',
            'email.unique' => 'This email is already subscribed.',
            'email.regex' => 'The email must be a valid format (e.g., must include ".com").',
        ];
    
        public function updated($propertyName)
        {
            $this->validateOnly($propertyName);
        }
    
        public function submit()
        {
            $validated = $this->validate();
    
            // Save the email to the subscribers table
            Subscriber::create(['email' => $this->email]);
    
            // Send email
            Mail::to($this->email)->send(new SubscriptionMail($this->email));
    
            $this->reset();
            session()->flash('success', 'You have subscribed successfully!');
        }
   

the codes above does not work ,

Assets got net::ERR_ABORTED 404 (Not Found) in route `/` on Laravel 10 with Nginx server

I got so many net::ERR_ABORTED 404 (Not Found) for my public/assets file when accessing the route of / but when I tried another route like /home with the same page and same file its works fine.
error image
I deployed my Laravel 10 project on Ubuntu 22 with Nginx.

this is my Nginx virtual host configuration file :

server {
    listen 80;

    root /var/www/v2-hexagon/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    server_name compro.hexagon.co.id www.compro.hexagon.co.id;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    location ~ .php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /.(?!well-known).* {
        deny all;
    }
}

and this is my routes/web.php file :

<?php

use IlluminateSupportFacadesRoute;

Route::get('/', function () {
    return view('Home');
})->name('Home');

Route::get('/home', function () {
    return view('Home');
})->name('Home');

Route::get('/about', function () {
    return view('about');
})->name('About');

Route::get('/Portofolio', function () {
    return view('Portofolio');
})->name('Portofolio');

Route::get('/Services', function () {
    return view('Services');
})->name('Services');

Route::get('/News', function () {
    return view('News');
})->name('News');

Route::get('/Career', function () {
    return view('Career');
})->name('Career');

Route::get('/Contact', function () {
    return view('Contact');
})->name('Contact');

Route::get('/News/Post/{id}', function ($id) {
    return view('singlepost', ['id' => $id]);
})->name('singlepost');

Route::get('/Portofolio/Post/{id}', function ($id) {
    return view('singleporto', ['id' => $id]);
})->name('singleporto');

// Route::get('/about_layout', function () {
//     return view('about_layout');
// });

Route::get('/Service/IT Consultation', function () {
    return view('IT Consultation');
})->name('IT Consultation');


Route::get('/Service/Digital Marketing', function () {
    return view('Digital Marketing');
})->name('Digital Marketing');


Route::get('/Service/Branding', function () {
    return view('Branding');
})->name('Branding');

To be clear, I got this kind of error only when accessing the route / but when I accessing the /home route with same function it works fine.
Any helps?

How to pass correct URL for SetUp Intent on Stripe for subscriptions

Hello am getting this error when i try to create a subscription to my Ionic 5 angular 14, capacitor 5 project

Setup Intent: {id: 'seti_1Pej4HGozbMWFnur4OWfvqdA', object: 'setup_intent', automatic_payment_methods: {…}, cancellation_reason: null, client_secret: 'seti_1Pej4HGozbMWFnur4OWfvqdA_secret_QVkZdP11j4gFm56rj95UypBo3PHvYU8', …}
subscription.page.ts:127 Setup Intent ID: seti_1Pej4HGozbMWFnur4OWfvqdA
subscription.page.ts:128 Payment Method: pm_1Pej4lGozbMWFnurI7EVBUxj
subscription.page.ts:140 Subscribing with Payment Method ID: pm_1Pej4lGozbMWFnurI7EVBUxj
subscription.page.ts:141 Subscribing with SetupIntent ID: seti_1Pej4HGozbMWFnur4OWfvqdA
subscription.page.ts:149 Could not determine which URL to request: StripeSetupIntent instance has invalid ID: 

in this component code

import { Component, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { UserData } from 'src/app/services/user-data/user-data';
import { loadStripe, Stripe, StripeElements, StripeElementsOptions, PaymentMethod } from '@stripe/stripe-js';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-subscription',
  templateUrl: 'subscription.page.html',
  styleUrls: ['subscription.page.scss'],
})
export class SubscriptionPage implements AfterViewInit {
  @ViewChild('paymentElement') paymentElementRef: ElementRef;
  stripe: Stripe;
  elements: StripeElements;
  clientSecret: string;
  planId = 'price_1OPuphGozbMWFnudfddsfgh';
  customerId: any;
  isPaymentElementFilled: boolean = false;

  appearance: StripeElementsOptions['appearance'] = {
    theme: 'stripe',
    variables: {
      colorPrimary: '#0570de',
      colorBackground: '#ffffff',
      colorText: '#30313d',
      colorDanger: '#df1b41',
      fontFamily: 'Ideal Sans, system-ui, sans-serif',
      spacingUnit: '2px',
      borderRadius: '4px',
    },
  };

  user: any = {};
  email: string = '';
  uid: string = '';
  paymentMethod: string | PaymentMethod;
  menuOpenCopyright: boolean = false;

  modalOpen: boolean = false;
  cardInputFocused: boolean = false;

  constructor(public router: Router, public userData: UserData) {
    this.user = this.userData.getUserData();
    this.uid = this.user.uid;
    this.email = this.user.email;
  }

  ngAfterViewInit() {
    this.createCustomerAndSetupIntent();
  }

  createCustomerAndSetupIntent() {
    this.userData.createCustomer(this.email).subscribe((customerResponse: any) => {
      if (customerResponse.success) {
        this.customerId = customerResponse.customer.id;
        this.userData.createSetupIntent(this.customerId).subscribe((setupIntentResponse: any) => {
          if (setupIntentResponse.success) {
            this.clientSecret = setupIntentResponse.setupIntent.client_secret;
            console.log('Client Secret:', this.clientSecret);

            this.initializeStripe().then(() => {
              this.createPaymentElement(this.clientSecret);
            }).catch(error => {
              console.error('Error initializing Stripe:', error);
            });
          } else {
            console.error(setupIntentResponse.error);
          }
        });
      } else {
        console.error(customerResponse.error);
      }
    });
  }

  async initializeStripe() {
    const stripePromise = loadStripe('pk_test_51HiSUoGozbMWFnurWW3azSXFZV47mcnH8p4MQG6HvbHuszrDPvUFYuq15TbVqZujcJNv4CSHSqkAkFm3pRk7nwod00iHfdert');
    this.stripe = await stripePromise;
  }

  createPaymentElement(clientSecret: string) {
    if (!this.stripe) {
      console.error('Stripe is not initialized.');
      return;
    }

    this.elements = this.stripe.elements({
      clientSecret: clientSecret,
      appearance: this.appearance,
    });

    const paymentElementOptions = {};

    const paymentElement = this.elements.create('payment', paymentElementOptions);

    paymentElement.on('change', (event) => {
      this.isPaymentElementFilled = event.complete;
    });

    paymentElement.mount(this.paymentElementRef.nativeElement);
  }

  async confirmPayment() {
    const result: any = await this.stripe.confirmSetup({
      elements: this.elements,
      confirmParams: {
        return_url: window.location.href,
        payment_method_data: {
          billing_details: {
            email: this.email,
          },
        },
      },
      redirect: 'if_required' // Disable automatic redirection
    });

    console.log('Setup Intent:', result.setupIntent);

    if (result.error) {
      console.error(result.error);
    } else if (result.setupIntent) {
      const setupIntent = result.setupIntent;
      if (setupIntent.status === 'succeeded') {
        const paymentMethod = setupIntent.payment_method;
        this.paymentMethod = paymentMethod;
        console.log('Setup Intent ID:', setupIntent.id); // Log setupIntent ID
        console.log('Payment Method:', paymentMethod); // Log payment method
        this.subscribe(paymentMethod, setupIntent.id);
      } else {
        console.error('Setup Intent not succeeded:', setupIntent);
      }
    } else {
      console.error('Unexpected result structure:', result);
    }
  }

  async subscribe(paymentMethod: string | PaymentMethod, setupIntentId: string) {
    const paymentMethodId = typeof paymentMethod === 'string' ? paymentMethod : paymentMethod.id;
    console.log('Subscribing with Payment Method ID:', paymentMethodId); // Log payment method ID
    console.log('Subscribing with SetupIntent ID:', setupIntentId); // Log setupIntent ID

    this.userData.createSubscription(this.customerId, this.planId, setupIntentId).subscribe((subscriptionResponse: any) => {
      if (subscriptionResponse.success) {
        console.log('Subscription successful:', subscriptionResponse.subscription);
        this.showSubscriptionSuccess();
        this.router.navigate(['app/tablinks/home']);
      } else {
        console.error(subscriptionResponse.error);
      }
    });
  }




  showSubscriptionSuccess() {
    Swal.fire({
      title: 'Subscription Successful',
      text: 'Your subscription has been successfully created.',
      icon: 'success',
      confirmButtonText: 'OK'
    });
  }

user-data functions

createCustomer(email: string): Observable<any> {
        const url = this.appData.getApiUrl() + 'createCustomer';
        const data = this.jsonToURLEncoded({
          api_signature: this.api_signature,
          email: email,
        });
    
        return this.http.post(url, data, { headers: this.options.headers });
      }
    
      createSetupIntent(customerId: string): Observable<any> {
        const url = this.appData.getApiUrl() + 'createSetupIntent';
        const data = this.jsonToURLEncoded({
          customerId: customerId,
        });
    
        return this.http.post(url, data, { headers: this.options.headers });
      }
    
      createSubscription(customerId: string, planId: string, setupIntentId: string): Observable<any> {
        const url = this.appData.getApiUrl() + 'createSubscription';
        const data = this.jsonToURLEncoded({
            customerId: customerId,
            planId: planId,
            setupIntentId: setupIntentId
        });
    
        return this.http.post(url, data, { headers: this.options.headers });
    } 

php functions

  function createCustomer() {
    $request = SlimSlim::getInstance()->request();
    $response['success'] = true;

    $userEmail = $request->post('email');

    try {
        // Create a new Stripe customer
        $customer = StripeCustomer::create([
            'email' => $userEmail,
        ]);

        $userStripeCustomerId = $customer->id;

        // Update the user record in the database with the Stripe customer ID
        $db = getDB();
        $sql = "UPDATE users SET customer_id = :customer_id WHERE email = :email";
        $stmt = $db->prepare($sql);
        $stmt->bindParam(":customer_id", $userStripeCustomerId, PDO::PARAM_STR);
        $stmt->bindParam(":email", $userEmail, PDO::PARAM_STR);
        $stmt->execute();

        $response = [
            'customer' => $customer,
            'success' => true,
        ];
    } catch (StripeExceptionCardException $e) {
        $response = [
            'error' => $e->getMessage(),
            'success' => false,
        ];
    }

    echo json_encode($response);
}

function createSetupIntent() {
    $request = SlimSlim::getInstance()->request();
    $response['success'] = true;

    $customerId = $request->post('customerId');

    try {
        // Create a SetupIntent for the given customer
        $setupIntent = StripeSetupIntent::create([
            'customer' => $customerId,
        ]);
        $clientSecret = $setupIntent->client_secret;

        $response = [
            'setupIntent' => $setupIntent,
            'clientSecret' => $clientSecret,
            'success' => true,
        ];
    } catch (StripeExceptionCardException $e) {
        $response = [
            'error' => $e->getMessage(),
            'success' => false,
        ];
    }

    echo json_encode($response);
}


function createSubscription() {
    $request = SlimSlim::getInstance()->request();
    $response = ['success' => true];

    $customerId = $request->post('customerId');
    $planId = $request->post('planId');
    $setupIntentId = $request->post('setupIntentId'); // Receiving setupIntentId from frontend

    // Log received setupIntentId
    error_log("Received setupIntentId: " . $setupIntentId);

    try {
        // Retrieve the SetupIntent using the setupIntentId
        $setupIntent = StripeSetupIntent::retrieve($setupIntentId);
        
        // Log the retrieved setupIntent
        error_log("Retrieved SetupIntent: " . print_r($setupIntent, true));

        if ($setupIntent->status !== 'succeeded') {
            throw new Exception("SetupIntent is not succeeded.");
        }

        $paymentMethod = $setupIntent->payment_method;

        // Create a subscription for the customer with the specified plan
        $subscription = StripeSubscription::create([
            'customer' => $customerId,
            'items' => [
                [
                    'price' => $planId,
                ],
            ],
            'default_payment_method' => $paymentMethod,
        ]);

        $response = [
            'subscription' => $subscription,
            'success' => true,
        ];
    } catch (StripeExceptionApiErrorException $e) {
        // Log Stripe API errors
        error_log("Stripe API error: " . $e->getMessage());
        $response = [
            'error' => $e->getMessage(),
            'success' => false,
        ];
    } catch (Exception $e) {
        // Log general exceptions
        error_log("General error: " . $e->getMessage());
        $response = [
            'error' => $e->getMessage(),
            'success' => false,
        ];
    }

    echo json_encode($response);
}

It looks like the issue stems from how the setupIntentId and paymentMethodId are being used in the subscription creation process. The error message “Could not determine which URL to request: StripeSetupIntent instance has invalid ID” suggests that there’s a problem with the ID being passed. How do i fix that? Is a problem with the code or i have to do some implementation in Stripe dashboard?
Can you give me any help? Thanks

Dynamically created ACF select field returning false

I am using this which lists all posts from a CPT on site 1, from site 2 (multisite wordpress site).

On site 2, I select the name in the select field and shows as selected after the page has updated, but on the front-end of the site there are no values selected. CAn anyone help me figure this out please?

function populate_speakers_field_from_site_1($field) {
    // Switch to Site 1
    $site_1_id = 1; // Replace with your Site 1 ID
    switch_to_blog($site_1_id);

    // Fetch all speakers
    $args = array(
        'post_type' => 'speakers',
        'post_status' => 'publish',
        'orderby' => 'title',
        'order' => 'asc',
        'posts_per_page' => -1
    );

    $speakers_query = new WP_Query($args);

    // Reset choices
    $field['choices'] = array();

    // Loop through speakers and add to field choices
    if ($speakers_query->have_posts()) {
        while ($speakers_query->have_posts()) {
            $speakers_query->the_post();
            $field['choices'][get_the_ID()] = get_the_title();
        }
        wp_reset_postdata();
    }

    // Restore to current blog (Site 2)
    restore_current_blog();

    return $field;
}
add_filter('acf/load_field/key=field_6699142ff52aa', 'populate_speakers_field_from_site_1');

and to retrieve the data I’m just doing a simple var_dump(get_field_object('field_6699142ff52aa'));

C:wamp64wwwesmediawp-contentthemesES-Livetemplatestemplate-events.php:241:
array (size=26)
  'ID' => int 244
  'key' => string 'field_6699142ff52aa' (length=19)
  'label' => string 'Speakers Names' (length=14)
  'name' => string 'scheduled_speakers' (length=18)
  'aria-label' => string '' (length=0)
  'prefix' => string 'acf' (length=3)
  'type' => string 'select' (length=6)
  'value' => 
    array (size=0)
      empty
  'menu_order' => int 9
  'instructions' => string '' (length=0)
  'required' => int 0
  'id' => string '' (length=0)
  'class' => string '' (length=0)
  'conditional_logic' => 
    array (size=1)
      0 => 
        array (size=1)
          0 => 
            array (size=3)
              ...
  'parent' => int 150
  'wrapper' => 
    array (size=3)
      'width' => string '' (length=0)
      'class' => string '' (length=0)
      'id' => string '' (length=0)
  'choices' => 
    array (size=179)
      947 => string 'Abigail Barnes' (length=14)
      1163 => string 'Abigail Barnes and Helen Rees' (length=29)
      42137 => string 'Abigail Rudner' (length=14)
      1002 => string 'Adam Hergenrother' (length=17)
      1004 => string 'Adam Hergenrother and Hallie Warner' (length=35)
      41950 => string 'Ali Pasha' (length=9)
      959 => string 'Alice Scutchey' (length=14)
      38242 => string 'Alicia Fairclough' (length=17)
      40584 => string 'Aliina Rowe' (length=11)
      2566 => string 'Amanda Johnson' (length=14)
      1458 => string 'Amy McKeown' (length=11)
      907 => string 'Andrea Macarie' (length=14)

etc etc

947 => string ‘Abigail Barnes’ is the selected person in the select, but as you can see, the values are empty.

I am wanting the selected people (in this case Abigail Barnes) to be displayed only so I can do a database search with their ID’s

Why doesn’t work PDF file open by PDF.js viewer [with URL]?

I downloaded manually the PDF.js viewer, and it was working perfectly in program XAMPP, but when I uploaded to a web server, it broke down. I uploaded also the web, the build folders and the LICSENSE file several times, but I think the issue isn’t there, however in the URL.

This is the URL’s code, what I’m using:

<td><a class="hrefborder" href="/web/viewer.html?file=%2Fkotta/<?php echo "{$row["elsokotta"]}"; ?>">Open</a></td>

And this is the specific URL. I would open ‘Éneklem A Te Jóságodat – A.pdf’ from the ‘kotta’ folder inside htdocs.

http://example.com/web/viewer.html?file=%2Fkotta/%C3%89neklem%20A%20Te%20J%C3%B3s%C3%A1godat%20-%20A.pdf

Laravel illuminate/filesystem and laravel/framework coexist but did not find illuminate/filesystem in composer.json

I am updating laravel from composer but getting one error during updating it

Only one of these can be installed: illuminate/filesystem[v9.0.0-beta.1, …, 9.x-dev, v10.0.0, …, 10.x-dev, v11.0.0, …, 11.x-dev], laravel/framework[v10.0.0, …, 10.x-dev]. laravel/framework replaces illuminate/filesystem and thus cannot coexist with it

I check in composer.json file there is no illuminate/filesystem in it.Can anybody tell me how to solve this issue?

I tried to create the composer.js file again but its not solve anything.

syntax error, unexpected string content “”, expecting “-” or identifier or variable or number

In a PHP application I am trying to the users information from the table like below

session_start();

$sql = “SELECT * FROM users WHERE company_id = $_SESSION[‘companyId’]”;

$result = $connect->query($sql);

but query statement in bold throws syntax error.

syntax error, unexpected string content “”, expecting “-” or identifier or variable or number
Am I missing something?

Attached screenshot