0

I am having a difficulty of why inserting data in second table is not "inserting" when in the first table it is "inserted".

controller.js

$scope.addStudent = function(student){

    var data {
       firstName: student.firstName,
       gFirstName: student.firstName
    };

    $http.put("php/students/addStudent.php",data).then(function(response){
        console.log(response);
    });
}

addStudent.php

<?php 
   include("../../connection.php");
   $data = json_decode(file_get_contents("php://input"));
   $firstName = $data->firstName;
   $gFirstName = $data->gFirstName;

   $q = "INSERT INTO tblstudents (firstName) VALUES ('$firstName')";
   $db->query($q);
   $r = "INSERT INTO tblparents (firstName) VALUES ('$gFirstName')";
   $db->query($r);
?>

I just added the $r query thinking that it will work the way I expected to work but it's not working the way I expected. No data was being inserted into the table tblparents, while on table tblstudents data is inserted normally.

connection.php

<?php 
   header("Cache-Control: no-cache, must-revalidate"); 
   $db = new PDO("mysql:host=localhost;dbname=myDB","root","");
?>
Marksmanship
  • 169
  • 1
  • 11
  • 1
    Try echoing out your query to make sure it looks valid. Also, you are wide open for SQL injection. Since you're using PDO, take advantage of [prepared statements](https://secure.php.net/manual/en/pdo.prepared-statements.php) and [bindparam](http://php.net/manual/en/pdostatement.bindparam.php) or [bindvalue](http://php.net/manual/en/pdostatement.bindvalue.php). **This will take care of any pesky quoting issues that may occur.** – aynber Aug 18 '17 at 13:57
  • Okay thanks, I will try what you said. Sorry for unsecured coding of mine. Thanks for the tips. – Marksmanship Aug 18 '17 at 14:02
  • there's no error handling here – Masivuye Cokile Aug 18 '17 at 14:17

1 Answers1

0

I did try what @aynber said in the comment in my question above. Thanks to him. And also Thanks to this link of another related question.

This is now my updated addStudent.php

<?php 
  include("../../connection.php");  

    $data = json_decode(file_get_contents("php://input"));
    $firstName = $data->firstName;
    $gFirstName = $data->gFirstName;

    try {
    $db->exec("SET CHARACTER SET utf8");    
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "
    INSERT INTO `tblstudents`(`firstName`) VALUES (:firstName);
    INSERT INTO `tblguardians`(`firstName`) VALUES (:gFirstName);
    ";

    $statement = $db->prepare($sql);
    $statement->bindValue(":firstName", $firstName);
    $statement->bindValue(":gFirstName", $gFirstName);

    $result = $statement->execute();

    }
    catch(PDOException $e) {
       echo $e->getMessage();
    }

    echo json_encode($result);

?>
Marksmanship
  • 169
  • 1
  • 11