assigning variables from a mySQL/PDO query in php-ThrowExceptions

Exception or error:

I am working on a formula to create a diet plan based on some info gathered from people. My data is getting written to the database properly and my PDO query is returning the proper data but I need a way to run the data from the query through a formula in the php script. Here is what I have and is not working

require_once("../auth/login_check.php"); //Make sure the user is logged in
require_once("../../variables.php"); //Get the database connection patameters

try {
    $user_id = intval($_SESSION['user_id']);
    $con = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);

    $con->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
    $stmt = $con->prepare("
        SELECT blood_type, body_type, target_fat, plan_weight, sex, desired_outcome, current_fat , activity_lvl
        FROM users
        WHERE user_id = ?;
    ");

    $stmt->execute([$user_id]);
    $data = $stmt->fetchAll();

    //I want to assign the values from the fields to variables so I can use them in a formula
    $blood_type = $data['blood_type'];
    $body_type = $data['body_type'];
    $target_fat = $data['target_fat'];
    $plan_weight = $data['plan_weight'];
    $sex = $data['sex'];
    $desired_outcome = $data['desired_outcome'];
    $current_fat = $data['current_fat'];
    $activity_lvl = $data['activity_lvl'];

  //for example asinging $protein to the same value as the persons $plan_weight
    $protein = $plan_weight;
    $starch = 0;
    $veg = 3;
    $fruit1 = 10;
    $fruit2 = 0;
    $fruit3 = 0;
    $fruit4 = 0;
    $fruit5 = 0;
    $fat = 0;


    //This json returns null with anything that is associated with a value from the database
    //since $protein = $plan_weight it is null in the json on the web page that calls this script
    $meals = [
        ["Meal"=>"1", "Protein"=>$protein, "Starch"=>$starch, "Vegetables"=>$veg, "Fruits"=>$fruit1, "Fats"=>$fat],
        ["Meal"=>"2", "Protein"=>$protein, "Starch"=>$starch, "Vegetables"=>$veg, "Fruits"=>$fruit2, "Fats"=>$fat],
        ["Meal"=>"3", "Protein"=>$protein, "Starch"=>$starch, "Vegetables"=>$veg, "Fruits"=>$fruit3, "Fats"=>$fat],
        ["Meal"=>"4", "Protein"=>$protein, "Starch"=>$starch, "Vegetables"=>$veg, "Fruits"=>$fruit4, "Fats"=>$fat],
        ["Meal"=>"5", "Protein"=>$protein, "Starch"=>$starch, "Vegetables"=>$veg, "Fruits"=>$fruit5, "Fats"=>$fat]
    ];

    die(json_encode($meals));

I am new to JS and php and have spent hours trying to figure this out, any help would be greatly appreciated.

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *