1

I am trying to insert data in database but its not working at all! I followed a tutorial and work according to it But its not working. I tried a lot but no success till now.

Here is my html file

<!DOCTYPE html>
<html>
<script  src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">  </script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form>
Name:-<input type="text" ng-model="bname" />
Phone:-<input type="text" ng-model="bphone" />
<input type="button" value="Submit" ng-click="insertData()" />
</form>
</div>
<script>
 var app = angular.module('myApp',[]);
 app.controller('myCtrl',function($scope,$http){    
 $scope.insertData=function(){      
 $http.post("insert.php", {
    'bname':$scope.bname,
    'bphone':$scope.bphone})        

 .success(function(data,status,headers,config){
 console.log("Data Inserted Successfully");
 });
    }
     });
     </script>
     
</body>
</html>

And insert.php in which I am inserting data in database

<?php 
$data = json_decode(file_get_contents("php://input"));
$bname = mysql_real_escape_string($data->bname);
$bauthor = mysql_real_escape_string($data->bphone);
mysql_connect("localhost", "root", ""); 
mysql_select_db("angular");
mysql_query("INSERT INTO ang('name', 'phone')    VALUES('".$bname."','".$bauthor."')");
?>

UPDATE

    <?php 
$data = json_decode(file_get_contents("php://input"));
$con = new mysqli('localhost', 'root', '', 'angularjs');
$bname = mysqli_real_escape_string($con, $data->bname);
$bphone = mysqli_real_escape_string($con, $data->bphone);
if($con->connect_errno > 0){
  die('Unable to connect to database [' . $con->connect_error . ']');
}
mysqli_query($con,"INSERT INTO jstable (name, phone)VALUES ('".$bname."', '".$bphone."')");    
mysqli_close($con);
?>

After Updating my code I got this error :-

Notice: Trying to get property of non-object in E:\xampp\htdocs\insert.php on line 4

Notice: Trying to get property of non-object in E:\xampp\htdocs\insert.php on line 5

I searched regarding this error and found many result but none of them was helpful in my case!

3
  • what error do you get? Do you receive data properly on server? try to echo $data->bname and $data->bphone and check the network tab for response... Its a sure thing that the response would not be good else they would already have entered into database.. Commented Jun 9, 2016 at 10:35
  • @Tirthraj Barot It showing no error. Actually form is not showing any kind of activity when I click on submit button! On my guess form's data not even reaching to the insert.php file Commented Jun 9, 2016 at 10:40
  • Alright Rishabh.. Give me a while... I got your problem.. Commented Jun 9, 2016 at 10:42

5 Answers 5

4

I modified your code in the following manner

HTML CODE:

<!DOCTYPE html>
<html>
<script  src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">  </script>
<body>
    <div ng-app="myApp" ng-controller="myCtrl">
        <form>
            Name:-<input type="text" ng-model="bname" />
            Phone:-<input type="text" ng-model="bphone" />
            <input type="button" value="Submit" ng-click="insertData()" />
        </form>
    </div>
    <script>
    var app = angular.module('myApp',[]);
    app.controller('myCtrl',function($scope,$http){    
        $scope.insertData=function(){      
            $http.post("test.php", {
                'bname':$scope.bname,
                'bphone':$scope.bphone
            }).then(function(response){
                    console.log("Data Inserted Successfully");
                },function(error){
                    alert("Sorry! Data Couldn't be inserted!");
                    console.error(error);

                });
            }
        });
    </script>

</body>
</html>

and test.php

<?php 
$data = json_decode(file_get_contents("php://input"));
// $bname = mysql_real_escape_string($data->bname);
// $bauthor = mysql_real_escape_string($data->bphone);

$bname = $data->bname;
$bphone = $data->bphone;


mysql_connect("localhost", "root", "password"); 
mysql_select_db("test");

mysql_query("INSERT INTO `ang`(`name`,`phone`)
    VALUES ('".$bname."','".$bphone."') ") or die(mysql_error());
echo $bname." ".$bphone;
?>

This works well..

Sign up to request clarification or add additional context in comments.

24 Comments

It tried this. It shows message in console that data inserted successfuly. But nothing inserted in my database's table. It still empty. I have checked field values, db name and table name and they all are fine in code
one more thing! I removed the the all code from my php file to check if form is actually reaching to the php file or not. And it shows the same result. That mean whether I use php file(in which database conn. establised) or not result come out the same. why it is actually not picking any sql query from that file. Even file is out of the reach for some reason. Have you test this code in ur localhost?
@Rishabh.. There was a little error in my php code.. I just corrected it.. have a look.
Thanks for the reply Tirthraj! Right now I am unable to test your updated code. But I will test it later and let you know the outcome soon :-)
Its still not inserting data. Cant understand whts the problem here
|
1
**insert.php**

<!DOCTYPE html>
<html>
<script  src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">  </script>
<body>
    <div ng-app="myApp" ng-controller="myCtrl">
        <form>
            Name:-<input type="text" ng-model="uname" />
            Phone:-<input type="text" ng-model="uphone" />
            <input type="button" value="Submit" ng-click="insertData()" />
        </form>
    </div>
    <script>
    var app = angular.module('myApp',[]);
    app.controller('myCtrl',function($scope,$http){    
        $scope.insertData=function(){      
            $http.post("testinsert.php", {
                'uname':$scope.uname,
                    'uphone': $scope.uphone
                })
                    .success(function (data, status, headers, config) {
                        console.log("Inserted Successfully!");


                    });
            }
        });
    </script>

</body>
</html>

**testinsert.php**

<?php 
$data = json_decode(file_get_contents("php://input"));
$uname = $data->uname;
$uphone = $data->uphone;
$con = mysql_connect("localhost","root","");
mysql_select_db("angular");
$sql = "insert into Table Name(user_name,user_phone) values('$uname','$uphone')";
$result = mysql_query($sql);
?>

2 Comments

Hi @Chintan, instead of just pasting code as an answer, try to explain it and above all, try to explain how it relates and solves the problem to the question.
insert.php file is view file put the same code and just change the variable name. testinsert.php is php file for insert data into database.
0

You are emptying your values (setting them to false...) using mysql_real_escape_string() before you open a database connection. You should open the connection first.

But the best solution would be to switch to PDO or mysqli and use prepared statements. Then you don't have to do any escaping any more.

1 Comment

I tried your first suggestion but no success. Actually My form's submit button is not even working! when I click on submit button then nothing happens. Copy my html code and execute it. You will understand problem is somehow starting with html page I guess. Dont know if the submit button behavior is fine like that (do nothing). May be after submit it must have shown some error like connectivity or something. BUt its doing nothing at all.
0

change your code like this, it might solve your problem.

mysql_connect("localhost", "root", ""); 
mysql_select_db("angular");
$data = json_decode(file_get_contents("php://input"),true);
$bname = mysql_real_escape_string($data['bname']);
$bauthor = mysql_real_escape_string($data['bphone']);

5 Comments

I tried it but no success. may be problem is somewhere in my html file. Because submit button is not working at all. May be it shows some error when I submit the form (if problem is in insert.php). But its doing nothing. On my guess its not even reaching to the insert.php
Error -: angular.js:10765XMLHttpRequest cannot load file:///E:/xampp/htdocs/saket/wp-content/themes/Divi/insert.php. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
you are executing your HTML file direct from drive, means if your file is on D driver you might clicking on it and executing it, and you might be using chrome, so for your solution put your HTML file in htdocs and try to execute it using localhost
Your suggestion solved the error in console, thx for that But my problem still remains the same.
0

you can insert data with image and also validate input.

<form ng-controller="insert_Ctrl"  method="post" action=""  name="myForm" enctype="multipart/form-data" novalidate>
    <div>
        <p><input type="text" class="form-control" placeholder="Name" name="name" ng-model="name" required>
            <span style="color:red" ng-show="myForm.name.$invalid&&myForm.name.$touched">Enter Name</span>
        </p>
    </div>
    <div>
        <p><input type="file" ng-model="myFile" class="form-control"  onchange="angular.element(this).scope().uploadedFile(this)">
            <span style="color:red" ng-show="(myForm.myFile.$error.required&&myForm.myFile.$touched)">Select Picture</span>
        </p>
    </div>
    <div>
        <input type="button" name="submit2"  ng-click="uploadFile()" class="btn-primary" ng-disabled="myForm.name.$invalid || myForm.myFile.$invalid" value="Insert">
    </div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
<script src="insert.js"></script>

insert.js

var app = angular.module('myApp',[]);
app.service('uploadFile', ['$http','$window', function ($http,$window) {
    this.uploadFiletoServer = function(file,info,uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        fd.append('data', angular.toJson(info));
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(data){
            alert("insert successfull");
            $window.location.href = ' ';//your window location
        })
        .error(function(){
            alert("Error");
        });
    }
}]);
app.controller('insert_Ctrl',  ['$scope', 'uploadFile', function($scope, uploadFile){
    $scope.uploadFile = function() {
        $scope.myFile = $scope.files[0];
        var file = $scope.myFile;
        var info = {
            'name':$scope.name,
        };
        var url = "save_data.php";
        uploadFile.uploadFiletoServer(file,info,url);
    };
    $scope.uploadedFile = function(element) {
        var reader = new FileReader();
        reader.onload = function(event) {
            $scope.$apply(function($scope) {
                $scope.files = element.files;
                $scope.src = event.target.result  
            });
        }
        reader.readAsDataURL(element.files[0]);
    }
}]);

save_data.php

<?php
    require "dbconnection.php";
    $datas=$_POST['data'];
    $myArray = json_decode($datas, true);
    $name=$myArray['name'];
    $ext = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
    $image = time().'.'.$ext;
    move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$image);
    $query="insert into test_table values ('null','$name','$image')";
    mysqli_query($con,$query);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.