mysql – PHP How to import excel file xlsx or others into database using a web controller-ThrowExceptions

Exception or error:

There is how to import excel files into mysql database using a controller. A upload service class is needed and the PHPOFFICE too.

For upload service:
http://zetcode.com/symfony/uploadfile/

For installation of PHPOFFICE:
https://phpspreadsheet.readthedocs.io/en/latest/

My code is not the best, not the most secure and not the best in organization, but it works pretty well. For dev utilisation.


namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Service\FileUploader;
use Exception;


/**
 * @Route("/file")
 */
class UploadController extends AbstractController
{
/**
 * @Route("/upload", name="upload_player")
 */
public function indexUpload()
{
    return $this->render('upload/form.html.twig', [
        'controller_name' => 'UploadController',
    ]);
}

    /**
     * @Route("/doUpload", name="doUpload")
     */
    public function index(Request $request, string $uploadDir, FileUploader $uploader)
    {


        $file = $request->files->get('myfile');

        if (empty($file)) 
        {
            return new Response("No file specified",  
               Response::HTTP_UNPROCESSABLE_ENTITY, ['content-type' => 'text/plain']);
        }        

        $inputFileName = $file->getClientOriginalName();
        $uploader->upload($uploadDir, $file, $inputFileName);

        $targetPath = '../var/uploads/'.$inputFileName;



        $conn = mysqli_connect("localhost","db_user","db_password","db_name");



        /**  Identify the type of $inputFileName  **/
        $inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($targetPath);

        /**  Create a new Reader of the type that has been identified  **/
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);

        /**  Load $inputFileName to a Spreadsheet Object  **/
        $spreadsheet = $reader->load($targetPath);

        $worksheet = $spreadsheet->getActiveSheet();

        $highestRow = $worksheet->getHighestRow(); // total number of rows

        $highestColumn = $worksheet->getHighestColumn(); // total number of columns

        $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); // e.g. 5



        if ($highestRow <= 0) {
            Exit ('There is no data in the Excel table');
        }


        for ($row = 1; $row <= $highestRow; ++$row) {

            $lastname = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(1, $row)->getFormattedValue());
            $firstname = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(2, $row)->getFormattedValue());
            $picture = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(3, $row)->getFormattedValue());
            $birthday = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(4, $row)->getFormattedValue());
            $nationality = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(5, $row)->getFormattedValue());
            $address = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(6, $row)->getFormattedValue());
            $postal = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(7, $row)->getFormattedValue());
            $city = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(8, $row)->getFormattedValue());
            $email = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(9, $row)->getFormattedValue());
            $jersey_number = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(10, $row)->getFormattedValue());
            $foot_shoot = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(11, $row)->getFormattedValue());
            $shoe_size = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(12, $row)->getFormattedValue());
            $jersey_size = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(13, $row)->getFormattedValue());
            $short_size = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(14, $row)->getFormattedValue());
            $licence_number = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(15, $row)->getFormattedValue());
            $mobile_phone = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(16, $row)->getFormattedValue());
            $fix_phone = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(17, $row)->getFormattedValue());
            $note = mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(18, $row)->getFormattedValue());

/*With foreign keys:*/
            $team = ("SELECT id FROM team WHERE name = '". mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(19, $row)->getFormattedValue())."'"); 
            $category = ("SELECT id FROM categories WHERE type = '". mysqli_real_escape_string($conn, $worksheet->getCellByColumnAndRow(20, $row)->getFormattedValue())."'"); 

            $query = "insert into player(lastname, firstname, picture, birthday, nationality, address, postal, city, email, jersey_number, foot_shoot, shoe_size, jersey_size, short_size, licence_number, mobile_phone, fix_phone, note, team_id, categories_id) VALUES ('".$lastname."','".$firstname."','".$picture."','".$birthday."','".$nationality."','".$address."','".$postal."','".$city."','".$email."','".$jersey_number."','".$foot_shoot."','".$shoe_size."','".$jersey_size."','".$short_size."','".$licence_number."','".$mobile_phone."','".$fix_phone."','".$note."',(".$team."),(".$category."))";

        try {
            $result = mysqli_query($conn, $query);
            if ($result == true){
                echo 'OK ';
            }else{
                var_dump($result) . var_dump($conn) . var_dump($query);
            }

        } catch (Exception $e) {
        echo $e->getMessage();
        }
    }
        return new Response(" File uploaded",  Response::HTTP_OK, ['content-type' => 'text/plain']);  

    }
    }



How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *