phpwordpressinsert-query

PHP page inserts a blank record as soon as user visits page. Why?


I have this basic php insert script working fine and it will insert the form perfectly once the user hits submit. However, for some reason it also submits a record when the user simply visits the page before they even hit submit. Right away at the top it echoes "Entry Successful" before the user even does anything. There will be a blank record in the database. Why is this happening?

As a bonus question...can I prevent sql injection buy simply adding some mysql_escape code to various parts of this? It is a WordPress page, so is that even necessary?

<?php
$user_ID = get_current_user_id();

$hostname = "******";
$username = "******";
$dbname = "******";
$password = "*****";

//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("Unable to 
connect to database! Please try again later.");
mysql_select_db($dbname);

// Get values from form 
$genre = $_POST['genre'];
$movie_name = $_POST['movie_name'];
$movie_text = $_POST['movie_text'];


$query = "INSERT INTO movies (ID, genre, movie_name, movie_text)  VALUES
('$user_ID','$genre','$story_name','$story_text')";
$result = mysql_query($query);

if($result)
{
echo("
Entry Succesful");
}
else
{
echo("
failed to start");
}

?>

Get started!
<br><br>
<form name="movie" action="" method="post">

What type of movie? <select name="genre">
<option value="">Select...</option>
<option value="Comedy">Comedy</option>
<option value="Drama">Drama</option>

</select>

Name of Movie: <input type="text" size="55" name="movie_name">

<textarea rows="30" cols="80" name="movie_text" rows="4"></textarea>

<input type="submit" name="submit" id="submit" value="Add movie" />
</form>

Solution

  • "However, for some reason it also submits a record when the user simply visits the page before they even hit submit."

    Wrap your code inside an (if) isset() conditional statement, using your (named) submit button as a reference:

    <?php
    
        if(isset($_POST['submit'])){
        $user_ID = get_current_user_id();
        ...
    
    else
    {
    echo("
    failed to start");
    }
    
        } // end brace for if(isset($_POST['submit']))
    ?>
    
    Get started!
    <br><br>
    <form name="movie" action="" method="post">
    <input type="submit" name="submit" id="submit" value="Add movie" />
    
    ...
    
    </form>
    

    As far as SQL injection goes, visit:

    on Stack.