Связь междуи php - PullRequest
       1

Связь междуи php

0 голосов
/ 05 декабря 2018

Пожалуйста, обратитесь к изображению.Я хочу, чтобы значение нажатой кнопки было идентификатором студента в базе данных.Как узнать, какая кнопка нажата пользователем?Проблема в том, что имена всех входов одинаковы.

                <form method="post" name="data">
                    <table style="overflow-x: auto; display: block; white-space: nowrap; max-height: 450px; max-width: 1100px;"
                           class="table table-striped">
                        <tr>
                            <th>ID</th>

                            <th>Student Name</th>
                            <th>Address</th>
                            <th>Contact No.</th>
                            <th>Email</th>
                            <th colspan="4">Accept / Reject</th>
                        </tr>
                        <?php
                        $query = "SELECT StudentID,StudentName,Address,ContactNo,Email FROM Student WHERE Accepted=0";
                        $mysqli = connect();
                        //Get result
                        $result = $mysqli->query($query) or die($mysqli->error . " " . __LINE__); //__LINE__ shows the line no. we are getting the error at

                        if ($result->num_rows > 0) {
                            //Loop through results
                            while ($row = mysqli_fetch_array($result)) {
                                //Display customer info
                                $output = "<tr>";
                                $output .= "<td>" . $row['StudentID'] . "</td>";

                                $output .= "<td>" . $row['StudentName'] . "</td>";
                                $output .= "<td >" . $row['Address'] . "</td>";
                                $output .= "<td >" . $row['ContactNo'] . "</td>";
                                $output .= "<td >" . $row['Email'] . "</td>";

                                $output .= "<td><input type='hidden'  name='Yes" . $row['StudentID'] . "' value='" . $row['StudentID'] . "' ></td>";
                                $output .= "<td><input type='submit'   value='yes' class='btn-success' style='border:none;'></td>";

                                $output .= "<td><input type='hidden'  name='No' value='" . $row['StudentID'] . "' ></td>";
                                $output .= "<td><input type='submit'  value='No' class='btn-link' style='border:none;' ></td>";;
                                $output .= "</tr>";
                                echo $output;
                            }
                            echo "</table>";

                        } else
                            echo "No pending request found";

                        ?>
                    </table>
                </form>

Ответы [ 4 ]

0 голосов
/ 05 декабря 2018

Проблема в том, что имена всех входов одинаковы.

Присвойте им уникальные значения и используйте элемент <button>, чтобы метка дисплея не совпадала с меткойзначение.

<button type='submit' value='No-UNIQUE-ID' class='btn-link' style='border:none;'>
    No
</button>
0 голосов
/ 05 декабря 2018

У меня была похожая проблема, и мне пришлось использовать JS / jQuery

$(".myClass").bind("click", function() {
    var id = event.target.id;
    window.location.href = "myPage?id="+id;
});
0 голосов
/ 05 декабря 2018

Если у вас будет несколько кнопок отправки (по одной на каждую петлю foreach), все, что вам нужно, это передать уникальный value для кнопки, чтобы определить, какую из них вы нажали.Один из простых способов сделать это - передать как ответ «да / нет», так и идентификатор студента.Например:

<input type="submit" name="response" value="yes|<?php echo $row['studentID']; ?>" class="btn-success" style="border:none;">

Затем при обработке формы вы берете значение, полученное в $_POST['response'], взорвите его в трубе, и вы получите ответ да / нет и идентификатор студента:

$verdict = explode("|", $_POST['response']);
$yay_or_nay = $verdict[0];
$whom = $verdict[1];

тогда вы можете делать все, что вам нужно, с $yay_or_nay и $whom

0 голосов
/ 05 декабря 2018

У меня действительно была похожая проблема.Я решил, что в каждой строке по две радиокнопки с частью «да» или «нет», сохраненной в значении.Они отделяются разделителем от другого значения (вашего StudentID).Кнопка отправки под таблицей затем позволяет пользователю отправлять ответы в большом количестве.

Ваш код будет выглядеть примерно так:

                <form method="post" name="data">
                <table style="overflow-x: auto; display: block; white-space: nowrap; max-height: 450px; max-width: 1100px;"
                       class="table table-striped">
                    <tr>
                        <th>ID</th>

                        <th>Student Name</th>
                        <th>Address</th>
                        <th>Contact No.</th>
                        <th>Email</th>
                        <th colspan="4">Accept / Reject</th>
                    </tr>
                    <?php
                    $query = "SELECT StudentID,StudentName,Address,ContactNo,Email FROM Student WHERE Accepted=0";
                    $mysqli = connect();
                    //Get result
                    $result = $mysqli->query($query) or die($mysqli->error . " " . __LINE__); //__LINE__ shows the line no. we are getting the error at

                    $count = $result->num_rows;
                    if ($result->num_rows > 0) {
                        //Loop through results
                        while ($row = mysqli_fetch_array($result)) {
                            //Display customer info
                            $output = "<tr>";
                            $output .= "<td>" . $row['StudentID'] . "</td>";

                            $output .= "<td>" . $row['StudentName'] . "</td>";
                            $output .= "<td >" . $row['Address'] . "</td>";
                            $output .= "<td >" . $row['ContactNo'] . "</td>";
                            $output .= "<td >" . $row['Email'] . "</td>";

                            $output .= "<td><input type='radio'  name='radio" . $count . "' value='" . $row['StudentID'] . "|accept' ></td>";

                            $output .= "<td><input type='radio'  name='radio" . $count . "' value='" . $row['StudentID'] . "|reject' ></td>";

                            $output .= "</tr>";
                            echo $output;
                            $count += 1;
                        }
                        echo "</table>";
                        echo "<input type='submit' name='submit' value='submit'>";

                    } else
                        echo "No pending request found";

                    ?>
                </table>
            </form>

Затем вы получите значения из любого выбранного радио btn.и сделайте остаток своего кода:

if(isset($_POST['submit'])) {
    for($x = 0; $x < $count; $x++) {
        if(isset($_POST['radio' . $x])) {
            $values = explode('|', $_POST['radio' . $x]);
            $id = $values[0];
            $status = $values[1];

            //Do stuff with each result
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...