简体   繁体   English

MySQL和PHP数据库?

[英]MySQL and PHP databases?

I am doing an exercise with PHP and MySQL database management, and I'm trying to return an amount from a field in a table with PHP. 我正在使用PHP和MySQL数据库管理进行练习,我正在尝试使用PHP从表中的字段返回一个数量。 I am trying to get the value from the CalsPerServ in the foods table where the foodsID is equal to the foodsID the user has selected. 我试图从食物表中的CalsPerServ获取值,其中foodsID等于用户选择的foodsID。 All I'm getting now though is an array, when I should be returning one result. 我现在得到的只是一个数组,当我应该返回一个结果时。 Any idea what went wrong? 知道出了什么问题吗?

if($tableName == "meals"){
        $foodsID = filter_input(INPUT_POST, "foodsID");
        $servings = filter_input(INPUT_POST, "Servings");
        $foodsID = mysql_real_escape_string($foodsID);
        $servings = mysql_real_escape_string($servings);

        $query = "SELECT CalsPerServ FROM foods WHERE foodsID=$foodsID";
        $result = mysql_query($query, $connect);
        $CalsPerServ = mysql_fetch_assoc($result);

        print $CalsPerServ;

        $calories = ($CalsPerServ * $servings) * 100;

        $sql .= "(foodsID, Servings, Calories) VALUES ('$foodsID', '$servings', '$calories')";

        $sqltwo = "INSERT INTO daily_diary (foodsID, CaloriesPlus) VALUES ('$foodsID', '$calories')";
        $resulttwo = mysql_query($sqltwo, $connect);
}

The problem lies here in this line 问题出在这一行

$calories = ($CalsPerServ * $servings) * 100;

$CalsPerServ is an array containing the result from the query. $CalsPerServ是一个包含查询结果的数组。 In order to get single column value out of it you have to use it like this 为了获得单列值,你必须像这样使用它

$calories = ($CalsPerServ['CalsPerServ'] * $servings) * 100;

Even though you are querying for one thing, mysql_fetch_assoc() returns an array. 即使您要查询一件事,mysql_fetch_assoc()也会返回一个数组。

This way even if you have selected more than one thing, you will always know you will get back an associative array, with the selected items as its keys. 这样,即使您选择了多个内容,您也总会知道将返回一个关联数组,并将所选项作为其键。

$CalsPerServ = mysql_fetch_assoc($result);

 print $CalsPerServ['CalsPerServ'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM