Skip to main content

How yo insert data with image in AngularJs and PHP mysql

I have a CRUD table where I want to display users list with the profile pictures I'm using AngularJs and Bootstrap I have added upload file to the form and I'm able to insert to the DB but not able to save the uploaded file to my directory (/uploads)

My index form

<!DOCTYPE html>
<html>
    <head>
        <title>users</title>
        <script src="jquery.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
        <script src="jquery.dataTables.min.js"></script>
        <script src="angular-datatables.min.js"></script>
        <script src="bootstrap.min.js"></script>
        <link rel="stylesheet" href="bootstrap.min.css">
        <link rel="stylesheet" href="datatables.bootstrap.css">
        
    </head>
    <body ng-app="crudApp" ng-controller="crudController">
        
        <div class="container" ng-init="fetchData()">
            <br />
                <h3 align="center">user's List</h3>
            <br />
            <div class="alert alert-success alert-dismissible" ng-show="success" >
                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                
            </div>
            <div align="right">
                <button type="button" name="add_button" ng-click="addData()" class="btn btn-success">Add</button>
            </div>
            <br />
            <div class="table-responsive" style="overflow-x: unset;">
                <table datatable="ng" dt-options="vm.dtOptions" class="table table-bordered table-striped">
                    <thead>
                        <tr><!--data-visible="false"-->
                            <th width="10%">Image</th>
                            <th width="35%">First Name</th>
                            <th width="35%">Last Name</th>
                            <th width="10%">Edit</th>
                            <th width="10%">Delete</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr ng-repeat="name in namesData">
                            <td>
                                <img  id="" ng-src="uploads/" class="thumbnail" height="50" width="50" >
                            </td>
                            <td></td>
                            <td></td>
                            <td><button type="button" ng-click="fetchSingleData(name.id)" class="btn btn-warning btn-xs">Edit</button></td>
                            <td><button type="button" ng-click="deleteData(name.id)" class="btn btn-danger btn-xs">Delete</button></td>
                        </tr>
                    </tbody>
                </table>
            </div>

        </div>
    </body>
</html>

<div class="modal fade" tabindex="-1" role="dialog" id="crudmodal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form method="post" ng-submit="submitForm()">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title"></h4>
                </div>
                <div class="modal-body">
                    <div class="alert alert-danger alert-dismissible" ng-show="error" >
                        <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                        
                    </div>
                    <div class="form-group">
                        <label>Enter First Name</label>
                        <input type="text" name="first_name" ng-model="first_name" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Enter Last Name</label>
                        <input type="text" name="last_name" ng-model="last_name" class="form-control" />
                    </div>

                    <div class="custom-file">
                <input type="file" class="custom-file-input" name="photo" ng-model="photo">
                <label class="custom-file-label" for="photo">Choose file</label>
              </div>

                </div>
                <div class="modal-footer">
                    <input type="hidden" name="hidden_id" value="" />
                    <input type="submit" name="submit" id="submit" class="btn btn-info" value="" />
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </form>
        </div>
    </div>
</div>


<script>

var app = angular.module('crudApp', ['datatables']);
app.controller('crudController', function($scope, $http){

    $scope.success = false;

    $scope.error = false;

    $scope.fetchData = function(){
        $http.get('fetch_data.php').success(function(data){
            $scope.namesData = data;
        });
    };

    $scope.openModal = function(){
        var modal_popup = angular.element('#crudmodal');
        modal_popup.modal('show');
    };

    $scope.closeModal = function(){
        var modal_popup = angular.element('#crudmodal');
        modal_popup.modal('hide');
    };

    $scope.addData = function(){
        $scope.modalTitle = 'Add Data';
        $scope.submit_button = 'Insert';
        $scope.openModal();
    };

    $scope.submitForm = function(){
        $http({
            method:"POST",
            url:"insert.php",
            data:{'photo':$scope.photo, 'first_name':$scope.first_name, 'last_name':$scope.last_name, 'action':$scope.submit_button, 'id':$scope.hidden_id}
        }).success(function(data){
            if(data.error != '')
            {
                $scope.success = false;
                $scope.error = true;
                $scope.errorMessage = data.error;
            }
            else
            {
                $scope.success = true;
                $scope.error = false;
                $scope.successMessage = data.message;
                $scope.form_data = {};
                $scope.closeModal();
                $scope.fetchData();
            }
        });
    };

    $scope.fetchSingleData = function(id){
        $http({
            method:"POST",
            url:"insert.php",
            data:{'id':id, 'action':'fetch_single_data'}
        }).success(function(data){
            $scope.photo = data.photo;
            $scope.first_name = data.first_name;
            $scope.last_name = data.last_name;
            $scope.hidden_id = id;
            $scope.modalTitle = 'Edit Data';
            $scope.submit_button = 'Edit';
            $scope.openModal();
        });
    };

    $scope.deleteData = function(id){
        if(confirm("Are you sure you want to remove it?"))
        {
            $http({
                method:"POST",
                url:"insert.php",
                data:{'id':id, 'action':'Delete'}
            }).success(function(data){
                $scope.success = true;
                $scope.error = false;
                $scope.successMessage = data.message;
                $scope.fetchData();
            }); 
        }
    };

});

</script>

Insert file which I'm unable to insert images

<?php

//insert.php

include('database_connection.php');

$form_data = json_decode(file_get_contents("php://input"));

$error = '';
$message = '';
$validation_error = '';
$first_name = '';
$last_name = '';

if($form_data->action == 'fetch_single_data')
{
    $query = "SELECT * FROM tbl_sample WHERE id='".$form_data->id."'";
    $statement = $connect->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    foreach($result as $row)
    {
        $output['first_name'] = $row['first_name'];
        $output['last_name'] = $row['last_name'];
    }
}
elseif($form_data->action == "Delete")
{
    $query = "
    DELETE FROM tbl_sample WHERE id='".$form_data->id."'
    ";
    $statement = $connect->prepare($query);
    if($statement->execute())
    {
        $output['message'] = 'Data Deleted';
    }
}
else
{
    if(empty($form_data->first_name))
    {
        $error[] = 'First Name is Required';
    }
    else
    {
        $first_name = $form_data->first_name;
    }

    if(empty($form_data->last_name))
    {
        $error[] = 'Last Name is Required';
    }
    else
    {
        $last_name = $form_data->last_name;
    }

    if(empty($error))
    {
        if($form_data->action == 'Insert')
        {
            $data = array(
                ':first_name'       =>  $first_name,
                ':last_name'        =>  $last_name
            );
            $query = "
            INSERT INTO tbl_sample 
                (first_name, last_name) VALUES 
                (:first_name, :last_name)
            ";
            $statement = $connect->prepare($query);
            if($statement->execute($data))
            {
                $message = 'Data Inserted';
            }
        }
        if($form_data->action == 'Edit')
        {
            $data = array(
                ':first_name'   =>  $first_name,
                ':last_name'    =>  $last_name,
                ':id'           =>  $form_data->id
            );
            $query = "
            UPDATE tbl_sample 
            SET first_name = :first_name, last_name = :last_name 
            WHERE id = :id
            ";

            $statement = $connect->prepare($query);
            if($statement->execute($data))
            {
                $message = 'Data Edited';
            }
        }
    }
    else
    {
        $validation_error = implode(", ", $error);
    }

    $output = array(
        'error'     =>  $validation_error,
        'message'   =>  $message
    );

}



echo json_encode($output);

?>

Fetch table

<?php

//fetch_data.php

include('database_connection.php');

$query = "SELECT * FROM tbl_sample ORDER BY id";
$statement = $connect->prepare($query);
if($statement->execute())
{
    while($row = $statement->fetch(PDO::FETCH_ASSOC))
    {
        $data[] = $row;
    }

    echo json_encode($data);
}

?>

I'm using PDO connection



source https://stackoverflow.com/questions/70406252/how-yo-insert-data-with-image-in-angularjs-and-php-mysql

Comments

Popular posts from this blog

Where and how is this Laravel kernel constructor called? [closed]

Where and how is this Laravel kernel constructor called? public fucntion __construct(Application $app, $Router $roouter) { } I have read the documentation and some online tutorial but I can find any clear explanation. I am learning Laravel and I am wondering where does this kernel constructor receives its arguments from. "POSTMOTERM" CLARIFICATION: Here is more clarity.I have checked the boostrap/app.php and it is only used for boostrapping the interfaces into the container class. What is not clear to me is where and how the Kernel class is instatiated and the arguments passed to the object calling the constructor.Something similar to; obj = new kernel(arg1,arg2) or, is the framework using some magic functions somewhere? Special gratitude to those who burn their eyeballs and brain cells on this trivia before it goes into a full blown menopause alias "MARKED AS DUPLICATE". To some of the itchy-finger keyboard warriors, a.k.a The mods,because I believe in th...

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

Confusion between commands.Bot and discord.Client | Which one should I use?

Whenever you look at YouTube tutorials or code from this website there is a real variation. Some developers use client = discord.Client(intents=intents) while the others use bot = commands.Bot(command_prefix="something", intents=intents) . Now I know slightly about the difference but I get errors from different places from my code when I use either of them and its confusing. Especially since there has a few changes over the years in discord.py it is hard to find the real difference. I tried sticking to discord.Client then I found that there are more features in commands.Bot . Then I found errors when using commands.Bot . An example of this is: When I try to use commands.Bot client = commands.Bot(command_prefix=">",intents=intents) async def load(): for filename in os.listdir("./Cogs"): if filename.endswith(".py"): client.load_extension(f"Cogs.{filename[:-3]}") The above doesnt giveany response from my Cogs ...