PHP / MySQL — вставка данных JSON в БД на сервере Bluehost, пустая запись в БД

Это одноразовый скрипт для вставки данных JSON в мою базу данных MySQL на Bluehost. Я использовал различные операторы 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();
?>

Последнее «Данные вставлены правильно» всегда срабатывает, но в моей БД есть только одна запись с 0, сохраненным в cmc, мощностью, ударной вязкостью и многовариантным и бесцветным в записи цветов. card_ID — мой первичный ключ, и он пуст.

Либо БД не настроена правильно, либо я что-то упустил в коде. Я бы добавил скриншот структуры моей БД, но я не уверен, разрешено ли это здесь. Для параметров сортировки установлено значение utf8_general_ci и Varchar для текстовых записей и int или smallint для чисел. Структура JSON находится здесь: http://mtgjson.com/ .

Я не знал PHP и MySQL два дня назад, так что простите, если я что-то упустил. Все остальные вопросы, которые я прочитал, похоже, не решают эту проблему.

1

Решение

Ваш mysql_query находится вне цикла for, поэтому он выполняется только один раз. Так должно быть

for($i = 0; $i <= count($cards); $i++) {
//
//...
// 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')";

//----> HERE instead
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Data inserted correctly. <br>";
}
}

$card_Type = mysql_real_escape_string($cards[$i]['type']);
$card_Rarity = mysql_real_escape_string($cards[$i]['rarity']);

так далее

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector