【发布时间】:2015-11-01 19:13:37
【问题描述】:
这是一个一次性脚本,用于将 JSON 数据插入到我在 Bluehost 上的 MySQL 数据库中。我在循环内外使用了各种 echo 语句,以确保正确解析 JSON 信息并且循环按预期工作。 Bluehost 帮助文件告诉我使用 SQL 语句而不是 SQLi 或 DBO。
<?php
$con = mysql_connect ("localhost:port", "username", "password");
if (!$con) {
die('Could not reach database: Error Code ' . mysql_error() . "<br>");
} else {
echo 'Connected to database. ' . "<br>";
}
mysql_select_db ("db_name", $con);
$jsondata = file_get_contents('BFZ.json');
$data = json_decode($jsondata, true);
$cards = $data['cards'];
// loop through the cards array and load each set of variables into the DB
for($i = 0; $i <= count($cards); $i++) {
$card_Name = $cards[$i]['name'];
$card_ManaCost = $cards[$i]['manaCost'];
$card_CMC = $cards[$i]['cmc'];
// Clear the variable from its last use
$card_Colors = "";
// If the card has no color info, assign the text "Colorless"
if ($cards[$i]['colors'] == "") {
$card_Colors = "Colorless";
// Else if the card has color info, convert the colors array into one long text variable
} else {
for($colorIndex = 0; $colorIndex < count($cards[$i]['colors']); $colorIndex++) {
$card_Colors = $card_Colors . $cards[$i]['colors'][$colorIndex] . " ";
}
}
// various bits to load into the DB
$card_Type = $cards[$i]['type'];
$card_Rarity = $cards[$i]['rarity'];
$card_Text = $cards[$i]['text'];
$card_Number = $cards[$i]['number'];
$card_Power = $cards[$i]['power'];
$card_Toughness = $cards[$i]['toughness'];
$card_MultID = $cards[$i]['multiverseid'];
$card_ID = $cards[$i]['id'];
// insert the data into the cards table
$sql = "INSERT INTO cards (card_ID, card_name, manaCost, cmc, colors, type, rarity, card_text, card_number, power, toughness, multiverseid)
VALUES ('$card_ID', '$card_Name', '$card_ManaCost', '$card_CMC', '$card_Colors', '$card_Type', '$card_Rarity', '$card_Text', '$card_Number', '$card_Power', '$card_Toughness', '$card_MultID')";
}
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Data inserted correctly. <br>";
}
$con->close();
?>
最后一个“正确插入的数据”总是触发,但我的数据库只有一个条目,在 cmc、power、toughness 和 multiverseid 和 Colorless 条目中存储为 0。 card_ID 是我的主键,它是空白的。
要么数据库设置不正确,要么我在代码中遗漏了一些东西。我会附上我的数据库结构的屏幕截图,但我不确定这里是否允许这样做。排序规则在文本条目上设置为 utf8_general_ci 和 Varchar,在数字上设置为 int 或 smallint。 JSON 结构在这里:http://mtgjson.com/。
直到两天前我才知道 PHP 和 MySQL,所以如果我遗漏了一些简单的东西,请原谅我。我读过的所有其他问题似乎都没有解决这个问题。
【问题讨论】:
-
1) 你能发布发送到服务器的 SQL 吗(所以在 PHP 插入变量之后)? 2)您可能想要检查
mysql_affected_rows()函数(不仅是在查询执行正常的情况下)。 3) 尝试使用 MySQLi 而不是 MySQL 函数,因为它们已被弃用 -
我不知道如何做第 1 点,但我绝对可以研究第 2 点。第 3 点,好吧,我不确定 DB 或 Bluehost 是否允许,但我可以尝试。跨度>
-
定义好后可以
echo $sql; -
我刚刚发现数据包含反斜杠。我不知道如何处理它,但我认为这是我正在处理的问题。
标签: php mysql json database bluehost