Я пытаюсь изменить таблицу в базе данных, но когда я пытаюсь изменить данные столбца отображаются, но не в той же строке других данных? - PullRequest
0 голосов
/ 27 апреля 2020

Это страница PHP, которую я создал для отображения данных из базы данных:

<?php
$museumDb = new PDO('sqlite:museums.db');
if (isset($_POST['add'])) {
    $queryString = "INSERT INTO museums (museum_id, museum_name, country) VALUES (" . $_POST['museum_id'] . ", '" . $_POST['museum_name'] . "', '" . $_POST['country'] . "')";
    $query = $museumDb->prepare($queryString);
    $query->execute();
}
if (isset($_POST['delete'])) {
    $queryString = "DELETE FROM museums WHERE museum_id = " . $_POST['museum_id'];
    $query = $museumDb->prepare($queryString);
    $query->execute();
}
$query = $museumDb->prepare('SELECT * FROM museums');
$query->execute();
$museums = $query->fetchAll(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="style.css" type="text/css" rel="stylesheet">
    <title>Museums</title>
</head>

<body>
    <table>
        <tr>
            <th>ID#</th>
            <th>Museum Name</th>
            <th>City</th>
            <th>Country</th>
        </tr>
        <?php foreach ($museums as $museum) : ?>
            <tr>
                <td><?php print $museum['museum_id']; ?></td>
                <td><?php print $museum['museum_name']; ?></td>
                <td><?php print $museum['city_name']; ?></td>
                <td><?php print $museum['country']; ?></td>
                <td><input type="submit" name="edit" value="edit"></td>
                <td><input type="submit" name="delete" value="delete"></td>
            </tr>
        <?php endforeach; ?>
    </table>
    <form action="result.php" method="GET">
        <label for="country">Pick A Country:</label>
        <select id="country" name="country">
            <option value="" disabled selected="selected">---Pick a state---</option>
            <option value="France">France</option>
            <option value="Russia">Russia</option>
            <option value="China">China</option>
            <option value="United States">United States</option>
            <option value="Vatican City">Vatican City</option>    
            <option value="Japan">Japan</option>
            <option value="Mexico">Mexico</option>
            <option value="United Kingdom">United Kingdom</option>
            <option value="South Korea">South Korea</option>
            <option value="Belgium">Belgium</option>
            <option value="Israel">Israel</option>
            <option value="Singapore">Singapore</option>
            <option value="Italy">Italy</option>
            <option value="Spain">Spain</option>
            <option value="Egypt">Egypt</option>
            <option value="Brazil">Brazil</option>
            <option value="Austria">Austria</option>
            <option value="Czech Republic">Czech Republic</option>
            <option value="Germany">Germany</option>
            <option value="Australia">Australia</option>
            <option value="India">India</option>
            <option value="Netherlands">Netherlands</option>
            <option value="Canada">Canada</option>
            <option value="Hungary">Hungary</option>
            <option value="Switzerland">Switzerland</option>
            <option value="Poland">Poland</option>
            <option value="Taiwan">Taiwan</option>
            <option value="Tunisia">Tunisia</option>
            <option value="Norway">Norway</option>
            <option value="UAE">UAE</option>
            <option value="Greece">Greece</option>
        </select>
        <br>
        <input type="submit" value="Submit">
    </form>
    <form method="POST">
        <table>
            <tr>
                <td><input type="text" name="museum_" required></td>
                <td><input type="text" name="addcountry" required></td>
                <td><input type="text" name="addmuseum" required></td>
                <td><input type="submit" name="add" value="add museum"></td>
            </tr>
        </table>
    </form>
</body>
</html>

Это файл mysqlite, который я создал, я создал первую таблицу раньше и теперь должен добавить еще один столбец с новая информация, чтобы соответствовать другим строкам в таблице. Поэтому я выбираю команду ALTER TABLE.

.open museums.db
CREATE TABLE museums (
museum_id INTEGER PRIMARY KEY AUTOINCREMENT,
museum_name TEXT,
country TEXT
);
INSERT INTO museums (
museum_name,
country
)
VALUES
("Louvre","France"),
("State Hermitage Museum", "Russia"),
("National Museum of China", "China"),
("Metropolitan Museum of Art", "United States"),
("Vatican Museums", "Vatican City"),
("Tokyo National Museum", "Japan"),
("National Museum of Anthropology", "Mexico"),
("Victoria and Albert Museum", "United Kingdom"),
("National Museum of Korea", "South Korea"),
("Art Institute of Chicago", "United States"),
("Nanjing Museum", "China"),
("British Museum", "United Kingdom"),
("National Gallery of Art", "United States"),
("MASS MoCA", "United States"),
("Cinquantenaire Museum", "Belgium"),
("Three Gorges Museum", "China"),
("Museum of Fine Arts", "United States"),
("Shandong Art Museum", "China"),
("Israel Museum", "Israel"),
("National Gallery Singapore", "Singapore"),
("Minneapolis Institute of Art", "United States"),
("Arsenal (Biennale)", "Italy"),
("Musée National d'Art Moderne", "France"),
("Musée d'Orsay", "France"),
("Ōtsuka Museum of Art", "Japan"),
("San Francisco Museum of Modern Art", "United States"),
("Museo del Prado", "Spain"),
("Philadelphia Museum of Art", "United States"),
("Denver Art Museum", "United States"),
("Egyptian Museum", "Egypt"),
("Museo di Capodimonte", "Italy"),
("Matarazzo Ciccillo (Bienal)", "Brazil"),
("Dia:Beacon", "United States"),
("Dallas Museum of Art", "United States"),
("Museo Reina Sofía", "Spain"),
("MMCA, Gwacheon", "South Korea"),
("Detroit Institute of Arts", "United States"),
("Kunsthistorisches Museum", "Austria"),
("Tokyo National Art Center", "Japan"),
("National Taiwan Museum of Fine Arts", "Taiwan"),
("National Gallery in Prague (Veletržní)", "Czech Republic"),
("Indianapolis Museum of Art", "United States"),
("Bavarian National Museum", "Germany"),
("Brooklyn Museum", "United States"),
("Capital Museum", "China"),
("Montreal Museum of Fine Arts", "Canada"),
("National Gallery", "United Kingdom"),
("National Gallery of Victoria (St Kilda Road)", "Australia"),
("Palais de Tokyo", "France"),
("Salar Jung Museum", "India"),
("Virginia Museum of Fine Arts", "United States"),
("Tate Modern", "United Kingdom"),
("Cleveland Museum of Art", "United States"),
("National Gallery of Canada", "Canada"),
("Hamburger Kunsthalle", "Germany"),
("Museum Boijmans Van Beuningen", "Netherlands"),
("Houston Museum of Fine Arts", "United States"),
("National Gallery of Modern Art", "India"),
("Palais des Beaux-Arts de Lille", "France"),
("Pinakothek der Moderne", "Germany"),
("Rijksmuseum", "Netherlands"),
("Tretyakov Gallery (Krymsky Val)", "Russia"),
("Milwaukee Art Museum", "United States"),
("Taipei Fine Arts Museum", "Taiwan"),
("Museum of Modern Art", "United States"),
("Art Gallery of Ontario", "Canada"),
("Art Gallery of New South Wales", "Australia"),
("Capitoline Museums", "Italy"),
("Fondazione Prada", "Italy"),
("Guggenheim Museum", "Spain"),
("Los Angeles County Museum of Art", "United States"),
("MAC-University of São Paulo", "Brazil"),
("Pergamon Museum", "Germany"),
("Shaanxi History Museum", "China"),
("HangarBicocca", "Italy"),
("Museu Nacional d'Art de Catalunya", "Spain"),
("Tibet Museum", "China"),
("Portland Art Museum", "United States"),
("Museum of Fine Arts,Budapest", "Hungary"),
("Carnegie Museum of Art", "United States"),
("Hamburger Bahnhof", "Germany"),
("Kunstmuseum Basel", "Switzerland"),
("MAXXI", "Italy"),
("Museo Egizio", "Italy"),
("Museum Kunstpalast", "Germany"),
("MMCA Seoul", "South Korea"),
("National Museum, Poznań", "Poland"),
("Russian Museum", "Russia"),
("Saint Louis Art Museum", "United States"),
("Museums of Sforza Castle", "Italy"),
("Tel Aviv Museum of Art", "Israel"),
("National Palace Museum", "Taiwan"),
("National Archaeological Museum", "Spain"),
("Musée Fabre", "France"),
("Bardo National Museum", "Tunisia"),
("Cité de l'Architecture et du Patrimoine", "France"),
("National Museum, New Delhi", "India"),
("National Gallery", "Norway"),
("Power Station of Art (Biennale)", "China"),
("Smithsonian American Art Museum", "United States"),
("Musée du quai Branly", "France"),
("Liaoning Provincial Museum", "China"),
("Gallerie di Piazza Scala", "Italy"),
("National Art Museum of China", "China"),
("Galleria degli Uffizi", "Italy"),
("Galleria Nazionale d'Arte Moderna", "Italy"),
("Gemäldegalerie", "Germany"),
("Louvre Abu Dhabi", "UAE"),
("Museum Ludwig", "Germany"),
("National Archaeological Museum", "Greece"),
("Neues Museum", "Germany"),
("Petit Palais", "France"),
("Pushkin Museum", "Russia"),
("Stedelijk Museum", "Netherlands"),
("Thyssen-Bornemisza Museum", "Spain"),
("Toledo Museum of Art", "United States"),
("Tretyakov Gallery", "Russia"),
("de Young", "United States"),
("Nelson-Atkins Museum of Art", "United States");
ALTER TABLE museums 
ADD COLUMN city_name TEXT;
INSERT INTO museums(city_name)
VALUES
('Paris'),
('St. Petersburg'),
('Beijing'),
('New York City'),
('Vatican City (Rome)'),
('Tokyo'),
('Mexico City'),
('London'),
('Seoul'),
('Chicago'),
('Nanjing'),
('London'),
('Washington'),
('North Adams'),
('Brussels'),
('Chongqing'),
('Boston'),
('Jinan'),
('Jerusalem'),
('Singapore'),
('Minneapolis'),
('Venice'),
('Paris'),
('Paris'),
('Naruto'),
('San Francisco'),
('Madrid'),
('Philadelphia'),
('Denver'),
('Cairo'),
('Naples'),
('São Paulo'),
('Beacon, New York'),
('Dallas'),
('Madrid'),
('Gwacheon'),
('Detroit'),
('Vienna'),
('Tokyo'),
('Taichung'),
('Prague'),
('Indianapolis'),
('Munich'),
('New York City'),
('Beijing'),
('Montreal'),
('London'),
('Melbourne'),
('Paris'),
('Hyderabad'),
('Richmond'),
('London'),
('Cleveland'),
('Ottawa'),
('Hamburg'),
('Rotterdam'),
('Houston'),
('New Delhi'),
('Lille'),
('Munich'),
('Amsterdam'),
('Moscow'),
('Milwaukee'),
('Taipei'),
('New York City'),
('Toronto'),
('Sydney'),
('Rome'),
('Milan'),
('Bilbao'),
('Los Angeles'),
('São Paulo'),
('Berlin'),
('Xi''an'),
('Milan'),
('Barcelona'),
('Lhasa'),
('Portland, Oregon'),
('Budapest, Hungary'),
('Pittsburgh'),
('Berlin'),
('Basel'),
('Rome'),
('Turin'),
('Düsseldorf'),
('Seoul'),
('Poznań'),
('Saint-Petersburg'),
('St. Louis'),
('Milan'),
('Tel Aviv'),
('Taipei'),
('Madrid'),
('Montpellier'),
('Tunis'),
('Paris'),
('New Delhi'),
('Oslo'),
('Shanghai'),
('Washington, D.C.'),
('Paris'),
('Shenyang'),
('Milan'),
('Beijing'),
('Florence'),
('Rome'),
('Berlin'),
('Abu Dhabi'),
('Cologne'),
('Athens'),
('Berlin'),
('Paris'),
('Moscow'),
('Amsterdam'),
('Madrid'),
('Toledo, Ohio'),
('Moscow'),
('San Francisco'),
('Kansas City');
.exit

Изображение - это результат того, что произошло после того, как я добавил столбец "city_name". Раньше он прекрасно работал, прежде чем я добавил колонку города.

enter image description here

1 Ответ

0 голосов
/ 27 апреля 2020

После ALTER вы создаете новые записи с INSERT. Если вы хотите связать ваши города с существующими записями, вы должны указать это:

UPDATE museums SET city_name='Paris' WHERE museum_id=XXX;

, где XXX - это точно запись Museum_id с 'Louvre'.

Если вы используете миграцию базы данных, чем вы должны подготовьте значения городов для существующей базы данных.

Или, если у вас есть имя и состояние:

UPDATE museums SET city_name='Paris' WHERE museum_name='Louvre' AND country='France';
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...