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!

Community
  • 1
  • 1
Rishabh
  • 610
  • 2
  • 11
  • 32
  • 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.. – Tirthraj Barot Jun 09 '16 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 – Rishabh Jun 09 '16 at 10:40
  • Alright Rishabh.. Give me a while... I got your problem.. – Tirthraj Barot Jun 09 '16 at 10:42

5 Answers5

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..

Tirthraj Barot
  • 2,671
  • 2
  • 17
  • 33
  • 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 – Rishabh Jun 09 '16 at 12:13
  • 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 Jun 09 '16 at 12:35
  • @Rishabh.. There was a little error in my php code.. I just corrected it.. have a look. – Tirthraj Barot Jun 09 '16 at 12:44
  • 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 :-) – Rishabh Jun 09 '16 at 14:31
  • Its still not inserting data. Cant understand whts the problem here – Rishabh Jun 10 '16 at 04:46
  • Ok now when I run php file instead of html then it shows error `Fatal error: Call to undefined function mysql_connect()` – Rishabh Jun 10 '16 at 05:14
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/114304/discussion-between-tirthraj-barot-and-rishabh). – Tirthraj Barot Jun 10 '16 at 05:18
  • @Rishabh You should reply.. I want my answer to be marked as correct if it helped you... – Tirthraj Barot Jun 14 '16 at 08:46
  • @ Tirthraj Barot I havent sort out my prob till now. You can see in chat what error I m facing right now. I was busy in my project, thats way couldnt reply you. Sry about that. This ques. was not part of my project, I was doing it for knowledge purpose. So didnt get much time to make search for my new error. – Rishabh Jun 15 '16 at 05:52
  • Hi Tirthraj! Have a look on my updated ques. and tell me if you have any idea regarding this :) – Rishabh Jun 18 '16 at 09:31
  • Use $data["bname"] instead of -> operator... @Rishabh – Tirthraj Barot Jun 18 '16 at 09:35
  • It removed error But still not inserting data in db table! May be test this code in ur machine once.. – Rishabh Jun 18 '16 at 09:42
  • Echo it before escape string function.. The error lies in that.. The mysql_real_escape_string function. @Rishabh – Tirthraj Barot Jun 18 '16 at 09:44
  • Echo Just the data["bname"]... Before calling that mysql_real_escape_string function – Tirthraj Barot Jun 18 '16 at 09:50
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/114997/discussion-between-rishabh-and-tirthraj-barot). – Rishabh Jun 18 '16 at 09:53
  • M sorry I can't get into chat.. &@Rishabh – Tirthraj Barot Jun 18 '16 at 09:56
  • ok its fine :) But that didnt work. May be try execute the code later so that u can understand the prob that i m facing – Rishabh Jun 18 '16 at 10:02
  • I have understood your problem pretty well.. All you need to do is remove mysql_real_escape_string from your code – Tirthraj Barot Jun 18 '16 at 10:04
  • Nothings changed by removing mysql_real_escape_string. First it inserted empty value in table then second and other time it didnt even insert empty value. – Rishabh Jun 18 '16 at 10:07
  • bname"]); does not need a ")" you did it twice in the code you sent in chat – Tirthraj Barot Jun 18 '16 at 10:11
  • And you don't need a "new" before mysqli @Rishabh – Tirthraj Barot Jun 18 '16 at 10:14
  • Firstly by removing new keyword it throw error `Fatal error: Call to undefined function mysqli() in E:\xampp\htdocs\insert.php on line 3` And second thing see my updated code in chat as per ur suggetion but still no luck! – Rishabh Jun 18 '16 at 10:17
  • You need to call mysqli_connect() @Rishabh – Tirthraj Barot Jun 18 '16 at 10:29
  • I am done with that! Nothing is working for me. I quit on this topic now. Since its not part of my projects so I can leave in between tho. I got tired with it now! 9 days still nothing works form me! Anyhow I accepted ur answer for trying to help me out. Thx for ur time :-) – Rishabh Jun 18 '16 at 10:34
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);
?>
Chintan
  • 11
  • 1
  • 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. – Nahuel Ianni Dec 05 '16 at 09:14
  • 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. – Chintan Feb 20 '17 at 10:03
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.

jeroen
  • 91,079
  • 21
  • 114
  • 132
  • 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. – Rishabh Jun 09 '16 at 10:26
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']);
Archish
  • 850
  • 8
  • 32
  • 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 – Rishabh Jun 09 '16 at 10:29
  • 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.` – Rishabh Jun 09 '16 at 10:48
  • 1
    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 – Archish Jun 09 '16 at 10:57
  • also see here http://stackoverflow.com/questions/10752055/cross-origin-requests-are-only-supported-for-http-error-when-loading-a-local – Archish Jun 09 '16 at 10:57
  • Your suggestion solved the error in console, thx for that But my problem still remains the same. – Rishabh Jun 09 '16 at 12:27
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);
?>