0

I am making a very simple movie database, with the possibility to update the movies that are in it. All you have to do is fill in the fields underneath the table. However, when you fill in the id and only one other field, like film_id, the description etc. are erased from the table. How do i make sure that it's possible to change only one thing?

The code for the page:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>

<?php
session_start(); //Start sessie.
function is_logged() {
if (isset($_SESSION['username'])) return true;
return false; //De gebruikersnaam wordt gecontroleerd
}
if(!is_logged()){
header("Location: sign-in.php"); //Als de gebruiker naar overzichtlogin.php 
gaat, zonder dat hij of zij is ingelogd, worden ze doorgestuurd naar de 
login pagina.
}

require_once('db_const.php'); //De gegevens voor het maken van de verbinding 
met de database staan in dit bestand gedeclareerd.
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if  (!$mysqli){
die("Connection failed: ".mysqli_connect_error()); //Als de verbinding niet 
lukt zal deze niet werken.
}

?>

 <?php $current = 'secured'; ?> <!-- Om aan te geven dat men zich op de 
beveiligde overzichtspagina bevindt, wordt gebruik gemaakt van deze 
variabele. Current krijgt nu de waarde 'secured', waardoor de button waar 
'secured' staat een kleur krijgt. -->


<div class="header">
<?php
if(isset($_SESSION['username'])){
require_once("headersecured.php"); //Indien de gebruiker ingelogd is, wordt 
'headersecured.php' gebruikt als header.
}else{
require_once("header.php"); //Indien de gebruiker niet is ingelogd, wordt 
header.php gebruikt als header.
}
?>
</div>



<h1>Filmoverzicht</h1>

<?php
$sql = "SELECT film_id, title, description, release_year, rating FROM 
 films"; //De gewenste gegevens uit de database worden geselecteerd.
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
echo "<table style='border: solid 1px grey; margin-left: auto; margin-right: 
auto; margin-top:50px;'><tr><th>ID</th> <th>Titel</th> <th>Beschrijving</th> 
<th>Jaar</th> <th>Rating</th> <th> </th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" .$row["film_id"] . "<td>"  .$row["title"] . "<td>" . 
$row["description"] . "<td>" . $row["release_year"]. "<td> " . 
$row["rating"]. "<td> " . '<td><a class="alert" href="deletemovie.php?
id='.$row['film_id'].'" >
</i>'?> VERWIJDER <?php '</a></td>';
} //De beschikbare gegevens worden weergegeven.

echo "</table>";
} else {
echo "0 results";
}

?>

<br><br>

<form method="post" action="<?php $_SERVER["PHP_SELF"]; ?>"> <!--De 
bewerkfunctie wordt op dezelfde pagina uitgevoerd.-->


<h2>Films bewerken</h2>


<input name="film_id" required="required" placeholder="ID">

<input name="title" placeholder="Titel film">

<textarea id="textarea" name="description" cols="20" rows="5" 
placeholder="Beschrijving"></textarea>

<input name="release_year" placeholder="Uitkomstjaar">

<input name="rating" placeholder="Beoordeling">

<input id="submit" name="submit" type="submit" value="Wijzigen"> <!-- In 
deze 
invulvelden kunnen nieuwe gegevens worden ingevoerd, zodat de films worden 
aangepast. -->

<?php
if (isset($_POST['submit'])) {
$film = $_POST["film_id"]; //Slaat de gegevens voor het ingevoerde ID op in 
een 
variabele.
$title = $_POST["title"]; //Slaat de gegevens voor de ingevoerde titel op in 
een 
variabele.
$description = $_POST["description"]; //Slaat de gegevens voor de ingevoerde 
beschrijving op in een variabele.
$year = $_POST["release_year"]; //Slaat de gegevens voor het ingevoerde jaar 
op 
in een variabele.
$rating = $_POST["rating"]; //Slaat de gegevens voor de ingevoerde rating op 
in een variabele.

$sql = "UPDATE films SET film_id = '$film', title = '$title', description = 
'$description', release_year = '$year', rating = '$rating' WHERE film_id = 
$film"; //De tabel 'films' in MySQL wordt geselecteerd, de gegevens die in 
de 
variabelen zijn opgeslagen worden gewijzigd in de database.

if (mysqli_query($mysqli, $sql)) { // Voert de actie uit
  echo "<br>"; // Wit ruimte
  echo "<br>"; // Wit ruimte
  echo "<br>"; // Wit ruimte
  echo "Succesvol aangepast!"; // Geeft aan dat het aangepast is
  echo "<br>"; // Wit ruimte
  echo "<a href='overzichtspagina.php'>Terug naar de vorige pagina.</a>"; // 
 een link waar de gebruiker terug kan gaan naar de vorige pagina
  } else {
  echo "Error: " . $sql . "<br>" . mysqli_error($mysqli); // geef fout 
melding aan de gebruiker als het mis gaat
  }
}

 ?>


</form>


<?php

$mysqli->close(); //Verbinding wordt verbroken.

?>


<div class="footer">
<?php include 'footer.php';?> <!-- De footer wordt opgehaald. -->
</div>

</body>
</html>
  • 1
    (1) You could allow the user to choose from a select dropdown the option they want to make the update for. Pass the text field and the dropdown value to the PHP code for it to identify the field to update. (2) Change your update query to have only one field (the query will either have to be constructed conditionally or you'll need four versions of the query for updating one field at a time). (3) Please prefer using [MySQLi Prepared Statements](http://php.net/manual/en/mysqli.prepare.php) to secure your code from [SQL Injection Attacks](https://stackoverflow.com/q/60174/2298301). – Dhruv Saxena May 23 '17 at 18:35

2 Answers2

0

The problem is when the $_POST["description"] is not defined the value of $description is taken as NUll. In order to avoid this the Update query has to be constructed dynamicaly.

$sql = "UPDATE films SET film_id = '$film', title = '$title'";
if(isset($_POST["description"])) {
    $description = $_POST["description"];
 $sql .= ", description = $description"
}
$sql .= ", release_year = '$year', rating = '$rating' WHERE film_id = $film";

In this case when the $_POST["description"] is not set the query becomes "UPDATE films SET film_id = '$film', title = '$title', release_year = '$year', rating = '$rating' WHERE film_id = $film"; or else the query becomes "UPDATE films SET film_id = '$film', title = '$title', description = $description, release_year = '$year', rating = '$rating' WHERE film_id = $film";

  • How should I do it if I want to do this with every single one of them? So also with film_id, title, release_year and rating? I tried it a few times by using your code but I couldn't do it. – Yvonne Blok May 23 '17 at 19:04
  • For each element you need to check if the value exists and construct the query accordingly. Here I have checked if $_POST["description"]) is set and the update query contains `description = $description"` only if the description is set. Similarly you may have to check for each element. – Vidhyashankar Madheswaraswamy May 24 '17 at 05:00
  • At this moment I have copied the code en changed all variables so that they match the variables declared earlier. The code for the sql statement starts like this: $sql = "UPDATE films SET "; if(isset($_POST["film_id"])) { $film = $_POST["film_id"]; $sql .= ", film_id = $film"; } The second part, where the if statement begins is repeated for every variable. This still doesn't work. – Yvonne Blok May 24 '17 at 13:12
  • May be you should try printing the SQL query and check if it has valid syntax. – Vidhyashankar Madheswaraswamy May 25 '17 at 05:21
0
  • You have to check on multiple values for validation, because you want that at least one field (other than film ID) is completed. If none provided, than notify the user. This validation should be made on client-side (with js, jquery, validation plugins, etc).
  • Then, you must dynamically build your sql statement. Use sprintf() function for such "complex" constructs. It's very elegant. In it, the %s parts are placeholders for the variables.
  • Please notice the UPDATE statement: you don't want to update the film_id field! You must use it ONLY to select the one record which you want to update (e.g. just in WHERE clause). If you want to change film_id, you must reinsert a record with the new id.
  • You are missing the <body> tag.
  • I was bringing last php code UNDER the </form> tag.
  • As a general rule: separate display logic from server processing.

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8">
        <title>My films</title>
    </head>
    <body>

        <?php
        $mysqli = new mysqli('localhost', 'root', 'root', 'tests');
        if (!$mysqli) {
            die("Connection failed: " . mysqli_connect_error());
        }
        ?>

        <!-- ... -->

        <form method="post" action="<?php $_SERVER["PHP_SELF"]; ?>">
            <h2>Films bewerken</h2>
            <input name="film_id" required="required" placeholder="ID">
            <input name="title" placeholder="Titel film">
            <textarea id="textarea" name="description" cols="20" rows="5" placeholder="Beschrijving"></textarea>
            <input name="release_year" placeholder="Uitkomstjaar">
            <input name="rating" placeholder="Beoordeling">
            <input id="submit" name="submit" type="submit" value="Wijzigen">
        </form>

        <?php
        if (isset($_POST['submit'])) {
            $film = $_POST["film_id"];
            $title = $_POST["title"];
            $description = $_POST["description"];
            $year = $_POST["release_year"];
            $rating = $_POST["rating"];

            $message = '<br/><br/><br/>';

            if (!isset($film)) {
                $message .= 'You must provide the film ID!';
            } elseif (
                    (!isset($title) || empty($title)) &&
                    (!isset($description) || empty($description)) &&
                    (!isset($year) || empty($year)) &&
                    (!isset($rating) || empty($rating))
            ) {
                $message .= 'You must provide at least one field for the selected film ID!';
            } else {
                $sql = sprintf(
                        "UPDATE films SET %s%s%s%s WHERE film_id = %s"
                        , isset($title) ? "title = '$title'" : ""
                        , isset($description) ? ", description = '$description'" : ""
                        , isset($year) ? ", release_year = '$year'" : ""
                        , isset($rating) ? ", rating = '$rating'" : ""
                        , $film
                );

                if (mysqli_query($mysqli, $sql)) {
                    $message .= "Succesvol aangepast!";
                    $message .= "<br>";
                    $message .= "<a href='overzichtspagina.php'>Terug naar de vorige pagina.</a>";
                } else {
                    $message .= "Error: " . $sql . "<br>" . mysqli_error($mysqli);
                }
            }

            echo $message;
        }


        $mysqli->close();
        ?>

    </body>
</html>

EDIT 1:

I recommend you to use exception handling. Here is an example:

try {
    // Connect to db.
    $mysqli = new mysqli('localhost', 'root', 'root', 'tests');
    if (!isset($mysqli) || !$mysqli) {
        throw new Exception("Connection failed: " . mysqli_connect_error());
    }

    // Run query on db.
    $query = mysqli_query($mysqli, $sql);
    if (!$query) {
        throw new Exception('The statement can not be executed!');
    }

    $mysqli->close();
} catch (Exception $exception) {
    echo $exception->getMessage();

    /*
     * OR display the whole error information.
     * But only in the development stage!
     */
    // echo '<pre>' . print_r($exception, true) . '</pre>';

    exit();
}
  • Don't forget to add a <title> tag to your page.