ok well i have this code working fine, theres just one thing if the fields are empty it still gets inserted into the database i tried adding this code in so it echos but wont cause a error: <? If (empty($_POST[’name’])) { echo 'Please enter a name'; } ?> PHP: here is the main script. <?php $host=""; // Host name $username="users"; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name="test_mysql"; // Table name ?> <?php // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // Get values from form $name=$_POST['name']; $lastname=$_POST['lastname']; $email=$_POST['email']; // Insert data into mysql $sql="INSERT INTO $tbl_name(name, lastname, email)VALUES('$name', '$lastname', '$email')"; $result=mysql_query($sql); // if successfully insert data into database, displays message "Successful". if($result){ echo "Successful"; echo "<BR>"; echo "<a href='insert.php'>Back to main page</a>"; } else { echo "ERROR"; } // close connection mysql_close(); ?> PHP:
you can also use following code if ( $_POST['NAME'] == ''" && !isset($_POST['name'])) echo "Please enter name"; }
IMO, you should not code anything for your site where the basic functionality would depend on javascript. If someone has javascript turned off, then your site automatically breaks. Javascript is best left for extra frill type things. Just my $.02.
if($_POST['key'] == null) always works well for me. I also don't see your "else" statement. Don't forget to mysql_real_escape_string your $_POST vars, lest someone pulls a little johny DROP TABLE `users` on your database. if(isset($_POST['submit_key'])) { if($_POST['key']== null) { echo("<p>Errored!</p>"); writeForm(); } else { $var = mysql_real_escape_string($_POST['key']); // do some stuff } Code (markup):
^ Listen to this guy. Don't ever rely on Javascript. It might work, but using isset() is better. Because if $_POST['key'] is not set when comparing to NULL, it'll trigger an E_NOTICE, which isset() won't. That's the same in green. It's being inserted because nothing stops the script if there's no name. Put an exit() under the echo error line. (That's the easiest way - not the most beautiful.)
Since it's being posted by a form, [maybe] by default it will be "set" to an empty string. I've had some problems using !isset on $_POSTs. You can always fall back on !isset(key) || key == null.
That code won't work, what you want is: if (!isset($_POST['name']) || trim($_POST['name']) == "" ) ... Code (markup): Seeing as it is something you'll use a lot it is probably best to write a function: function isBlank($key) { return(!isset($_REQUEST['name']) || trim($_REQUEST['name']) == ""); } ... if(isBlank('name')) { echo "Please enter name:"; .... } Code (markup):