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.

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.

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.

How to create a multiple number guessing game with Javascript/PHP/any progamming language? [closed]

I want to create and understand how to create a multiple number guessing game like this: Number Guessing Game Example

I want to understand the algorithm of this program. Like how this program randomly generate a multiple number. And then, how do I know the random number that will be generated from this game. Like, how can I know what number will come out.

How to get Mailgun response With laravel Mail

How i can get the response from mailgun using Laravel mail.
Here is my code.

// In User Model.
$mail = Mail::send([], [], function ($message) use ($parsed_template) {
          $message
            ->to('[email protected]')
            ->subject('Test')
            ->setBody($parsed_template, 'text/html')
            ->addPart('Hello, welcome to Laravel!', 'text/plain');

     }); 

I can get the response in the the Listner using the Mailgun EVENT.

protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        'IlluminateMailEventsMessageSent' => [
            'AppListenersMailGunMailListner',
        ],
    ];

//   'AppListenersMailGunMailListner',

public function handle(MessageSent $event)
    {
        dd($event->message->getId());
    }

I can get the response in the listener, But How I can access it in the User model.

Thanks

typo3 – search bar and radio button filter doesn’t work together

I’m a new user a typo3 and I created an extension for searching shops and to show them in a map, my search system in work with a radio button filter and a search bar.

My issue is my radio buttons and my search bar are working only alone, for example when I write something and I didn’t click on a filter, or when I click on a filter and I didn’t write anything.

when I use them together they don’t work, I don’t have results, I don’t know why

there is some code :

controller :

    public function listAction()
    {
        $get = GeneralUtility::_GET();
        $results = $this->to32wContentRepository->sortByTypeTitle(
            $get['tx_import_search']['redirect']['formMap'] ?? null,
            $get['tx_import_search']['redirect']['search'] ?? null
        );

        $this->view->assign('formMap', $get['tx_import_search']['redirect']['formMap']);
        $this->view->assign('search', $get['tx_import_search']['redirect']['search']);
        $this->view->assign('results', $results);
    }

repository :

    public function sortByTypeTitle($type, $title)
    {
        $query = $this->createQuery();
        $query->getQuerySettings()->setRespectStoragePage(FALSE);
        $query->setOrderings([
            'title' => QueryInterface::ORDER_ASCENDING
        ]);

        $mission = new To32wContent();

        if ($type != NULL && $title != NULL) {
            $mission->setDisplayType($type);
            $oR = $query->logicalOr($query->like('title', '%'.$mission->getDisplayType(). '%'), $query->like('title', '%' . $title. '%'));
            $query->matching($query->logicalAnd($oR, $query->like('structure_cp', '%'.$title.'%')));
        } else if ($type != NULL && $title == NULL) {
            $mission->setDisplayType($type);
            $query->matching($query->like('title', '%'.$mission->getDisplayType(). '%'));
        } else if ($title != NULL && $type == NULL) {
            $query->matching($query->logicalOr($query->like('structure_cp', '%'.$title.'%'), $query->like('title', '%' . $title. '%')));
        }
        return $query->execute();
    }

someone have an idea to how can I solve my issue please?

Detele from DB with button [closed]

I want to delete info by click a button. So from select menu when i chose number from 1- 20 and push button NEXT is shows me “all the orders in that table from DB” When I push the button Finish in theory should delete all orders on the table i choose in DB. When i push the buutton it give me sql error.PLS help.

<?php
    require_once("connect.php");
    echo '<pre>'; print_r($_POST); echo '</pre>';
    
    if (isset($_POST['buton']))
    {   
        $tablenumber=$_POST['number'];
        $sql="SELECT orders.code,menu.name,orders.count,menu.price, orders.count*menu.price as Total 
        FROM orders,menu WHERE table_number=$tablenumber and orders.code=menu.code";    
        $quer=mysqli_query($conn,$sql)or die ('error sql');
        $num=mysqli_num_rows($quer);

        $sql2="SELECT  SUM(orders.count*menu.price) as TotalPrice 
        FROM orders,menu WHERE table_number=$tablenumber and orders.code=menu.code";    
        $quer2=mysqli_query($conn,$sql2)or die ('error sql2');      
    }
        if (isset($_POST['Finish']))    
        {   
            $tablenumber=$_POST['number'];
    
        $sql3=" DELETE FROM orders WHERE table_number=$tablenumber";
        $quer3=mysqli_query($conn,$sql3)or die ('error 1sql');
        }
    
?>
<html>
<form action="login.php" method="post">
<span style="display:flex; justify-content:flex-end; width:100%; padding:0;">
    <input type="submit" value="Exit"/>
</form>
</span>
        <style>
            body {background-color: #87CEEB;}
        </style>
    <head>
        <title>Factura</title>
        <!---<meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="dff.css"/>  !--->
    </head>
    <body>  
        <form id="frmFactura" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
                
           <div id="cabeceraFactura">
                <br>
                <SELECT NAME="number" size="1">
                    <option value="---">---</option>
                    <?php
                        for($i=1;$i<=20;$i++)
                        { echo "<option value=".$i.">".$i."</option>";}
                    ?>
                </SELECT>               
                <input type='submit' name='buton' value="NEXT"/>    
            </div>
            <br>
            <table id ="detalle" border="2" width="3" cellspacing="2" cellpadding="1">
                <thead>
                    <tr>
                     <th>Name</th>
                        <th>Count</th>
                        <th>Unit price</th>
                        <th>Total</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                
                    if(isset($_POST['buton']))
                    {    while ($resul=mysqli_fetch_array($quer) )  
                        {   echo '
                    <tr>
                        <td><input class="descrip" type="text" name="naimenovanie" value="'.$resul["name"].'" disabled=""/></td>
                        <td><input class="cant" type="text" name="kolichestvo"  value="'.$resul["count"].'" disabled=""/></td>
                        <td><input class="vunit"type="text"  name="cena" value="'.$resul["price"].'" disabled=""/></td>
                        <td><input class="totPro" type="text"  name="obstho" value="'.$resul["Total"].'" disabled=""/></td>     
                    </tr>
                        ';
                        }
                    }       
                ?>
                </tbody>
            </table> 
            <br>
            <div class="Resultados">
                <table border="2" width="3" cellspacing="2" cellpadding="1">                  
                    <tr>
                        <td><label id="lbl">TotalPrice</label></td>
                        <?php
                            if(isset($_POST['buton'])) $resul2=mysqli_fetch_array($quer2);
                        ?>
                        <td><input class="totPro" type ="text" value="<?php if(isset($_POST['buton'])) 
                         echo $resul2['TotalPrice'];?>"  disabled=""/> </td>
                     
                    </tr>   
                </table>
                <br>
                <button onclick="window.print()" width="200">Print </button>    
                    <input type="submit"  name= "Finish" value = "Finish">
            </div>  
        </form>                                         
    </body>
</html>

How to delete the entire row in the database from html table instead of deleting entire table in the database

I have added delete button to the html table on each row and when clicked on delete button the entire row should be deleted but instead whole table in the database is being deleted.

here is my code for admin.php

    <div class="container mt-3 ml-3">
<table class="table">
    <thead>
    <tr>
        <th>S.No</th>
        <th>Name</th>
        <th>Email</th>
        <th>Rating</th>
        <th>Review</th>
        <th>Image</th>
        <th>Suggestion</th>
        <th>NPS</th>
        <th>Delete</th>
    </tr>
    </thead>
    <tbody class="table-warning">

<?php
include 'database_conn.php';      // makes db connection

$sql = "SELECT feedbackID, name, email, rating, review, image, suggestion, nps
        FROM feedback 
        ORDER BY feedbackID Desc";
$queryResult = $dbConn->query($sql);

// Check for and handle query failure
if($queryResult === false) {
    echo "<p>Query failed: ".$dbConn->error."</p>n";
    exit;
}
// Otherwise fetch all the rows returned by the query one by one
else {
    if ($queryResult->num_rows > 0) {
        while ($rowObj = $queryResult->fetch_object()) {
            echo "<tr>
                  <td>{$rowObj->feedbackID}</td>
                  <td>{$rowObj->name}</td>
                  <td>{$rowObj->email}</td>
                  <td>{$rowObj->rating}</td>
                  <td>{$rowObj->review}</td>
                  <td>{$rowObj->image}</td>
                  <td>{$rowObj->suggestion}</td>
                  <td>{$rowObj->nps}</td>
                  <td><a id='delete' href=delete.php?id={$rowObj->feedbackID}>Delete</a></td>
                  

              ";
        }

    }
}
?>

</tr>
    </tbody>
</table>
</div>

And here my code for delete.php. I think there is something wrong in the sql query I made.

    <?php
include 'database_conn.php';      // makes db connection


$sql = "DELETE FROM feedback WHERE feedbackID=feedbackID";

if ($dbConn->query($sql) === TRUE) {
    echo "Record deleted successfully. Please go to Customer Feedback Page by clicking"; echo "<a href='http://unn-w18031735.newnumyspace.co.uk/feedback/admin.php'> here</a>";
} else {
    echo "Error deleting record: " . $dbConn->error;
}

$dbConn->close();
?>

please need to fix this i cant add in my database [duplicate]

Notice: Undefined variable: title in C:xampphtdocssampleappadd_record.php on line 19

Notice: Undefined variable: task in C:xampphtdocssampleappadd_record.php on line 19
An error has been occured!PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘title’ cannot be null in C:xampphtdocssampleappadd_record.php:20 Stack trace: #0 C:xampphtdocssampleappadd_record.php(20): PDOStatement->execute(Array) #1 {main

This is my code