Как обновить данные из динамически созданной таблицы в базу данных в php - PullRequest
0 голосов
/ 22 января 2020

Я создал таблицу, используя php динамически. Но мне нужно обновить некоторые значения ячейки в зависимости от ввода пользователя. Но я не могу понять, как это сделать. мои коды приведены ниже. Я нашел способ сделать имена массивом, это использовать [] в атрибуте names из stackoverflow. но это не сработало для меня. Если я отображаю $ _POST ['std_name'], пока l oop или за пределами l oop, учитывается только последняя строка имени студента. Пожалуйста, помогите. Я застрял здесь на 3 дня.

<form action="" method="post">
        <table>
            <tr>
                <th>Student ID</th>
                <th>Student Name</th>
                <th>Student Father Name</th>
                <th>Student Mother Name</th>
                <th>Student Parents Mobile Number</th>
                <th>Student Mobile Number</th>
                <th>Student Batch Name</th>
                <th>Student College Name</th>
                <th>Student Gender</th>
                <th>Student Picture</th>
                <th>Student Admit Date</th>
                <th>January</th>
                <th>February</th>
                <th>March</th>
                <th>April</th>
                <th>May</th>
                <th>June</th>
                <th>July</th>
                <th>August</th>
                <th>September</th>
                <th>October</th>
                <th>November</th>
                <th>December</th>
            </tr>
            <tr>
                <?php
            $host="localhost";
            $username="root";
            $password="";
            $db="paragon_first_year";
            $qry="select * from `student_info`";
            $con=mysqli_connect($host,$username,$password);
            mysqli_select_db($con,$db);
            $res=mysqli_query($con,$qry);
            if(mysqli_num_rows($res)>0){
                while($dt=mysqli_fetch_array($res)){?>
                <td><input type="text" name="std_id[]" value="<?php echo $dt['std_id']?>"></td>
                <td><input type="text" name="std_name[]" value="<?php echo $dt['std_name']?>"></td>
                <td><input type="text" name="std_father_name[]" value="<?php echo $dt['std_father_name']?>"></td>
                <td><input type="text" name="std_mother_name[]" value="<?php echo $dt['std_mother_name']?>"></td>
                <td><input type="text" name="std_parent_mob[]" value="<?php echo $dt['std_parents_mob_no']?>"></td>
                <td><input type="text" name="std_mob[]" value="<?php echo $dt['std_mob_no']?>"></td>
                <td><?php echo $dt['std_batch_name'] ?></td>
                <td><?php echo $dt['std_college_name'] ?></td>
                <td><?php echo $dt['std_gender'] ?></td>
                <td><img style="height:100px;width:100px;" src="uploadImage/<?php echo $dt['std_name']."_".$dt['std_pic'] ?>" alt=""></td>
                <td><?php echo $dt['std_admit_date'] ?></td>
                <td><input type="text" name="jan[]" value="<?php echo $dt['january']?>"></td>
                <td><input type="text" name="feb[]" value="<?php echo $dt['february']?>"></td>
                <td><input type="text" name="mar[]" value="<?php echo $dt['march']?>"></td>
                <td><input type="text" name="apr[]" value="<?php echo $dt['april']?>"></td>
                <td><input type="text" name="may[]" value="<?php echo $dt['may']?>"></td>
                <td><input type="text" name="jun[]" value="<?php echo $dt['june']?>"></td>
                <td><input type="text" name="jul[]" value="<?php echo $dt['july']?>"></td>
                <td><input type="text" name="aug[]" value="<?php echo $dt['august']?>"></td>
                <td><input type="text" name="sep[]" value="<?php echo $dt['september']?>"></td>
                <td><input type="text" name="oct[]" value="<?php echo $dt['october']?>"></td>
                <td><input type="text" name="nov[]" value="<?php echo $dt['november']?>"></td>
                <td><input type="text" name="dec[]" value="<?php echo $dt['december']?>"></td>
            </tr><?php 

                }
            }
        ?>

        </table>
        <center>
            <input type="submit" name="submit" value="Update Data">
        </center>
</form>
</body>

мой стол хорошо показывает

надеюсь, кто-то поможет. Заранее спасибо.

1 Ответ

0 голосов
/ 23 января 2020

Вы можете использовать ключи массива для передачи информации. В этом примере первый ключ - это первичный ключ базы данных, а второй ключ - это имя переменной.

Полученный массив будет выглядеть примерно так:

$row[123][std_name] = 'joe';
$row[123][std_father_name] = 'bob';
... etc
$row[124][std_name] = 'sally';
$row[124][std_father_name] = 'john';
...etc

Тогда, когда вы итерируя по строкам, вы получаете ключ (123), чтобы использовать его для обновления базы данных, как в where std_id=123.

Примечание. Я использовал подготовленные операторы, чтобы показать обновление базы данных. Это важно Никогда не помещайте переменные в запрос с использованием конкатенации (т. Е. "select * from table where id='$id'")

Наконец, обратите внимание на структуру. Начните с PHP, без операторов print или echo. Это позволяет вам работать с пользовательским вводом, а затем перенаправлять. Сначала инициализируйте, затем работайте с пользовательским вводом, затем выполните логику страницы c, и, наконец, выйдите из php и выведите представление (html)

Этот пример не копирует и вставляет; в нем есть вещи, которые необходимо заполнить и, возможно, отладить. Он просто предназначен, чтобы показать большую картину.

<?php

// initialize
$host="localhost";
$username="root";
$password="";
$db="paragon_first_year";
$con=mysqli_connect($host,$username,$password);

// a simple wrapper to make the prepared query more manageable
// see https://phpdelusions.net/mysqli/mysqli_connect#helper
function prepared_query($mysqli, $sql, $params, $types = "")
{
    $types = $types ?: str_repeat("s", count($params));
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    return $stmt;
}

// work with user input
if($_SERVER['REQUEST_METHOD'] === 'POST') {

    $dataRows = (array)$_POST['data'];
    foreach($dataRows as $id=>$data) {

        $sql = "INSERT INTO student_info SET std_name=?, std_father_name=?, " .
               // etc  . 
               "WHERE std_id=?";
        $params = array(
                    $data['std_name'], 
                    $data['std_father_name'], 
                    // etc... 

                    $id
                  );
        // this does the prepare, bind, and execute... Yes, I could just do the 
        // bind and execute here, but the time savings isn't worth the trouble.
        $stmt = prepared_query($con, $sql, $params); 

    }

    // always redirect after a POST
    header('Location: /path/to/next/page/or/this/page');
    die;
}

// no user input; ok to use plain old query.
$qry="select * from `student_info`";
mysqli_select_db($con,$db);
$res=mysqli_query($con,$qry);

?>
<html>

...

<form action="" method="post">
    <table>
        <tr>
            <th>Student ID</th>
            <th>Student Name</th>
            <th>Student Father Name</th>
            <th>Student Mother Name</th>
            <th>Student Parents Mobile Number</th>
            <th>Student Mobile Number</th>
            <th>Student Batch Name</th>
            <th>Student College Name</th>
            <th>Student Gender</th>
            <th>Student Picture</th>
            <th>Student Admit Date</th>
            <th>January</th>
            <th>February</th>
            <th>March</th>
            <th>April</th>
            <th>May</th>
            <th>June</th>
            <th>July</th>
            <th>August</th>
            <th>September</th>
            <th>October</th>
            <th>November</th>
            <th>December</th>
        </tr>
        <!-- don't need mysqli_num_rows; the while won't loop if no results -->
        <?php while($dt=mysqli_fetch_array($res)): ?>
        <tr>
            <td><?= $dt['std_id'] ?></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_name']" value="<?= $dt['std_name'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_father_name']" value="<?= $dt['std_father_name'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_mother_name']" value="<?= $dt['std_mother_name'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_parent_mob']" value="<?= $dt['std_parents_mob_no'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_mob']" value="<?= $dt['std_mob_no'] ?>"></td>
            <td><?= $dt['std_batch_name']  ?></td>
            <td><?= $dt['std_college_name']  ?></td>
            <td><?= $dt['std_gender']  ?></td>
            <td><img style="height:100px;width:100px;" src="uploadImage/<?= $dt['std_name']."_".$dt['std_pic']  ?>" alt=""></td>
            <td><?= $dt['std_admit_date']  ?></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['jan']" value="<?= $dt['january'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['feb']" value="<?= $dt['february'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['mar']" value="<?= $dt['march'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['apr']" value="<?= $dt['april'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['may']" value="<?= $dt['may'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['jun']" value="<?= $dt['june'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['jul']" value="<?= $dt['july'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['aug']" value="<?= $dt['august'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['sep']" value="<?= $dt['september'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['oct']" value="<?= $dt['october'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['nov']" value="<?= $dt['november'] ?>"></td>
            <td><input type="text" name="data[<?= $dt['std_id'] ?>]['dec']" value="<?= $dt['december'] ?>"></td>
        <?php endwhile; ?>
        </tr>
    </table>
    <center>
        <input type="submit" name="submit" value="Update Data">
    </center>
</form>
</body>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...