uploading and retrieving image using angular php mysql

im working on a angular php project and im working on admin view where he will be able to add image of the project and i want to save the url in the database so i can show it in the client side how can i do that ?

this is my html code snippet for the image

<div class="row">
                    <div class="col-md-6 div">Image <span style="color:red;">* </span> </div>
                    <div class="col-md-6">
                        <input id="imageInput" type="file" class="form-control" formControlName="image_url"
                            name="image_url" accept="image/*" required="" (change)="setPhoto($event)">
                    </div>
                </div>

and this is my ts file

import { ElementRef, OnInit, ViewChild } from '@angular/core';
import { Component } from '@angular/core';
import { ApiService } from '../service/api.service';
import { Router } from '@angular/router';
import { FormArray, FormBuilder, FormControl, Validators, AbstractControl, ValidationErrors } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { countries } from '../countries_data';

import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-addprojects',
  templateUrl: './addprojects.component.html',
  styleUrls: ['./addprojects.component.css']
})

export class AddprojectsComponent implements OnInit {
  addForm: any;
  projectCategories: any[] | undefined;

  imageUrl = null;
  photo?: Blob;


  public countries: any = countries
  selectedFile: any;
  constructor(
    private formbuilder: FormBuilder,
    private router: Router,
    private projectservice: ApiService,
    private toastr: ToastrService
  ) {
    this.addForm = this.formbuilder.group({
      // project_id: ['', [Validators.required, Validators.min(1), Validators.pattern("^[0-9]+$")]],
      title: ['', [Validators.required, Validators.maxLength(255), Validators.pattern("^[a-zA-Z]+$")]],
      description: ['', [Validators.required, Validators.maxLength(255), Validators.pattern("^[a-zA-Z]+$")]],
      start_date: ['', [Validators.required]],
      end_date: ['', [Validators.required]],
      code_cat: ['', [Validators.required, Validators.min(1), Validators.pattern("^[0-9]+$")]],
      project_country: ['', [Validators.required,]],
      project_holder: ['', Validators.required],
      image_url: ['', Validators.required]

    },
      { validator: this.endDateValidator }

    )
  }
  endDateValidator(group: AbstractControl): ValidationErrors | null {
    const startDate = group.get('start_date')?.value;
    const endDate = group.get('end_date')?.value;

    if (startDate && endDate && startDate > endDate) {

      return { endDateInvalid: true };
    }
    return null;
  }

  setPhoto(event: any) {
    if (event.target.files && event.target.files.length > 0) {
      this.photo = event.target.files[0];
    }
  }
  onSubmit() {
    if (this.addForm.valid && this.photo) {

      const formData = new FormData();
      formData.append('image_url', this.photo);
      console.log(formData)

      this.projectservice.createProjects(this.addForm.value).subscribe({
        next: (data: any) => {
          this.toastr.success('Project created successfully', 'Success');
          setTimeout(() => {
            this.router.navigate(['/view']);
          }, 1500);


        },
        error: (error: any) => {
          console.log(error);
          this.toastr.error('Project ID exists already', 'Error');
        }
      });
    }
    else {
      this.toastr.error('Please Fill the form correctly ', 'Error');
    }
  }


  get id() {
    return this.addForm.get('project_id')
  }

  ngOnInit() {
    this.projectservice.getCategory().subscribe(
      (result: any) => {
        this.projectCategories = result.data;
        console.log(this.projectCategories);
      },
      error => {
        // Handle error
      }
    );


  }


}

and this is my service

 createProjects(project: FormData) {

let headers = new HttpHeaders({
  'Content-Type': 'application/json'
});
// let data = JSON.stringify(project);
// console.log(project)
console.log(project)
return this.http.post(this.baseUrl + 'addproject.php', project, { headers });

}

im just now trying to get the image in the formdata and it gives me null everytime in the console.log

enter image description here

Magento 2 update subtotal item

In Magento 2, on the checkout page where the cart items are displayed, when I modify the quantity to be higher than the available stock, only the available quantity (stock quantity) is shown. However, I notice that the subtotal calculation is incorrect as it is based on the desired quantity rather than the displayed quantity ( stock quantity) .
Furthermore, if I order another product and modify its quantity, I observe that the subtotal for the first product is displayed correctly, taking into account the displayed value (stock quantity).

I adjusted the entered quantity to the stock quantity if the entered quantity is greater than the stock quantity.

I want to give an example. I have a product with a unit price of $100 and a stock quantity of 1300. I want to order 1500 (1500 > 1300). The system displays 1300 in the quantity field (the stock quantity), but the subtotal calculation is incorrect: $150,000 (1500 * $100), whereas I want the subtotal to be $130,000 (1300 * $100) because I displayed 1300.

This is the code in the default.phtml file of the checkout module.
value=”getQty() > $qty_stock ? $qty_stock : $block->getQty(); ?>

PHP-FPM cannot change log file location

I am running a LAMP server (Almalinux) supporting different versions of php. I have used the remi repos to get the multiple php files setup.

looking at the main /etc/php-fpm.conf file, it writes errors to the standard /var/log location:

error_log = /var/log/php-fpm/error.log
  • Which is fine.

The remi setup created /etc/opt/remi/php81/php-fpm.conf which specifies the location of the error log file. I added my own path to where I want the file written:

;error_log = /var/opt/remi/php81/log/php-fpm/error.log
error_log /var/log/php81-fpm/error.log
  • now the service refuses to start, if I change it back it is fine. I have created that folder and even an empty error.log file (with the same permissions) but still it refuses to start.
php81-php-fpm.service: main process exited, code=exited, status=78/n/a
Unit php81-php-fpm.service entered failed state.

The error log message, seems irrelevant to the issue:

ERROR: [/etc/opt/remi/php81/php-fpm.conf:455] value is NULL for a ZEND_INI_PARSER_ENTRY

For now, I have reverted, but I would like to understand what is going wrong. BTW I tried disabling selinux, but that had no effect either.

have to logout the particular user should be logged out after 15 minutes of inactivity

Existing code:

function Inactivitytime(){
     console.log(1);
     let time;
     window.onload = resetTimer;
     document.onmousemove = resetTimer;
     document.onkeypress = resetTimer;

     function logout() {
         var root = document.location.origin;
         document.cookie = emp_id +'='+ empid +'; Path=/;';
         document.cookie = emp_email +'='+ emp_email +'; Path=/;';
         document.cookie = empname +'='+ emp_name +'; Path=/;';
         setCookie('emp_id','',time()-3600)
         setCookie('emp_email','',time()-3600)
         setCookie('empname','',time()-3600) 
         window.location.href = root+"/index.php";
         console.log(2);
    }

    function resetTimer() {
        clearTimeout(time);
        time = setTimeout(logout, 4000)
        console.log(3);
    }
}

Tried implementation

 document.cookie = emp_id +'='+ empid +'; Path=/;';
 document.cookie = emp_email +'='+ emp_email +'; Path=/;';
 document.cookie = empname +'='+ emp_name +'; Path=/;';
 setCookie('emp_id','',time()-3600)
 setCookie('emp_email','',time()-3600)
 setCookie('empname','',time()-3600) 

i have tried this don’t have any isue with code but the only problem is it’s not getting signed out
suggest me any changes THanks in advance!!!

How to flag multiple orders from the same customer for packaging in WooCommerce?

Sometimes Customers orders (as guest, not as logged-in users-accounts) and then shorty orders again other products in our woo commerce store.
Especially on weekends.
So we got multiple orders status processing from the same person and we would like to send it together in one package.
But with a lot orders processing (30-50) it is hard to identify orders from the same customers.

so it would be nice, if a order is processing and has the same name or email-address as another order in processing, that it is flagged with an icon or something like that.

is this possible?

we already altered the function php with some code to highlight if an order is international shipping.

Sharing Google Sheets with a Target Audience using PHP and Google Drive API

I am using PHP and Google Drive API to copy and rename an existing Spreadsheet in Google Drive. I have done this successfully and have learned to give users permissions to my copied files. I would like to share my new copied Spreadsheet with a previously created Target Audience. Is this possible and how would one achieve this.

I tried copying a Spreadsheet that already has a Target Audience and read/write permissions for various users, but the permissions did not carry across from the original to the duplicated file. I have tried to find information about this in the documentation but couldn’t find anything relating to it.

How can I add a download button to my PHP/HTML table populated from multiple drop-down menus?

First of all im new to php, i have two forms that select from the same table a project and a quarter the it is displayed in a table format, i have tried that and it works fine and the results are got, but what i want now is to download what has been selected here is a code

 <?php foreach($developersData as $developer) { ?>
   
                                <tr>
                                <td class="annualworkplan"><?php echo $row4['activities']; ?></td>
                                <td class="annualworkplan"><?php echo $row4['annualoutput']; ?></td>
                                <td class="annualworkplan"><?php echo $row4['annualbudget']; ?></td>
                                <td class="quarterlyworkplan"><?php echo $row4['q4interim']; ?></td>
                                <td class="quarterlyworkplan"><?php echo $row4['q4kpi']; ?></td>
                                <td class="quarterlyworkplan"><?php echo $row4['q4budget']; ?></td>
                                <td class="thcolor"> 
                                <div contentEditable='true' onkeypress="return (this.innerText.length <= 200)" 
                                oncopy="return false" oncut="return false" onpaste="return false"
                                class='edit' id='actualoutput4_<?php echo $row4['id']; ?>' >
                                <?php echo $row4['actualoutput4']; ?>
                                </div> 
                                </td>
                                <td class="thcolor">  
                                <div contentEditable='true' class='edit' 
                                id='actualkpi4_<?php echo $row4['id']; ?>'>
                                <?php echo $row4['actualkpi4']; ?>
                                </div> 
                                </td>
                                <td class="thcolor">   
                                <div contentEditable='true' class='edit' id='actualbudget4_<?php echo $row4['id']; ?>'>
                                <?php echo $row4['actualbudget4']; ?>
                                </div> 
                                </td>
                                <td class="quarterlyperf"><?php echo $row4['variance4']; ?></td>
                                <td class="quarterlyperf"><?php echo $row4['budgetperf4']; ?></td>
                                
                                </tr>
                                
                                <?php } ?>              '

How can I fix the ‘Invalid Email or Password’ error when logging in to my PHP website? [closed]

getting Invalid Email or Password in my localhost website

<?php

function accountLogin($userName, $userPassword){
    session_start();
    include('dbConnection.php');
    $password = md5($userPassword);

    $accountID = [];

    $query = "SELECT * FROM tbl_account WHERE `accountID` = '" . $userName . "' AND `accountActive` = '1'"; //QUERY CODE
    $sql = mysqli_query($conn, $query) or die("System Error: " . mysqli_error($conn)); //SENDING QUERY TO DATABASE

    //DOES QUERY CONTAINS ROWS?
    if(mysqli_num_rows($sql)>0){
        $row = mysqli_fetch_assoc($sql);
        extract($row);

        if($accountPassword==$password){
            $_SESSION['userID'] = $accountID;
            $_SESSION['fName'] = $accountFName;
            
            return 1;
        }
        else{
            return 0;
        }
    }
    else{
        return 0;
    }
    
}

?>

What seems to be the problem?

how do I execute r file from php [duplicate]

I’ve been trying to run an R file from PHP using exec().
I have searched a lot on the internet on how am I able to integrate both R and PHP.
So far I have this code in my PHP file

<?php
$command = ""C:\Program Files\R\R-4.3.0\bin\Rscript.exe" C:\xampp\htdocs\CKmeans1D.R";
exec($command, $output);

print_r($output);

and on my R file which is the CKmeans1D.R I have this code

library(Ckmeans.1d.dp)
x <- c(5,5,4,5,4.14,3.75)
result <- Ckmeans.1d.dp::Ckmeans.1d.dp(x, 3)
library(rjson)
cat(toJSON(result))

however, my PHP does not receive any output after I load it.

I tried running “C:Program FilesRR-4.3.0binRscript.exe” C:xampphtdocsCKmeans1D.R on my CMD on Windows 10 and it returns an output.

what am I missing?

how make price of an item go up on weekends with laravel

I want to make the price of an item go up on weekends or on Saturdays and Sundays, but I’m stacked and don’t know how to make it with Laravel. can someone help me please

please give an example or a hint how do I make the price of an item go up when selecting Saturday and Sunday in Laravel

I already know how to get the day of the date…

PHP takes only the first value in a loop

I have a problem that when I clicked the button which is a list, it only displays the first value which is ‘The Grass is Always Greener’ even if I clicked different book title.

<form method="POST" action="test.php">
                            <?php
                                echo '<ul class="grid-container">';
                                while ($row = mysqli_fetch_assoc($result)) {
                            ?>
                                <button><li>
                                    <?php echo '<img src="img/'.$row['cover'].'">'?>
                                    <p><?php echo $row['title']?></p>
                                    <p><?php echo $row['author']?></p>
                                    <input type="hidden" name="titleOfBook" value="<?php echo $row['title']?>"> 
                                </li></button>

                            <?php
                                }
                                echo '</ul>';
                            ?>
                        </form>

This is my test.php, just only for displaying the value

<?php
    require 'database/connect.php';

    $clicked = $_POST['titleOfBook'];

    echo '<h1>' . $clicked . '</h1>';
?>

I’ve tried several steps like changing the position of input througout the loop but it really doesn’t work.

This is the UI,
enter image description here

and this is the produced HTML when I clicked a book:
enter image description here

Laravel 10 Sail with Nuxt 3 and Vite: Browser can’t connect to 24678

I have a monorepo with Laravel 10 and Nuxt 3 being installed to a subdirectory. I don’t want to run the nuxt dev server from my host. Instead I want to run it using Laravel Sail, because Sail already has all dependencies (npm) installed.

The directory structure is:

enter image description here

enter image description here

I also wrote myself some small Artisan commands to make life a bit easier:

<?php

namespace AppConsoleCommands;

use IlluminateConsoleCommand;
use IlluminateSupportFacadesProcess;

class InstallFrontend extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'install:frontend';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Install frontend dependencies';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $result = Process::forever()->run('npm --prefix ./frontend install', function (string $type, string $output) {
            $this->info($output);
        });
    }
}

and

<?php

namespace AppConsoleCommands;

use IlluminateConsoleCommand;
use IlluminateSupportFacadesProcess;
use IlluminateProcessPipe;

class runFrontend extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'run:frontend';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Runs the frontend in dev mode.';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        Process::path(base_path() . '/frontend')->forever()->run('npm run dev -- --host 0.0.0.0', function (string $type, string $output) {
            $this->info($output);
        });
    }
}

Both commands just run totally fine.

The problem now:
I can’t connect to the nuxt dev server through websockets. As far as I can see Nuxt 3 uses Vite for the dev server. But the browser always refuses to connect for HMR:
enter image description here

I already opened the needed ports in my docker-compose.yml:

version: '3'
services:
    laravel.test:
        build:
            context: ./docker/8.2
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-8.2/app
        ports:
            - '${APP_PORT:-80}:80'
            - '${FRONTEND_PORT:-3000}:3000'
            - '${VITE_SERVER_PORT:-5173}:5173'
            - 24678:24678
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
            - redis

And added this to the nuxt.config.ts:

// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
  modules: ['@nuxtjs/tailwindcss', '@pinia/nuxt', 'nuxt-icon'],
  runtimeConfig: {
    public: {
      baseURL: 'http://localhost'
    }
  },
  vite: {
    server: {
      hmr: {
        protocol: "ws",
        host: "localhost"
      }
    }
  }
})

But nothing helps. The Browser can’t connect and I don’t know why.

Also there is a very strange behaviour I mentioned accidentally:
I had this in my artisan command before:

        Process::path(base_path() . '/frontend')->forever()->run('npm run dev --host 0.0.0.0', function (string $type, string $output) {
            $this->info($output);
        });

Instead of:

        Process::path(base_path() . '/frontend')->forever()->run('npm run dev -- -o --host 0.0.0.0', function (string $type, string $output) {
            $this->info($output);
        });

Which leads to a new subdirectory being created in the /frontend directory with it’s own .nuxt folder:
enter image description here

The very strange thing is, that I was able to reach the dev server with working HMR, but it is not my actual app, because the dev server served the newly created subdirectory. So the browser just showed some default Nuxt 3 app:
enter image description here

So the problem does not seem to be related to any connection errors itself. Vite just seems to be unable to serve the already existing app from the .nuxt folder?

Can anyone help me getting this finally working? 🙂

Thanks in advance!

Insert function inputting data twice MYSQL(different from other answered questions similar to this) [duplicate]

I have an issue with insert function inputting data twice. I have been looking around for possible solutions but I can’t seem to fix it. Big part is probably because I am new to using jquery and modals. Please do not criticize me not using parameterized queries. This is code:

This would be the code for my index page:

<div class="modal fade" id="uni_modal" role='dialog' data-bs-backdrop="static" data-bs-keyboard="true">
        <div class="modal-dialog modal-md modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
            <h5 class="modal-title"></h5>
        </div>
        <div class="modal-body">
        </div>
        <div class="modal-footer py-1">
            <button type="button" class="btn btn-sm rounded-0 btn-primary" id='submit' onclick="$('#uni_modal form').submit()">Save</button>
            <button type="button" class="btn btn-sm rounded-0 btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
        </div>
        </div>
    </div>


Script: for my main page:

<script>
    $(function(){
        // Components Functions
        $('.manage_percentage').click(function(){
            uni_modal('Manage Subject's Components Percentage',"editSubjectPercentage.php?id="+$(this).attr('data-id'))
        })
       
    })
</script>

editSubjectPercentage.php:

<div class="container-fluid">
<form action="" id="percentage-form">
        <input type="hidden" name="id" value="<?php echo isset($_GET['id']) ? $_GET['id'] : '' ?>">
        <table class="table table-striped table-hover">
            <colgroup>
                <col width="75%">
                <col width="25%">
            </colgroup>
            <thead>
                <tr>
                    <th class="py-0 px-1 text-center">Component</th>
                    <th class="py-0 px-1 text-center">Percentage (%)</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $component = $con->query("SELECT * FROM `tblcomponent` order by Id asc");
                $total = 0;
                while($row = mysqli_fetch_array($component)):
                    $total += isset($data[$row['Id']]) ? $data[$row['Id']] : 0;
                ?>
                <tr>
                    <td class="py-0 px-1"><input type="hidden" name="component_id[]" value='<?php echo $row['Id'] ?>'><?php echo $row['componentTitle'] ?></td>
                    <td class="py-0 px-1">
                        <input type="number" step="any" class="form-control form-control-sm rounded-0 w-100 text-end" name="percentage[]" value="<?php echo (isset($data[$row['Id']])) ? $data[$row['Id']] : 0 ?>" required>
                    </td>
                </tr>
                <?php endwhile; ?>
                <tfoot>
                    <tr>
                        <th class="py-0 px-1 text-center">Total</th>
                        <th class="py-0 px-1 text-center text-end" id="total"><?php echo $total ?>%</th>
                    </tr>
                </tfoot>
            </tbody>
        </table>
    </form>
</div>

<script>
    $(function(){
        $('input[name="percentage[]"]').on('input',function(){
            var total = 0;
            $('input[name="percentage[]"]').each(function(){
                var _perc = $.isNumeric($(this).val()) === true ? $(this).val() : 0;
                total += parseFloat(_perc)
            })
            $('#total').text(total+"%")
        })
        $('#percentage-form').submit(function(e){
            e.preventDefault();
            $('.pop_msg').remove()
            var _this = $(this)
            var total = $('#total').text()
                total = total.replace(/%/gi,'')
                console.log(total)
            if(parseFloat(total) !== 100)
            {
                alert("Total Percentage must be 100%");
                return false;
            }
            var _el = $('<div>')
                _el.addClass('pop_msg')
            $('#uni_modal button').attr('disabled',true)
            $('#uni_modal button[type="submit"]').text('submitting form...')
            $.ajax({
                url:'./Actions.php?a=save_percentage',
                method:'POST',
                data:$(this).serialize(),
                dataType:'JSON',
                error:err=>{
                    console.log(err)
                    _el.addClass('alert alert-danger')
                    _el.text("An error occurred.")
                    _this.prepend(_el)
                    _el.show('slow')
                     $('#uni_modal button').attr('disabled',false)
                     $('#uni_modal button[type="submit"]').text('Save')
                },
                success:function(resp){
                        _el.addClass('alert alert-success')
                        $('#uni_modal').on('hide.bs.modal',function(){
                            location.reload()
                        })
                    _el.text(resp.msg)

                    _el.hide()
                    _this.prepend(_el)
                    _el.show('slow')
                     $('#uni_modal button').attr('disabled',false)
                     $('#uni_modal button[type="submit"]').text('Save')
                }
            })
        })
    })
</script>

This is the code of “./Actions.php?a=save_percentage”

<?php 

Class Actions extends mysqli{
    private $sql;
    function __construct(){
        $this->sql = new mysqli("localhost", "root", "", "resultgrading");
    }
    function save_percentage(){
        extract($_POST);
        $data = "";
        foreach($component_id as $k => $v){
            if(!empty($data)) $data .= ", ";
            $data .= "('$id','{$v}','{$percentage[$k]}')";
        }
        $this->sql->query("DELETE FROM `component_subject_percentage` where `subject_id` = '{$id}'");
        if($this->sql->query("INSERT INTO `component_subject_percentage` (`subject_id`,`component_id`,`percentage`)VALUES ('29','5','30'), ('29','6','20'), ('29','8','50')") === true){
            $resp['status'] ='success';
            $resp['msg'] = $data;
        }else{
            $resp['status'] ='failed';
            $resp['msg'] = "Data fails to save. Error: ". $this->sql->lastErrorMsg();
            $resp['sql'] = $sql;
        }
        return json_encode($resp);
    }
}
$a = isset($_GET['a']) ?$_GET['a'] : '';
$action = new Actions();
switch($a){

    case 'save_percentage':
        echo $action->save_percentage();
    break;
    default:
    // default action here
    break;
}