1

Why I'm getting an undefined index when declaring variables? Currently using bootstrap.

<?php 

 mysql_connect("localhost", "root", "1234") or die(mysql_error());
 mysql_select_db("newitems") or die(mysql_error());

 $up =  $_POST['update']; 
 mysql_query("UPDATE announcements SET content = $up");


 ?>
 <div class="well well-small text-center">
 <h3>Create an Announcement / Reminder:<br>

 <form class="form-group" id="form-mahasiswa" method="POST" action="ad_post.php">

  <div class="control-group">

    <div class="controls">

        <textarea id="update" name="update"></textarea><br>
        
        <button id="annbtn" class="btn btn-success">Update Announcement</button>

    </div>

</div>
Rajeev Singh
  • 1,724
  • 1
  • 6
  • 23
  • You are using the variable $_POST['update']; which is not set until you post the form. – Jens W Nov 17 '14 at 18:36
  • What do i need to do? – Kim Octaviano Nov 17 '14 at 18:38
  • 1
    Does this answer your question? ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – Nico Haase Oct 18 '21 at 07:22

1 Answers1

1

The update should only take place when you submit the form. Wrap your code inside this condition:

if ($_SERVER['REQUEST_METHOD'] == POST && isset($_POST['update']) { 
   $up = $_POST['update']; 
   mysql_query("UPDATE announcements SET content = $up");
}
Jens W
  • 188
  • 6
  • Also the mysql_* functions are deprecated so consider using the mysqli_* functions. http://php.net/manual/de/book.mysqli.php – Jens W Nov 17 '14 at 19:36
  • And finally it's highly recommended to filter input before using in a query :-) http://php.net/manual/de/function.filter-input.php – Jens W Nov 17 '14 at 19:39