php fatal erro mysqli_connect() [duplicate]

<?php
    $servername = "localhost";
    $username = "root";
    $password = "123456";
    $dbname = "buke";
    
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    $sql ="INSERT INTO xuesheng (xingming,nianling,xingbie) 
    VALUES ('小明','18','男')";
    
    if (mysqli_query($conn, $sql)) {
        echo "新记录插入成功";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }
    
    mysqli_close($conn);
?>

when i run it in visule studio 2019 ,I met :

Fatal error: Uncaught Error: Call to undefined function mysqli_connect() in D:codenodejshtdocsaddStudent.php:8
Stack trace:
#0 {main}
  thrown in D:codenodejshtdocsaddStudent.php on line 8

I have installed
php debug
xdebug
php intelephense
php intellisense

and edit the php.ini:

extension="D:phpstudy_proExtensionsphpphp7.3.4ntsextphp_mysqli.dll"
extension_dir="D:phpstudy_proExtensionsphpphp7.3.4ntsext"

Move 50.000 folders with rename

I have the challenge of sorting about 50,000 folders with images in them.

Currently, it is like this. There is a folder “Uploads”. There are 50000 subfolders in it.

Now I want them to be sorted by year/month.
So
uploads/2022/03
uploads/2022/02
uploads/2022/01
etc

Creating the folders for month/year with mkdir and rename for moving the folders is known to me.

My question is rather if rename is the best solution here.

And maybe does someone also have an idea how long such a process takes?

As far as I understand, rename changes the path of the folder. Is the folder on the hard disk of the server “really moved” or is that “only” meta information and rename is done in a few milliseconds?

Remove duplicate in array and display quantity of each duplicate – Smarty

I have an array full of Strings. I am trying to remove the duplicates in the array, and display how much value there were. I don’t know if i’m clear.

Here is my code :

{loop type="product" name="mot-cle"}
    {assign var="fooVar" value="{$POSTSCRIPTUM}"}
    {assign var="parts" value=","|explode:$fooVar}
    
    {foreach from=$parts key=k item=i}
    <ul>
        <li>{$i}</li>
    </ul>
    {/foreach}
{/loop}

This code display this :

test
test2.
test3
test3
test3.
test
test3
test.
test2
test3.
test2
test
test3.
test3

I wish to display this :

test (4)
test2 (3)
test3 (7)

PS : I am new with smarty.
Any help ?

How to make architecture of querying SQL with arbitrary filters [closed]

Let’s say I have a table for showing data in the frontend, and the user can select all kinds of filters based on the columns. For text columns they can have certain text filters such as ‘starts with’, ‘contains’, ‘equals’, ‘is not equal to’, etc.

For columns with integers it would be stuff like ‘equals’, ‘greater than’, ‘less than’, ‘is not empty’, ‘is empty’.

For percentage columns the same etc etc.

How would one structure this, in broad terms, in the backend to recognize all these filters and place them in a query at the right place. So which filters would be a WHERE, which filters HAVING? Which filters go inside a join, which filters go outside a join or subquery?

And if certain columns show an average, how would you structure this so that certain filters get applied before or after an AVG function? If I want to see only AVG rows with a value above 20, OR I want to see AVG rows that are calculated from values above 20, both should be possible. Same with COUNT or SUM.

I’m struggling to come up with a coherent system that doesn’t become incredibly confusing and complex. How do other companies do this? Is there maybe a framework that has all this built in? I’m just using Symfony and MySQL.

Show S3 SSE-C Encrypted Image using Presigned URL in the browser

Without any encryption, even for a file that resides in a bucket with no public access, I can create a presigned URL by modifying response-content-type header for an image with an expiry time and it would show the image in the browser. This is very helpful when I need to display the image in the browser using the src attribute of img HTML tag.

However, When I encrypt an image using SSE-C in S3, is there any way to show the image in the browser using presigned URL? I’ve some images which are encrypted using SSE-C in S3.
However, in some cases they might required to be shown in the browser.

The documentation states this
enter image description here aws docs link

Is there any way? Thank you.

how to use Swup transition library with php for page transition?

I have 5 php pages the last page is the one that actually submit the all the 5page data to database. and each page has a form and submit and open the other page
so i want to add page transition while each page form get submit and i was working with swup, without the php it’s works . but adding the php the transition doesn’t work.

Error page with Laravel policy and authorization with User Model

This is my UserPolicy:

<?php
namespace AppPolicies;
use AppModelsUser;
use IlluminateAuthAccessHandlesAuthorization;
class UserPolicy
{
    use HandlesAuthorization;
    public function view(User $user, User $model)
    {
        return $user->id === $model->id;
    }
}

This is the AuthServiceProvider:

<?php
namespace AppProviders;
use AppModelsUser;
use AppPoliciesUserPolicy;
use IlluminateFoundationSupportProvidersAuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array<class-string, class-string>
     */
    protected $policies = [
        // 'AppModelsModel' => 'AppPoliciesModelPolicy',
        User::class => UserPolicy::class
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
    }
}

And finally the UserController

<?php

namespace AppHttpControllers;

use AppModelsUser;
use IlluminateHttpRequest;

class UserController extends Controller
{
    public function show(User $user)
    {
        $this->authorize('view', $user);
        return view('user.show', [
            'user' => $user,
        ]);
    }
}

I am trying to use $this->authorize('view', $user); to authorize but I am getting the “Something went wrong in Ignition!” error page.

I have already spent an entire day trying to figure out what I have done wrong. Can anyone please point out what’s wrong?

Why do I get only one row with fetchAll? [closed]

I have this statement. It should return me more results, but instead returns me only one?

    public function getCartProducts($customerId): bool|CartModel
    {
        $statement = $this->connection->prepare("SELECT ROUND(SUM(product.price * cartitem.quantity)) as totalprice, product.productid, product.imagepath, product.name, product.price, cartitem.quantity FROM cart_item as cartitem LEFT JOIN product as product ON cartitem.product_id = product.productid LEFT JOIN cart AS cart ON cart.cart_id=cartitem.cart_id WHERE customer_id=:customerId AND is_ordered = 0;");
        $statement->execute(['customerId' => $customerId]);
        $rows = $statement->fetchAll();

new user failed to login with username and password

I try to login with a new created user. But when I try to login it throw’s the error message.

So This is the login:


public function login()
  {
    // Check for POST
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

      echo ('hello');
      // Process form
      // Sanitize POST data
      $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

      // Init data
      $data = [
        'email' => trim($_POST['email']),
        'password' => trim($_POST['password']),
        'email_err' => '',
        'password_err' => '',
      ];

      // Validate Email
      if (empty($data['email'])) {
        $data['email_err'] = 'Pleae enter email';
      }

      // Validate Password
      if (empty($data['password'])) {

        $data['password_err'] = 'Please enter password';
      }

      // Check for user/email
      if ($this->userModel->findUserByEmail($data['email'])) {

        // User found
      } else {
        // User not found
        $data['email_err'] = 'No user found';
      }

      // Make sure errors are empty
      if (empty($data['email_err']) && empty($data['password_err'])) {
        // Validated
        // Check and set logged in user
        $loggedInUser = $this->userModel->login($data['email'], $data['password']);
       
        if ($loggedInUser) {

          echo $data['password'];
          echo $data['email'];



          // Create Session
          $this->createUserSession($loggedInUser);
        } else {
          $data['password_err'] = 'Password incorrect';

          $this->view('users/login', $data);
        }
      } else {
        // Load view with errors
        $this->view('users/login', $data);
      }
    } else {
      // Init data
      $data = [
        'email' => '',
        'password' => '',
        'email_err' => '',
        'password_err' => '',
      ];

      // Load view
      $this->view('users/login', $data);
    }
  }

and so it doesn’t reach the two echo messages.

But I can’t figure out why I can’t login.

and the new created user is appearing in the database.

anyone know how to fix this i am new on coding ?Warning: Trying to access array offset on value of type null [duplicate]

//i got an error in part of $_SESSION cannot login as user and teacher even their usertype is correct in database but when manually input in database it was successfully login

    //if($data===false)
   // {
      //  die("connection error");
    //}
    //if($_SERVER["REQUEST_METHOD"]=="POST")
    //{   
        //$username=$_POST["username"];
        //$password=$_POST["password"];
       // $usert="user";
     //   $sql="select * from users where username = '".$username."' AND password = '".$password."'";
       // $result =mysqli_query($data,$sql);
       // $row=mysqli_fetch_array($result);
         //if($row["usertype"]=="admin")
       // {
           // $_SESSION["username"]=$username;
         //   header("location:admin.php");
       // }
       // else if($row["usertype"]=="user")
       // {
           // $_SESSION["username"]=$username;
         //   header("location:studenthome.php");
       // }
        // else if($row["usertype"]=="teacher")
       // {
           // $_SESSION["username"]=$username;
         //   header("location:teacherhome.php");
       // }
        
       // else{
       //     echo "username and password incorrect";
     //   }
    //}
   
    
  

Consolidating repetitive queries in php

Currently, I have an array with elements and four queries that are similar just using different elements from the array. Roughly the situation seems like this (simplified)

$myArray = array('element1', 'element2', 'element3', 'element4');
foreach ( $myArray as $tors_array ) {
    $element[] = $tors_array;
    
}

$query = "SELECT en as country, $element[0] as value 
                FROM administrative
                WHERE year=2021 
                AND $element[0] IS NOT NULL"; 
$result = $DB->query($query);
$query1 = $DB->fetch_object($result);

$query = "SELECT en as country, $element[1] as value 
                FROM administrative
                WHERE year=2021
                AND $element[1] IS NOT NULL";
$result = $DB->query($query);
$query2 = $DB->fetch_object($result);


$query = "SELECT en as country, $element[2] as value 
                FROM administrative 
                WHERE year=2021
                AND $element[2] IS NOT NULL";
$result = $DB->query($query);
$query3 = $DB->fetch_object($result);

$query = "SELECT en as country, $element[3] as value 
                FROM administrative 
                WHERE year=2021
                AND $element[3] IS NOT NULL";
$result = $DB->query($query);
$query4 = $DB->fetch_object($result);

Is there another way how this be done instead of repeating the same query only to replace the element?

How to check availability of Property between check in and check out dates using PHP

$check_in = '2022-03-08';
$check_out = '2022-03-11';
$property_id = 6;

I have three parameters: $check_in, $check_out and $property_id Now I want to check availability of this property before booking.

Since my $check_in date is 2022-03-08 and $check_out date is 2022-03-11 then property id 6 should not be entry second time.

Again, if the $check_out date is ‘2022-03-10’ then the entry is not possible.

Booking Table

Property_Id Booking_Id Booking_Date Check_in_Date Check_out_Date
6 02 2022-03-25 2022-03-10 2022-03-15
7 03 2022-03-25 2022-03-20 2022-03-25
8 04 2022-03-25 2022-04-15 2022-04-20

Please help me to write a SQL query

How implement Php’s openssl_encrypt method in c#?

as in the title, I need to implement in my C# code the equivalent of php’s openssl_encrypt method, because I need to call a service on a php page, but we work with c#.
The php code is this:

    $textToEncrypt = "test";                                        
  
    $algo = "AES256";
    $iv   = openssl_random_pseudo_bytes(openssl_cipher_iv_length($algo));
    $key  = "1234567890987654"; //Not this key, but just same length
    $parametri_enc  = openssl_encrypt($textToEncrypt , $algo, $key, 0, $iv);
    $iv   = bin2hex($iv); 

I tried many thing, actually my code is:

    string textToEncrypt = "test";
    string secretCode = "1234567890987654"

    // Create sha256 hash
    SHA256 mySHA256 = SHA256Managed.Create();
    byte[] key = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(secretCode));

    // Create secret IV
    byte[] iv = new byte[16];
    RandomNumberGenerator generator = RandomNumberGenerator.Create();
    generator.GetBytes(iv);

    string encryptedText = EncryptString(idcorso, key, iv);

    // And I try to port also the bin2hex method
    var sb = new StringBuilder();
    foreach (byte b in iv)
    {
       sb.AppendFormat("{0:x2}", b);
    }
    var tokenBytesHex = sb.ToString();

And the method EncryptString is

public static string EncryptString(string plainText, byte[] key, byte[] iv)
{
   //Instantiate a new Aes object to perform string symmetric encryption
   Aes encryptor = Aes.Create();

   encryptor.Mode = CipherMode.CBC;

   // Set key and IV
   byte[] aesKey = new byte[32];
   Array.Copy(key, 0, aesKey, 0, 32);
   encryptor.Key = aesKey;
   encryptor.IV = iv;

   // Instantiate a new MemoryStream object to contain the encrypted bytes
   MemoryStream memoryStream = new MemoryStream();

   // Instantiate a new encryptor from our Aes object
   ICryptoTransform aesEncryptor = encryptor.CreateEncryptor();

   // Instantiate a new CryptoStream object to process the data and write it to the 
   // memory stream
   CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);

   // Convert the plainText string into a byte array
   byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);

   // Encrypt the input plaintext string
   cryptoStream.Write(plainBytes, 0, plainBytes.Length);

   // Complete the encryption process
   cryptoStream.FlushFinalBlock();

   // Convert the encrypted data from a MemoryStream to a byte array
   byte[] cipherBytes = memoryStream.ToArray();

   // Close both the MemoryStream and the CryptoStream
   memoryStream.Close();
   cryptoStream.Close();

   // Convert the encrypted byte array to a base64 encoded string
   string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);

   // Return the encrypted data as a string
   return cipherText;
}

I tried many variation about this porting (that I’ve found on internet), but without result. If I use a correct encrypted string from my code, I can call the service, so it is working. I need only to encrypt correctly that string, but until now, I’ve failed

Trying to filter by price

I have course search everything works. But i don’t know how to make filter by price? When i filter by price, it’s filter but it’s filters all courses. But it must filter last filtered courses not all courses. and i don’t know how to do it can anyone please help me with this?

 $courses = Course::when($r->mainCat, function ($query) use ($mainCat) {
            $courseIdsArray = Direction::whereIn('course_category_id', $mainCat)->pluck('course_id')->toArray();
            return $query->whereIn('id', $courseIdsArray);
        })->when($r->level, function ($query, $level) {
            return $query->where('level', 'like', "%{$level}%");
        })->when($categories && count($categories) > 0, function ($query) use ($categories) {
            return $query->whereIn('course_category_id', $categories);
        })


->when($r->price && in_array($r->price, ['more-expensive', 'less-expensive']), function ($query) use ($r) {
            return $query->orderBy('price', $r->price == 'less-expensive' ? 'asc' : 'desc');
        })


->paginate(18)->appends($r->query());

if someone will filter courses by categories and after that he will filter by courses by price it must filter current categories courses by price and now it’s filtering all courses by price.