上這是一個使用腳本的JSON數據插入到上BlueHost的我的MySQL數據庫。我在循環內部和外部使用了各種echo語句,以確保JSON信息正確解析並且循環按預期工作。 Bluehost幫助文件告訴我使用SQL語句而不是SQLi或DBO。PHP/MySQL的 - 將JSON數據到數據庫服務器BlueHost的,空的DB進入
<?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,電力,韌性好,multiverseid和無色的顏色條目0一個條目。 card_ID是我的主鍵,它是空白的。
要麼DB是沒有正確設置或我缺少的東西代碼。我會包含我的數據庫結構的屏幕截圖,但我不確定這是否允許。排序規則設置爲文本條目上的utf8_general_ci和Varchar以及數字上的int或smallint。 JSON結構如下:http://mtgjson.com/。
我不知道PHP和MySQL,直到兩年前天,以便原諒我,如果我失去了一些東西簡單。我讀過的所有其他問題似乎都沒有解決這個問題。
1)你能張貼獲取發送到服務器的SQL(所以PHP插入變量之後)? 2)你可能想檢查'mysql_affected_rows()'函數(不僅如果查詢執行正常)。 3)嘗試使用,而不是MySQL的函數庫MySQLi,因爲他們已被棄用 – Philip
我不知道該怎麼辦1點,但我可以肯定地看着點2點3,好了,我不知道該DB或BlueHost的允許但我可以嘗試。 –
你可以'echo $ sql;'定義它之後 – Philip