1

I am working on an ionic app where the user needs to post data to a MySQL database. Due to some very helpful answers on SO I have gotten around the CORS issues however I have now run into another problem. The submit.php file looks like this:

<?php
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }

    $data = json_decode(file_get_contents("php://input"));
    $celeb = $data->celeb;
    $camp = $data->camp;
    $spirit = $data->spirit;

    $sport = $data->sport;
    $bizs = $data->bizs;
    $entrep = $data->entrep;

    $young = $data->young;
    $conser = $data->conser;
    $saty = $data->saty;

    $name = $data->name;
    $surname = $data->surname;
    $email = $data->email;

    $contacts = $data->contacts;

    $con = mysql_connect('localhost', 'root', 'thePssWrd');
    mysql_select_db('theDB', $con);

    $qry = 'INSERT INTO test 
                    (celeb,camp,spirit,sport,bizs,
                     entrep,young,conser,saty,name,
                     surname,email,contacts) 
             values ("' . $celeb . '","' . $camp . '",' .$spirit . 
                     ','.$sport. ','.$bizs. ','.$entrep. ','.$young. 
                     ','.$conser. ','.$saty. ','.$name. ','.$surname. 
                     ','.$email. ','.$contacts. ')';
    $qry_res = mysql_query($qry);

    if ($qry_res) {

        if ($qry_res) {
            $arr = array('msg' => "Submitted Successfully!!!", 'error' => '');
            $jsn = json_encode($arr);
            print_r($jsn);
        } else {
            $arr = array('msg' => "", 'error' => 'Error In Submit');
            $jsn = json_encode($arr);
            print_r($jsn);
        }
    } else {
        $arr = array('msg' => "", 'error' => 'This is the big error thing...');
        $jsn = json_encode($arr);
        print_r($jsn);
    }
?>

and my controller:

.controller('FrmController', function ($scope , $http) {
    $scope.errors = [];
    $scope.msgs = [];

    $scope.vote = function() {

        $scope.errors.splice(0, $scope.errors.length); 
        $scope.msgs.splice(0, $scope.msgs.length);

        $http.post('http://www.ann7.com/saty/submit.php', {

            'celeb'     : $scope.celeb, 
            'camp'      : $scope.camp, 
            'spirit'    : $scope.spirit,
            'sport'     : $scope.sport,
            'bizs'      : $scope.bizs, 
            'entrep'    : $scope.entrep, 
            'young'     : $scope.young,
            'conser'    : $scope.conser,
            'saty'      : $scope.saty, 
            'name'      : $scope.name, 
            'surname'   : $scope.surname,
            'email'     : $scope.email,
            'contacts'  : $scope.contacts

        }
        ).success(function(data, status, headers, config) {
            if (data.msg != '')
            {

              console.log(data.msg);
                $scope.msgs.push(data.msg);
            }
            else
            {
              console.log(data.error);
                $scope.errors.push(data.error);
            }
        }).error(function(data, status) { 
            $scope.errors.push(status);
        });
    }
});

If you look at the PHP it is outputting error messages and I am receiving the "This is the big error thing..." error message in my console which I am taking as a successful connection to the DB but an error in inserting the values... my html file looks like as an example:

<form  name="nominationForm" ng-controller="FrmController" class="falecomigo novalidate form-manager" >
    <div ng-controller="VoteCtrl" class="list list-inset" >
    <div class="styled-select">
           <select ng-model="bizs">
              <option value="e">option1</option>
              <option value="1">option1</option>
              <option value="2">option1</option>
              <option value="3">option1</option>
              <option value="4">option1</option>
              <option value="5">option1</option>
           </select>
        </div>
        <label class="item item-input">
            <input ng-model="name" name="fieldName" type="text" placeholder="Name" required ng-minlength="2" ng-maxlength="70">
        </label>

        <label class="item item-input">
            <input ng-model="surname" name="fieldSurname" type="text" placeholder="Surname" required ng-minlength="2" ng-maxlength="70">
        </label>
        <label class="item item-input">
            <input ng-model="email" name="fieldEmail" type="email" placeholder="E-mail" required ng-maxlength="50">
        </label>

        <label class="item item-input">
            <input ng-model="contacts" name="fieldNumber" type="text" placeholder="Contact No." required ng-minlength="2" ng-maxlength="70">
        </label>
    </div>

    <div class="padding container">
        <div class="row">
            <button ng-click="vote()" class="button button-balanced  button-small col col-100"> Vote </button>
        </div>
    </div>
</form>

I am not sure where I am going wrong...

2
  • 1
    Could you post the output of mysqli_error() ? Commented Aug 19, 2015 at 8:32
  • @MohammadWalid the error it is outputting undefined Commented Aug 19, 2015 at 8:45

1 Answer 1

2

Instead of sending yourself a fairly meaningless error message do this instead ALWAYS

} else {
    $arr = array('msg' => "", 'error' => mysql_error());
    $jsn = json_encode($arr);
    //print_r($jsn);
    echo $jsn;
}

This error will actually tell you what is wrong.

Of course in a live system you would not want to do this as the user would see error messages that are far to likely to help a hacker. So you would do something like this

} else {
    // log error for admins to check
    error_log( mysql_error(),3, '/some/path/to/error.log');
    $arr = array('msg' => "", 'error' => 'An error occured, see the log');

    $jsn = json_encode($arr);
    //print_r($jsn);
    echo $jsn;
}

ADDITIONAL CHECKS:

I now see you are not doing error checking on any mysql_ function calls, maybe the error is in the connection process, so add

$con = mysql_connect('localhost', 'root', 'thePssWrd');
if (!$con) {
    // log error for admins to check
    //error_log( mysql_error(),3, '/some/path/to/error.log');
    die('Could not connect: ' . mysql_error());
}


if (! mysql_select_db('theDB', $con) ) {
   die ('Can\'t select the database: ' . mysql_error());
}

Ahhhh

It look like you are not actually sending the json encoded data back to the browser as a simple string. Instead of print_r($jsn) do a simple echo $jsn; and that applies to all retuning of json data strings. At this point $json is not actually an array anyway, its a simple string variable.

You could also simplify the coding of that query

Remember that double quotes allow you to expand $variables so it might be this solves the underlying issue by just making the coding ot that query a bit more straight forward.

$qry = "INSERT INTO test 
                (celeb,camp,spirit,sport,bizs,
                 entrep,young,conser,saty,name,
                 surname,email,contacts) 
         values ('$celeb','$camp','$spirit','$sport','$bizs',
                 '$entrep','$young','$conser','$saty','$name',
                 '$surname','$email','$contacts')";

$surname was missing

I feel I should add this, as if I dont someone else will. Please if you are just learning PHP and its database access mechanisms, dont waste time learning the mysql_ extension. It is deprecated and is no longer available in the new PHP7 soon to be released. Look at this and learn either the mysqli_ extension or PDO. Have a read on this to help you pick one.

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

6 Comments

Fair enough. console output is undefined
See additional checks, need to check almost all mysql_ functions return values
I have added the additional checks but I am still getting undefined in my console log. thanx for all the help so far.
haha I saw it the moment it was up. thanx! the error I am receiving is You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',,,,,,,,,)' at line 1
Ok check the simplify query suggestion and correction
|

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.