SELECT AND UPDATE - Undefined index when submitting form

Asked

Viewed 409 times

2

Hello

I am building a content manager and I have a page where I return the results of the chosen country, so I can then update each field.

When choosing each country on the Countries.php page, I send the parameter to the Edit-Countries.php page. The results of each column appear normally and so far so good. The problem is when I submit the form I get the following error:

Notice: Undefined index: Edit in C: xampp htdocs Backoffice Edit-Paises.php on line 5

Here is the code of the Edit-Paises.php page

<?php
require_once 'db.php';
include 'constants.php';

$edit = $_GET['edit'];

$stmt = $mysqli->prepare("SELECT country_id, country_name, flag_file, 
header_img, intro FROM countries WHERE country_id = ? ORDER BY country_id");
$stmt->bind_param('s', $edit);
$stmt->execute();
$stmt->bind_result($id, $countryName, $flag, $headerIMG, $intro);
$stmt->store_result();
if($stmt->fetch()) {
if(!$stmt) {
    echo "Failed to execute: (" . $stmt->errno . ")" . $stmt->error;
}     
$stmt->close();
}

//Form for the country update    
$paisError = "";
$flagError = "";
$imgError = "";
$introError = "";
$contError = "";

$update_country = $_GET['edit'];

if(isset($_POST['btnEdit'])) {

$país = $_POST['país'];
$intro = $_POST['intro'];
$continente = $_POST['continente'];
$bandeira = $_POST['bandeira'];
$imagem = $_POST['imagem'];

if(empty($país)) {
    $paisError = "Insira um país";
} elseif(empty($intro)) {
    $introError = "Insira uma descrição";
} elseif(empty($continente)) {
    $contError = "Escolha o respectivo continente";
}  elseif(empty($bandeira)) {
    $flagError = "Insira uma bandeira";
}  elseif(empty($imagem)) {
    $imgError = "Insira uma imagem";
}  else {

$stmt_update = $mysqli->prepare("UPDATE `countries` SET `country_name` = ?, `id_continentes` = ?, `flag_file` = ?, `header_img` = ?, `intro` = ? WHERE `country_id` = '".$_GET['edit']."' ");
$stmt_update->bind_param('s', $update_country);
$stmt_update->execute();

if(!$stmt_update) {
    echo "Failed to execute: (" . $stmt->errno . ")" . $stmt->error;
}     
$stmt->close();
header('Location: thankyou.php');
}
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Países</title>
    <script src="js/jquery-3.1.0.min.js" type="text/javascript"></script>
    <script src="js/imgPrev.js" type="text/javascript"></script>
    <link href="css/editPais.css" rel="stylesheet" type="text/css"/>
</head>
<body>
    <?php
    include_once 'Menu.php';
    ?>
    <h1 id="heading">Editar País</h1>
        <form action="<?PHP echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
            <div class="editContent">
            <label for="Pais">País</label>
            <input type="text" name="país" value="<?php echo $countryName; ?>">
            <span class="error"><?php echo $paisError; ?></span>
            </div>

            <div class="editContent">
            <label for="Pais">Continente</label>
            <select type="text" name="continente">
                <?php
                $sql = "SELECT * FROM continentes ORDER BY id";
                $result = mysqli_query($mysqli, $sql);
                     while ($row = mysqli_fetch_assoc($result)) {
                     echo '<option value="'.$row['id'].'">'.$row['continente'].'</option>';
                          }
                ?>
            </select>
            <span class="error"><?php echo $contError; ?></span>
            </div>

            <div class="editContent">
            <label for="Pais">Bandeira</label>
            <img id="img-A" src="<?php echo $site_root;?>/images/16/<?php echo $flag; ?>"/>
            <input type="file" id="imgInp" name="bandeira">
            <span class="error"><?php echo $flagError; ?></span>
            </div>

            <div class="editContent">
            <label for="Pais">Imagem País</label>
            <img id="img-B" src="<?php echo $site_root;?>/images/country_header_images/<?php echo $headerIMG; ?>"/>
            <input type="file" id="imgP" name="imagem">
            <span class="error"><?php echo $imgError; ?></span>
            </div>

            <div class="editContent">
            <label for="Pais">Texto Intro</label>
            <textarea name="intro" rows="5"><?php echo $intro;  ?></textarea>
            <span class="error"><?php echo $introError; ?></span>
            </div>
            <div class="editContent">
            <button type="submit" id="btn_edit" name="btnEdit">Submit</button>
            </div>
        </form>         
</body>

The $Edit variable returns the data of the respective country. Because this error appears if it is not involved in the form submission?

Edit

I pass the 'Edit' parameter through this block of code on the Countries page.php:

<?php
         $query = "SELECT country_id, country_name FROM countries ORDER BY country_name";
         $result = mysqli_query($mysqli, $query);
         if(mysqli_num_rows($result) == 0) {
             echo '<tr><td cols="4">No rows returned</td></tr>';
         } else {
         while ($row = mysqli_fetch_assoc($result)) {
             echo '<tr><td>- '.$row['country_name'].'</td><td><a href="edit-Paises.php?edit='.$row['country_id'].'">Edit</a>|<a href="">Delete</a></td></tr>';
                }
         }
         ?>
  • I don’t see in any corner you setting the value of the parameter edit. Nor in the form nor how query stops.

  • I saw: país (with the same accent), continente, bandeira, imagem and intro. All parameters passed by the form

  • Dear @Jeffersonquesado I edited my question above. The Edit parameter comes from the page Countries.php, to show the results in editPaises.php. So far so good, except when sending the form.

  • Which link is the form directs? I particularly don’t know what the $_SERVER['PHP_SELF'] returns. If it returns only the path, without the param query that is passed by the previous page, then we have to parameter $_GET is only filled in the first time you open the page, but not when submitting to the form. That’s why I said I didn’t see the $_GET through your form

  • An alternative that I have seen in some JSP projects (and that could be used in your project) is the form being submitted to a URL that will process the data, with possible database insertions, to then redirect to the successful or error page (or, success and error are the same page, pass the appropriate parameters for its presentation)

  • I have done this by putting the processing of the form on another page but by submitting the form the page returns white. I’m probably not doing this line of my query right: "WHERE country_id = ?" I’ll have to identify a way for the code to recognize which parents are editing.

  • Regarding the form action, the $_SERVER['PHP_SELF'] is to continue on the same page and process the form.

  • "The problem is when I submit the form I get the following error", the answer is: as you do not save the $_GET['edit'] nowhere, by resubmitting the form in the POST method, the content of Edit no longer exists, so there is an indefinite Indice. To solve this, you can treat using a IF isset($_GET['edit']) or resubmit via Form via POST, so the content should be recovered through the $_POST['edit']

Show 3 more comments

2 answers

1

The same way you did:

<input type="text" name="país" value="<?php echo $countryName; ?>">

has to be made a:

<input type="hidden" name="cod_pais" value="<?= $_GET['edit']; ?>">
<!-- note que mudei o type de text para hidden, pois não precisa exibir-->

By doing this, when submitting the form, there also be the $_POST['cod_pais'] which is the same as the $_GET['edit´]... and I noticed here now also that you put the name country with accent. This is not a good practice, use accent.

From then on, I think I’ve had enough to see what you have to do.

  • Dear @Luiz, the error continues to appear even though @. As I answered above, even if I change the form sending method to GET, errors continue to appear and data is not sent.

  • I’ll rephrase my answer, but for that, you have to tell me which parameter name you send to edit-Paises.php. You have to set the code of the country chosen in any of the inputs in the form and this you did not by what I saw.

  • I already edited my question above with the code from where the parameter 'Edit' comes. However I put the Hidden input that you said but ends up returning the same Undefined index message of the variable $_GET['Edit'] referring to the line where the input is.

  • Putting this line of code: if(isset($_GET['Edit'])) { $Edit = $_GET['Edit']; } the error disappears. The problem is that the data is not being updated. I edited my query above.

0


This problem is occurring because the first time you call the script you are passing the country id through the attribute edit in the URL, but when calling the script again to update the data, in the action of your form the Edit attribute is not being sent, because the property $_SERVER['PHP_SELF'] returns only the script name, not the URI attributes.

Replace the action of your form as follows:

action="<?PHP echo htmlspecialchars($_SERVER['PHP_SELF']); ?>"

for

action="<?PHP echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']; ?>"

  • Dear @Ruhan O.B had already made this change before. In the first option, the errors continue and in the second when I search the data through $_POST, these do not appear...only appears the empty form.

  • Probably the error is continuing because when calling the page for the first time $_GET['edit'] does not exist yet, in this case just check if it exists before using, through the isset function, so do not accuse of error.

  • When doing isset, for some reason always returns the row 1 of the table, ie in this case always returns the results of Austria.

  • 1

    This problem is occurring because the first time you call the script you are passing the country id through the attribute edit in the URL, but in the action of your form the attribute edit is not being sent as the property $_SERVER['PHP_SELF'] returns only the name of the script, not the attributes of the URI. Try overwriting action="<?PHP echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" for action="<?PHP echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']; ?>"

  • So Notice disappears, even without the code I posted above in the reply to @Luiz . However the form submission is entering the error validation block for some reason, which I will now have to check.

  • Okay, I can update the data now. Dear Ruhan, thank you for your help.

  • Did the changes I suggested solve the problem, or was it something different that you used? Let me know so I can edit my answer with correct solution.

  • Yes. As for the data update, I forgot to put in the UPDATE query the variable $_GET['Edit] in the WHERE clause. Before it had "?" and so identifies which line(or country) to edit. You can see the QUERY in my question.

  • I get it, I’ll edit my answer so you can mark the answer and help someone else with the same problem.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.