Used fgetcsv() for uploading CSV file but it show empty array

I’m working on a codeIgniter3 project where I need to upload CSV file into the database and I used custom made library for perform this task but it is not working and showing empty array!

here are the library that I used “Csvimport.php“:

  <?php defined('BASEPATH') or exit('No direct script access allowed');

  class Csvimport {

    var $fields;/** columns names retrieved after parsing */
    var $separator = ';';/** separator used to explode each line */
    var $enclosure = '"';/** enclosure used to decorate each field */
    var $max_row_size = 120400;/** maximum row size to be used for decoding */

    function parse_file($p_Filepath) {

      $file = fopen($p_Filepath, 'r');

      $this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure);



      $keys_values = explode(',', $this->fields[0]);

      $content = array();
      $keys = $this->escape_string($keys_values);

      $i = 1;
      while (($row = fgetcsv($file, 0, $this->separator, $this->enclosure)) != false) {
        
        if ($row != null) { // skip empty lines
          $values = explode(',', $row[0]);
          if (count($keys) == count($values)) {
            $arr = array();
            $new_values = array();
            $new_values = $this->escape_string($values);
            for ($j = 0; $j < count($keys); $j++) {
              if ($keys[$j] != "") {
                $arr[$keys[$j]] = $new_values[$j];
              }
            }

            $content[$i] = $arr;
            $i++;
          }
        }
      }
      fclose($file);
      return $content;
    }

    function escape_string($data) {
      $result = array();
      foreach ($data as $row) {
        $result[] = str_replace('"', '', $row);
      }
      return $result;
    }

  }
  ?>

Here is the “Controller” code that I used to upload the CSV file:

$this->load->library('csvimport');
$file_path = base_url()."upload/test.csv";
$csv_data = $this->csvimport->parse_file($file_path);
echo '<pre>';
print_r($csv_data);
echo '</pre>';

When I executed code it show empty array() as result!

Please help me i’m stuck with this!! 🙁

In CSV file I’ve following fields:

grade
name
address
city
phone
email
type
created

Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

I am new to php .I have checked values so many time, they are same in database too .
I am getting this error:
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:xampphtdocssmscreateAboutTest.php:26 Stack trace: #0 C:xampphtdocssmscreateAboutTest.php(26): PDOStatement->execute() #1 {main} thrown in C:xampphtdocssmscreateAboutTest.php on line 26
I don’t know what’s wrong with my code 🙁 . thankyou for your help in advance:

$pdo = new PDO('mysql:host=localhost;port=3306;dbname=testconductingportal', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$t_id = $_POST['t_id'];
$t_name= $_POST['t_name'];
$ins_name = $_POST['ins_name'];
$t_date = $_POST['t_date'];
$t_time = $_POST['t_time'];
$t_duration= $_POST['t_duration'];
$t_fee = $_POST['t_fee'];
$t_savedate = $_POST['t_savedate'];
$t_closing_date  = $_POST['t_closing_date'];
$t_description = $_POST['t_description'];
$statement= $pdo->prepare("INSERT INTO about_test (t_id, t_name, ins_name, t_date, t_time, t_duration, t_fee, t_savedate, t_closing_date, t_description)
VALUES(:t_id, :t_name, :ins_name, :t_date, :t_time, :t_duration, :t_fee, :t_savedate, :t_closing_date', :t_description')");
$statement->bindvalue(':t_id', $t_id);
$statement->bindvalue(':t_name', $t_name);
$statement->bindvalue(':ins_name', $ins_name);
$statement->bindvalue(':t_date', $t_date);
$statement->bindvalue(':t_time', $t_time);
$statement->bindvalue(':t_duration', $t_duration);
$statement->bindvalue(':t_fee', $t_fee);
$statement->bindvalue(':t_savedate', $t_savedate);
$statement->bindvalue(':t_closing_date', $t_closing_date);
$statement->bindvalue(':t_description', $t_description);
$statement->execute();
?>

How can I seek in a video outputted by PHP?

For outputting a big video (duration 20m46s, size 1.34 GB),
I use the following code (file video.php):

<?php
define('CHUNK_SIZE', 1024*1024); // Size (in bytes) of tiles chunk
// Read a file and display its content chunk by chunk
function readfile_chunked($filename, $retbytes = TRUE) {
    $buffer = '';
    $cnt    = 0;
    $handle = fopen($filename, 'rb');

    if ($handle === false) {
        return false;
    }

    while (!feof($handle)) {
        $buffer = fread($handle, CHUNK_SIZE);
        echo $buffer;
        ob_flush();
        flush();

        if ($retbytes) {
            $cnt += strlen($buffer);
        }
    }

    $status = fclose($handle);

    if ($retbytes && $status) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }

    return $status;
}

$filename = 'video.mp4';
$mimetype = 'video/mp4';
header('Content-Type: '.$mimetype );
readfile_chunked($filename);

?>

The video is watched in a HTML page with the following code:

<video controls>

<source src='video.php' type='video/mp4'>
  
</video>

However, seeking in the video doesn’t work correctly.
For example, if I move the play cursor for seeking to the 18:00 timestamp, it will
instead seek to the 0:58 timestamp.

How can I solve this?

pass multiple params from function to funtion and access inputs -Laravel

$myCourseData['points'] = "1";                 
 $myCourseData['totalPoints'] = "2";

$this->update($myCourseData,$myCourseId);

i wanted to pass points & totalPoints from a function to the function update() and access points in update() as $request->points;.How can i do that? Only points & totalPoints are passed from the above function , other params in the update() function input are getting from somewhere else.

function update($request,$id){

 $validator = Validator::make(
            $request->all(),
            [
                'course_id'       => 'nullable|integer',  
                'exam_numbers'    => 'nullable|integer',
                'points'          => 'nullable|integer', 
                'subscription' => 'nullable|boolean',
                'totalPoints'=>'nullable|integer'
            ]
        );     

$points =  $request->points;
}          
    

    

HOW TO GET QUERY IN SQL USING PHP IN SQL TIGGERING

This is my code my $sql variable didn’t give query plese help me for this I try this but I couldn’t please help me with that

<?php 
    $connect = mysqli_connect("localhost", "root", "", "finger");
    $f= "";
    $l= "";
    $sql = "CREATE TRIGGER `ersdmmmmecv` AFTER INSERT ON `event` FOR EACH ROW  SELECT fname,Lname INTO $f,$l  FROM user WHERE id=NEW.id;"
    $result = mysqli_query($connect, $sql);
?>

PHP Doctrine DTO integer id to uuid from ResultSetMapping

I am fetching results from doctrine native query and want to convert the id into uuid using result set mapper,I am using the below code:

$rsm = new ResultSetMapping();
    $rsm->addScalarResult('id', 'id', 'uuid_magic_optimised');
    $rsm->addScalarResult('title', 'title');
    $rsm->addScalarResult('vendor', 'vendor');
    $rsm->addScalarResult('icon_name', 'icon_url');

But getting the following error:

Doctrine  DBAL  Types  ConversionException
Could not convert database value "1" to Doctrine Type uuid_binary_ordered_time

Why can you call a private method on a new instance made inside a public method of the same class type, in PHP?

Why can you call a private method on a new instance made inside a public method of the same class type?

class Foo
{
    private function thePrivateMethod()
    {
        echo 'can not be called publicly?';
    }

    public function thePublicMethod()
    {
        $clone = new Foo;
        $clone->thePrivateMethod();
    }
}

$foo = new Foo();
$foo->thePublicMethod();
$foo->thePrivateMethod();

The above results in the following output when run in PHP 7.3.18

can not be called publicly?

Fatal error:  Uncaught Error: Call to private method Foo::thePrivateMethod() from context

Intuitively, I would expect the first call to Foo::thePrivateMethod() to also cause a fatal error. But I’m not able to find in the documentation that this behaviour would be allowed?

How to delete original after converting image with Spatie Media Library (laravel)

I am using Laravel 8 and I was wondering if there is anyway to automatically delete original image after it has converted in Spatie Media Library? it’s currently taking up my storage space so I want to be able to delete original images.

here’s the model

<?php

namespace AppModels;

use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
use SpatieImageManipulations;
use SpatieMediaLibraryHasMediaHasMedia;
use SpatieMediaLibraryHasMediaHasMediaTrait;
use SpatieMediaLibraryModelsMedia;

class Profile extends Model implements HasMedia
{
    use HasMediaTrait, softDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'theme_id',
        'name',
        'username',
        'location',
        'bio',
        'views',
    ];

    protected $appends = [
        'avatar_url',
        'route',
    ];

    protected $with = [
        'links',
        'theme',
    ];

    /**
     * Get the route key for the model.
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return 'username';
    }

    /**
     * @return mixed
     */
    public function getAvatarUrlAttribute()
    {
        if ($this->hasMedia('avatar')) {
            return $this->getFirstMedia('avatar')->getUrl('cropped');
        }

        return asset('/images/avatar.png');
    }

    /**
     * @return mixed
     */
    public function getRouteAttribute()
    {
        return route('profiles.show', $this);
    }

    /**
     * @return mixed
     */
    public function getKeywordsAttribute()
    {
        $keywords = $this->links
            ->map(function ($link) {
                return "{$link->name} {$this->name}";
            })
            ->toArray();

        $keywords[] = $this->name;

        return implode(',', $keywords);
    }

    /**
     * Get all of the profile's links.
     *
     * @param string $order
     *
     * @return IlluminateDatabaseEloquentRelationsMorphMany
     */
    public function links($order = 'asc')
    {
        return $this->morphMany(Link::class, 'linkable')->orderBy('order', $order);
    }

    /**
     * Get profile theme.
     *
     * @return IlluminateDatabaseEloquentRelationsBelongsTo
     */
    public function theme()
    {
        return $this->belongsTo(Theme::class);
    }

    /**
     *
     */
    public function viewed()
    {
        $this->increment('views');
    }

    /**
     *
     */
    public function registerMediaCollections()
    {
        $this->addMediaCollection('avatar')->singleFile();
    }

    /**
     * @param Media|null $media
     *
     * @throws SpatieImageExceptionsInvalidManipulation
     */
    public function registerMediaConversions(Media $media = null)
    {
        $this->addMediaConversion('cropped')
             ->crop(Manipulations::CROP_CENTER, 200, 200)
             ->nonQueued()
             ->performOnCollections('avatar');
    }
}

Anyone know any method to do this so I can save storage space?

How to connect ZKTeco attendance to google sheet or online php server

I don’t have any idea of it how can i get attendance data directly to google sheet from ZKTeco attendance device. I searched many way to connect to php server but there is no clear information, how can I get access to the device attendance log. There also no HTTP request from the device also. So can any share there experience and how can I solve that issue ? I am using ZKTeco K40 and F18

Select all data from database MySQL not working php but the inserting working

First I have the insertion part here it’s getting data from json file then insert then select

  $mysqli  = new mysqli($servername, $username, $password,$db) or die("Connect failed: 
  %sn". $mysqli  -> error);
  echo "Connected successfully";

 $json = file_get_contents("https://raw.githubusercontent.com/SeteMares/full-stack-test/master/feed.json") ;
    $json = json_decode(  $json,true);
    $content= array();
    $TITLE = array();
    $CONTENT = array() ;
    $MEDIA = array() ;
    $SLUG = array() ;
    $categories = array() ;
    foreach ($json as $key => $value){
      
        $TITLE[] = $json[$key]['title'] ;
      
       
        $CONTENT[] = $json[$key]['content'];
        $MEDIA[] = $json[$key]['media'];
        $SLUG[] = $json[$key]['slug'];
        $categories[] = $json[$key]['categories'];
    }
    
    for($s=0;$s<sizeof($TITLE);$s++){

        $url_string =  $CONTENT[$s][0]['content'];
        $res = urldecode($url_string);
        $Cataggory = $categories[$s]['primary']; 
        echo gettype($Cataggory );
        $slug = $SLUG[$s] ;
        echo gettype($slug );

         $sqlquery = "INSERT INTO `jsondata` (`title`, `slug`, `content`, `categories`, `media`) VALUES (  '$TITLE[$s]',   ? ,   ?, ?,  '$TITLE[$s]' )" ;
         $stmt = $mysqli->prepare($sqlquery);
         $stmt->execute(array($slug,$res,$Cataggory));
       
         
    }

when i select the data it doesn’t work it prints

Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetchAll() in C:xampphtdocsfirstphpindex.php:68 Stack trace: #0 {main} thrown in C:xampphtdocsfirstphpindex.php on line 68

this the select code for sure all the code in the same file



     $sqlquery3 = "SELECT 'title'   FROM jsondata  " ;
     $sth = $mysqli->prepare($sqlquery3);
     $sth->execute();
  
     $result = $sth->fetchAll();
     print_r($result);
    

Conflict between 2 function using ajax in wordpress

I have written this code here

  add_action('wp_head','pageType');
function pageType(){
  
    if (is_product()) {
            global $post;
            $product = wc_get_product( $post->ID );
            $tipo    = $product->get_type();
            echo $product->get_name();
            echo $product->get_price();
            echo $product->get_regular_price();
            return $product->get_name();
        }else{    
          return "NOTHING";
        }
    }

add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
  check_ajax_referer( 'my-special-string', 'security' );
  $whatever = intval( $_POST['whatever'] );


 $dataOfProduct = pageType();

  $whatever += 10000;
  echo $whatever . '=>>' . $dataOfProduct .' . ' . '<==== d';
  die(); 
}

The code is working fine

Example when pageType is being added to wp_head with add_action(wp_head,'pageType') the is_product is working fine so it is printing

        echo $product->get_name();
        echo $product->get_price();

But in the second method i have an ajax function because i am trying to send data to a tracking script

add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {

Inside this method when i am calling

 $dataOfProduct = pageType();

It is returning “NOTHING”

What can be the problem why its working is_product() function not working on my_action_callback()

What can be the problem

Here $dataOfProduct = pageType(); i want pageType to return the name of the product

THank you

Finding ocuppations via SQL and/or PHP

I am making a student web app. Amongst other tables, I have a table in which students enroll and enrollments are between two dates.

This app uses MySQL 5.6 and PHP 7.2
It has the following fields:

  • IDStudent
  • StartDate
  • EndDate
  • IDCourse

Each course has a maximum capacity in which it cannot be surpassed.

I want to know, given a start date, end date and IDCourse, how many concurrent students are in a course. I get an approxiumate value just counting rows between two dates

SELECT COUNT(*) FROM enrollments
    WHERE IDCourse = ? 
    AND (
      (StartDate BETWEEN "<start date>" AND "<end date>")
      OR
      (EndDate BETWEEN "<start date>" AND "<end date>")
      OR
      (StartDate <= "<start date>" AND EndDate>= "<end date>")
    )

But that doesn’t take account non overlapping ranges. It counts every enrollment.

For example, I have this very simple case:

Want to find how many students are enrolled between 01/01/2021 and 05/01/2021 at a specified course

And I have those 3 enrollments on that course:

  1. 01/01/2021 – 02/01/2021
  2. 03/01/2021 – 04/01/2021
  3. 20/12/2020 – 01/02/2021

I should get 2 count and not 3, because 1 and 2 don’t overlap while 3 overlaps both.
I tried to search online but I didn’t found something similar, maybe I am not using the correct keywords!

Many thanks for your help
Regards

how can i run PHP functions with query to database from javascript [duplicate]

How can i run php functions with query to the database from the level of the javascript function?

</script>
function databaseUpdate() {

}

</script>


<?php
function databaseUpdatePHP () {

    $sqlUpdateVocabulary = "UPDATE users SET number='$number+20' WHERE email='" . $_SESSION['username'] . "'";
    if(mysqli_query($conn, $sqlUpdateVocabulary)){
        echo "updated successfully.";
    } else {
        echo "ERROR";
    }

}
?>