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

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

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

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data