назначение переменных из запроса mySQL / PDO в php - PullRequest
1 голос
/ 18 марта 2020

Я работаю над формулой для создания плана диеты, основанного на некоторой информации, полученной от людей. Мои данные правильно записываются в базу данных, и мой запрос PDO возвращает правильные данные, но мне нужен способ для запуска данных из запроса через формулу в сценарии php. Вот что у меня есть и не работает

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));

Я новичок в JS и php и потратил часы, пытаясь выяснить это, любая помощь будет принята с благодарностью.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...