【发布时间】:2011-08-22 02:17:41
【问题描述】:
好的 - 我正在尝试加载 JSON 响应(来自名为 recipes.json 的外部文件,其中包含数百个食谱),其格式如下,以便将其插入名为“recipes”的 MySQL 表中:
{ "recipeName": "After Glow Smoothie", "ingredients": "4 oz. (1/2 cup) pomegranate juice", "ingredients2": "4 oz. (1/2 cup orange juice)", "ingredients3": "2 scoops Vi-Shape shake mix", "ingredients4": "1 cup frozen pineapple", "ingredients5": "5 ice cubes"},
{ "recipeName": "All Berry Delight", "ingredients": "8 oz. skim milk", "ingredients2": "2 scoops Vi-Shape shake mix", "ingredients3": "1/4 cup frozen raspberries", "ingredients4": "1/4 cup frozen blackberries", "ingredients5": "1/4 cup frozen strawberries", "ingredients6": "1/4 cup frozen dark cherries", "ingredients7": "5 ice cubes"}
我对数组不太方便,所以我想知道为什么我不能循环遍历食谱并正确插入它们。我的 JSON 格式是否错误,或者我是这样一个 PHP 菜鸟,以至于我在我的主要代码中犯了错误。参考如下:
<?php
header('Content-Type: text/html; charset=utf-8');
$hostname_ndb = "localhost";
$database_ndb = "test";
$username_ndb = "root";
$password_ndb = "root";
$ndb = mysql_pconnect($hostname_ndb, $username_ndb, $password_ndb) or trigger_error(mysql_error(),E_USER_ERROR);
$url = "http://localhost:8888/shakerecipes/recipes.json";
$json = file_get_contents($url);
// var_dump(json_decode($json, true));
$out = json_decode($json, true);
foreach($out["recipeName"] as $recipeNames) {
$name = addslashes($recipeNames[recipeName]);
$ingredients= addslashes($recipeNames[ingredients]);
$ingredients2 = addslashes($recipeNames[ingredients2]);
$ingredients3 = addslashes($recipeNames[ingredients3]);
$ingredients4 = addslashes($recipeNames[ingredients4]);
$ingredients5 = addslashes($recipeNames[ingredients5]);
$ingredients6 = addslashes($recipeNames[ingredients6]);
$ingredients7 = addslashes($recipeNames[ingredients7]);
$ingredients8 = addslashes($recipeNames[ingredients8]);
$ingredients9 = addslashes($recipeNames[ingredients9]);
mysql_query("INSERT INTO test (recipeName, ingredients, ingredients2, ingredients3, ingredients4, ingredients5, ingredients6, ingredients7, ingredients8, ingredients9) VALUES('$name', '$ingredients', '$ingredients2', '$ingredients3', '$ingredients4', '$ingredients5', '$ingredients6', '$ingredients7', '$ingredients8', '$ingredients9')") or die (mysql_error());
}
?>
感谢所有提示/帮助。
BRR
【问题讨论】:
-
1. addlashes 不是您防止注射的方式。 addlashes 是一种湿面巾纸,它填满了胡佛水坝 50 英尺的裂缝。 2. 如果你不知道你从 json_decode 调用中得到了什么,你可以 var_dump/print_r 看看。