0

Thank you for being here!

i want to be able to select acc_id from account_info table and insert it in patient_info table as Foreign Key

I am getting this error :

In my localhost i can see the value it's suppose to return. And this error which I suppose it occurs because i haven't inserted acc_id yet SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'acc_id' cannot be null

Also var_dump($data) returns array(1) { [0]=> object(stdClass)#3 (1) { ["acc_id"]=> int(124) } }

php file :

 <?php
 header('Access-Control-Allow-Origin: *');

// Define database connection parameters
$hn      = 'localhost';
$un      = 'root';
$pwd     = '';
$db      = 'ringabell';
$cs      = 'utf8';

// Set up the PDO parameters
$dsn  = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt  = array(
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                   );
// Create a PDO instance (connect to the database)
$pdo  = new PDO($dsn, $un, $pwd, $opt);

// Retrieve specific parameter from supplied URL
$data = array();


     try{

    $stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
    $data = $stmt->fetchAll(PDO::FETCH_OBJ);
        // Return data as JSON
            echo json_encode($data); 
            var_dump($data);


    $sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)    
                            VALUES(:data, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";


        $stmt    = $pdo->prepare($sql); 

        $stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
        $stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
        $stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
        $stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
        $stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
        $stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);
            $stmt->bindParam(':data', $acc_id, PDO::PARAM_STR); 


        $stmt->execute();

         echo json_encode(array('message' => 'Congratulations the record was added to the database')); 
   }

    catch(PDOException $e)
     {
        echo $e->getMessage();
     }
?>
Voula16
  • 55
  • 8
  • The exception is throwing an error, view the browser console and find out what it is. [echo $e->getMessage();](https://stackoverflow.com/questions/47650049/insert-selected-data-in-database) – Lawrence Cherone Dec 05 '17 at 22:45
  • console:I have this error `core.js:1350 ERROR SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at Response.Body.json (VM10679 vendor.js:52450) at MapSubscriber.project (VM10680 main.js:324) at MapSubscriber._next (VM10679 vendor.js:51233) at MapSubscriber.Subscriber.next (VM10679 vendor.js:18364) at XMLHttpRequest.onLoad (VM10679 vendor.js:52943) at t.invokeTask (VM10678 polyfills.js:3) at Object.onInvokeTask (VM10679 vendor.js:5235) at t.invokeTask (VM10678 polyfills.js:3) at r.runTask (VM10678 polyfills.js:3)` – Voula16 Dec 05 '17 at 22:50
  • No not the error, the response of `patients.php` – Lawrence Cherone Dec 05 '17 at 22:51
  • I'm sorry you mean in my local host page, if so there is no errors – Voula16 Dec 05 '17 at 22:52
  • Try serching an error before posting [SyntaxError: Unexpected token < in JSON at position 0](https://stackoverflow.com/questions/37280274/syntaxerror-unexpected-token-in-json-at-position-0-in-react-app), somthing is wrong with your php file **its not returning valid json** (most likely its responding with HTML, like an xdebug error because of an uncaught exception) – Lawrence Cherone Dec 05 '17 at 22:53
  • please show us your patients.php code – Kamrul Khan Dec 05 '17 at 22:53
  • I added it ! @KamrulKhan – Voula16 Dec 05 '17 at 22:59
  • from your ajax code, you need to send something like: `this.http.get('http://localhost:10080/ionic/patients.php?key=')` – Kamrul Khan Dec 05 '17 at 23:03
  • i had other options in my code such as update and delete that's why i have key. but when i put `try{..}` inside switch nothing happens anymore – Voula16 Dec 05 '17 at 23:03
  • i updated my code is it better now? – Voula16 Dec 05 '17 at 23:07
  • if you remove the ` var_dump($data);` from your code and simply run `http://localhost:10080/ionic/patients.php` from your browser, what do you see? The way you have your code now, if you can run your code without any error, it should response with two JSON objects. Which is not a valid JSON object. – Kamrul Khan Dec 05 '17 at 23:09
  • it returns the value `[{"acc_id":127}]` – Voula16 Dec 05 '17 at 23:13
  • what i want to be able to do in the end is insert this value as foreign key in the table – Voula16 Dec 05 '17 at 23:15
  • you dont get anything for `echo json_encode(array('message' => 'Congratulations the record was added to the database')); ` ? that does not sound right to me – Kamrul Khan Dec 05 '17 at 23:19
  • @Voula16 It wouldn't simply return that, it would return `[{"acc_id":127}]{"message":"Congratulations the record was added to the database"}`, you cant json encode twice, or var_dump as thats **not valid** json! Moving on, good luck. – Lawrence Cherone Dec 05 '17 at 23:19
  • @KamrulKhan please bear with me i don't get anything for `echo json_encode(array('message' => 'Congratulations the record was added to the database'));` – Voula16 Dec 05 '17 at 23:23
  • when i removed `switch` i got this error too `Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'acc_id' cannot be null in C:\xampp\htdocs\ionic\patients.php:59 Stack trace: #0 C:\xampp\htdocs\ionic\patients.php(59): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\ionic\patients.php on line 59` I think this is because the column acc_id is still empty right ? – Voula16 Dec 05 '17 at 23:24
  • @KamrulKhan still there ? – Voula16 Dec 05 '17 at 23:37
  • Yes that's because the $acc_id variable is null and in your database you defined the acc_id column as not null. I don't see where you are getting all the value you are binding in your insert query? – Kamrul Khan Dec 05 '17 at 23:53
  • it's in my ts file – Voula16 Dec 05 '17 at 23:55

1 Answers1

1

It seems there are multiple issues in your code or the way you are trying to do things. Please check the code below. It should work. I have added few inline comments. Please check them:

<?php


// Define database connection parameters
$hn      = 'localhost';
$un      = 'root';
$pwd     = '';
$db      = 'ringabell';
$cs      = 'utf8';

// Set up the PDO parameters
$dsn  = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt  = array(
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                   );
// Create a PDO instance (connect to the database)
$pdo  = new PDO($dsn, $un, $pwd, $opt);

// Retrieve specific parameter from supplied URL
$data = array();


try {

    $stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
    $data = $stmt->fetchAll(PDO::FETCH_OBJ);
    // You do not need to return response from here
    // echo json_encode($data); 
    // var_dump($data);


    $sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)    
                            VALUES(:acc_id, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";


    $stmt    = $pdo->prepare($sql);

    // the $p_fname, $p_lname, $p_gender etc variables in your code were never initiated. You would get
    // notice for this if you had all error_reporting on. I am not sure from where you intend to get this info;
    // so, I just added some dummy data.
    $p_fname = 'Patient first name';
    $p_lname = 'Patient last name';
    $p_gender = 'm';
    $p_condition = 'condition';
    $p_birthdate = '1999-01-01';
    $p_emergencycontact = 'Contact';

    $stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
    $stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
    $stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
    $stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
    $stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
    $stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);

    // You do not have any $acc_id variable in your code. To get data from your fetch you need to do 
    // like this:
    $stmt->bindParam(':acc_id', $data[0]->acc_id, PDO::PARAM_STR); 


    $stmt->execute();

    header('Access-Control-Allow-Origin: *');

    // If you want to get the acc_id in your client side through the AJAX call, combine both
    // mesage and data in the same JSON object.
    echo json_encode(
        array(
            'message' => 'Congratulations the record was added to the database'
            'data' => $data
        )
   ); 
} catch(PDOException $e) {
    // make sure to send the proper status code
    http_response_code(500);
    // even error should be sent back as in json so that your javascript client can
    // easily parse it
    echo json_encode(
        array(
            'error' => $e->getMessage()
        )
    );
}
?>
Kamrul Khan
  • 3,260
  • 4
  • 32
  • 59