douzhimei8259 2018-01-28 17:40
浏览 63

无法从Key JSON MySQL PHP获得价值

I am retrieving data from a MySQL database using PHP and attempting to use JSON.stringify and JSON.parse to create an object. It works fine but I cannot get the assocaited keys/values. Just the entire object. I break this up in to parts. Here is the PHP code:

First PHP File:

<?php
session_start();
include("web_db_operations.php");

if(isset($_POST['recipeId']) && isset($_SESSION['email'])){
    $recipeId = $_POST['recipeId'];
    $email = $_SESSION['email'];
}
else{
    echo "Did not work";
}
    $results = getAllMyRecipesAsList_recipeTable2($email, $recipeId);
    $_SESSION['recipeResults'] = $results;
    header('location:web_selected_recipe.php');
    exit();
?>

Second PHP File

 function getAllMyRecipesAsList_recipeTable2(string $email, int $recipeId){
    include 'config.php';
    $sql = 'SELECT * FROM recipeTable WHERE email = :email AND recipeId = :recipeId';
    $stmt = $conn->prepare($sql);       
    $stmt->bindParam(':email', $email, PDO::PARAM_STR);
    $stmt->bindParam(':recipeId', $recipeId, PDO::PARAM_STR);
    $stmt->execute();
    $getResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $json = array();
    if(count($getResults) > 0){
        foreach($getResults as $row){
            $json[] = array('firstName' => $row['firstName'],
                           'lastName' => $row['lastName'],
                           'email' => $row['email'],
                           'recipeName' => $row['recipeName'],
                           'description' => $row['description'],
                           'ingredients' => $row['ingredients'],
                           'prepTime' => $row['prepTime'],
                           'steps' => $row['steps'],
                           'nutrition' => $row['nutrition'],
                           'servings' => $row['servings'],
                           'rating' => $row['rating'],
                           'tags' => $row['tags'],
                           'imagePath' => $row['imagePath'],
                           'imageName' => $row['imageName'],
                           'recipeId' => $row['recipeId']
                           );
         }
        $results = json_encode($json);
        return $results;
    }else{
        echo "no data found";
    }
    }

Then to retrieve in my JS file (this is just the relevant parts):

<script>
    <?php $results = $_SESSION['recipeResults'];
var results = <?php echo $results; ?>;
    var toString = JSON.stringify(results);
    console.log(toString);
    var parsed = JSON.parse(toString);
    console.log(parsed);
</script>

Logging resultAsString yields this:

[{"firstName":"Marcus","lastName":"Holden","email":"marcus@gmail.com","recipeName":"Aloo Paratha","description":"","ingredients":"","prepTime":"25 Minutes","steps":"","nutrition":"","servings":"","rating":"","tags":"","imagePath":"../userRecipeImages","imageName":"9110164.jpg","recipeId":"1"}]

Logging parsed yields this:

[{…}]
0:description:
"No Description", email "marcus@gmail.com", firstName:"Marcus", imageName:"9110164.jpg", imagePath:"../userRecipeImages", ingredients:"Some Ingredients",lastName:"Holden", nutrition:"Not given", prepTime:"25 Minutes", rating:"5/10", recipeId:"1", recipeName:"Aloo Paratha", servings: "6", steps:"Your Steps Here", tags:"It's bread"

Now, I have tried all steps to get the value associated with a key... for instance my object here is called parsed... so I have tried parsed.firstName.. returns undefined... as well as Object.keys(parsed). I cannot seem to get the keys. I would like to work with it like an array... setting content like this:

element.innerHTML = parsed[2]... etc.

What am I missing here?

  • 写回答

1条回答 默认 最新

  • dongzanghui4624 2018-01-28 17:48
    关注

    I think you're doing quite a bit more than you need to. The data is coming to you as a JSON-encoded object. Just work with it.

    <script>
    var results = <?php echo $_SESSION['recipeResults']; ?>;
    
    var first_results = results[0]; // Each array member is one object from your result set
    console.log( first_results.firstName );
    
    console.log( results[0].firstName ); // OR specify which array index to interact directly
    </script>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决