0

I've been trying to create an update form. The idea is that a few links in my website should change upon update. I've managed to do it, but what I want is for the 'echo "Changes successfully made!"' in the end of the form to show up only once.

 <?php 
//credentials
if (isset($_POST["submit"])){
    $server = 'server';
    $user = 'user';
    $pw = 'password';
    $BD = 'db-of-mine';

    //estabelece a conexão
    $conn = mysqli_connect($server, $user, $pw, $BD);
    if (!$conn) {
        die ('<span style="color: #FF0000;">"connection failed: "</span>' .  mysqli_connect_error());
    }

    $home = $_POST["home"];
    $apendix = $_POST["apendix"];
    $sobre = $_POST["sobre"];
    $contato = $_POST ["contato"];

    $query1 = "UPDATE form SET home= '$home' WHERE id='1'";
    $query2 = "UPDATE form SET apendix= '$apendix' WHERE id='1'";
    $query3 = "UPDATE form SET sobre= '$sobre' WHERE id='1'";
    $query4 = "UPDATE form SET contato= '$contato' WHERE id='1'";

    //$query = "INSERT INTO form (home, apendix, sobre, contato) VALUES ('$home', '$apendix', '$sobre', '$contato')";

    if (mysqli_query($conn, $query1)){
        echo "Changes successfuly made!";
    } else {
        echo "ERROR" . $query . "<br>" . mysqli_error($conn);
    }

    mysqli_close($conn); 
}
?> 

The query above changes only the "home" value. I've managed to change them all through copying and pasting if (mysqli_query($conn, $query[number])); for instance, query2, query3, query4 etc.

But when I do this, the success message appears four times. I'd like to be able to change them all at once and for the message to appear only once.

Also, if it would be possible, I'd like for the values not to go blank if the forms be left empty, which is also a problem I am having.

Thanks in advance :D

chris85
  • 23,846
  • 7
  • 34
  • 51
Paulo Soares
  • 177
  • 3
  • 18

1 Answers1

1

All these updates can be done as one query

$query1 = "UPDATE form SET home= '$home' WHERE id='1'";
$query2 = "UPDATE form SET apendix= '$apendix' WHERE id='1'";
$query3 = "UPDATE form SET sobre= '$sobre' WHERE id='1'";
$query4 = "UPDATE form SET contato= '$contato' WHERE id='1'";

Can be written as

$query = "UPDATE form SET 
            home= '$home',
            apendix= '$apendix',
            sobre= '$sobre',
            contato= '$contato'
          WHERE id='1'";

Although I have to mention that your script is at risk of SQL Injection Attack Have a look at what happened to Little Bobby Tables Even if you are escaping inputs, its not safe! Use prepared parameterized statements

Can I suggest that you look at a basic SQL tutorial

Community
  • 1
  • 1
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149