开发者

How to check if a value was entered, and if it wasn't-do not insert it into db?

Form1.php

<?php
if(isset(".$_POST[fname].", ".$_POST[lname].", ".$_POST[mail]."))
{$query = "INSERT INTO table1 (fname, lname, mail) VALUES ('".$_POST[fname]."', '".$_POST[lname]."', '".$_POST[mail]."')"; 
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());}
else{
    echo "No Values To Insert";
}
?>开发者_如何学JAVA;

I'm trying to check if the value was set, and if it wasn't-throw an error without inserting into DB.

Help?


Try

if ( isset ($_POST['fname']{0}) and isset( $_POST['lname']{0}) and isset( $_POST['mail']{0}) ){
   // Insert into db
}
else{
   echo "Please fill all the feilds";
}

What happens here is even if the user didnt enter any value into the fname feild, still the $_POST['fname'] will be set. So the isset ($_POST['fname']) will always return true if the form was submitted.

But when you check for isset ($_POST['fname']{0}) you are making sure that atleast one charater is entered and the feild is not empty. you can also use an is_empty but this is much better way.

Also The catch in using this is "{}" are going to be removed in php version 6. so if you are planning to upgrade your servers in the future then this might cause a small problem. But using "[]" instead of "{}" will solve that problem in php version 6.


Sorry, i read the heading of the question and mis-understood. What you have for code should work for catching failed inserts (though I recommend breaking off a test against the mysql_error instead of an or die(...)`. But, you can do an insert based on if the value already exists in the database by using this page as a reference

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜