I'm new to PHP. I added in the isset command, and the form is working with the database but every time I bring up this page it automatically submits a blank record to my database. How can I make it so that it only runs through the PHP commands if an input is entered and a user hits submit?
<?php
$handle = isset($_POST['handle']);
$address = isset($_POST['address']);
$code = isset($_POST['code']);
$rrr=mysqli_connect("localhost","knock_knock","whosthere","1");
if (mysqli_connect_errno()) {
echo "Connection to DB failed" . mysqli_connect_error();
}
$handle2 = mysqli_real_escape_string($rrr, $handle);
$address2 = mysqli_real_escape_string($rrr, $address);
$code2 = mysqli_real_escape_string($rrr, $code);
if(empty($handle)){
echo "Handle can not be empty";
}
$sql="INSERT INTO players (Handle, Address, Code)
VALUES ('$handle2', '$address2', '$code2')";
if (!mysqli_query($rrr,$sql)) {
die ('Error: ' . mysqli_error($rrr));
}
echo "Record added";
mysqli_close($rrr);
?>
$handle = isset($_POST['handle']);
$address = isset($_POST['address']);
$code = isset($_POST['code']);
the above code will store true in all the variables if the are set.it should be -
$handle = isset($_POST['handle']) ? $_POST['handle'] : false;
$address = isset($_POST['address']) ? $_POST['address'] : false;
$code = isset($_POST['code']) ? $_POST['code'] : false;
and all code that is supposed to be executed after the form submit should be placed in -
if (isset($_POST['submit'])) {
//code to be executed
}
submit or whatever the field is for submit button. and then the checks should be added for empty values.
you have to stop the execution or redirect.
if(empty($handle)){
header('location:page.php?msg=yourmessage');
exit;
}
or
if(empty($handle)){
echo "Handle can not be empty";
exit;
}
Put a simple if condition at the top
$handle =$_POST['handle'];
if(empty(isset($handle)) || $handle=='')
{
echo "Handle can not be empty";
}
else
{
//Your stuff
}
Related
I've been working for the past 5 hours on why does this if get triggered...
Let me show you the code and explain you :
<?php
require_once "ConnectDB.php";
$link2 = $link;
$key = $posthwid = "";
$err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["key"])){
$err = "Thanks for the ip (" .$_SERVER['REMOTE_ADDR']. "), have a good day! (1)";
}
else{
$key = trim($_POST["key"]);
}
$hwid = $_POST["hwid"];
if(empty($err)){
$sql = "SELECT hwid, idkey, length, created_at FROM money WHERE idkey = '" .$key. "'";
$row = mysqli_query($link, $sql);
if(mysqli_num_rows($row) < 2){
while($result = mysqli_fetch_assoc($row)) {
if($result["idkey"] == $key)
{
$err = "key";
if($result["hwid"] == "")
{
$err = "nohwid";
$sql2 = "UPDATE IceCold SET hwid = '" .$hwid. "' WHERE idkey = '" .$key. "'";
if(mysqli_query($link2, $sql2)){
$hwid = $result["hwid"];
mysqli_close($link2);
echo "debug";
}
else {
$err = "Oops! Something went wrong. Contact the support.";
}
}
if ($hwid !== $result["hwid"]) {
$err = "Contact the support";
}
elseif($_SESSION["admin"] == true) {
//Do special stuff
}
else {
///do other checks
if($created_at > $date){
$err = $hwid;
} else {
$err = "The key date is too old, buy a new one.";
}
}
}
else{
$err = "The key you entered was not valid.";
}
} mysqli_close($link);
} else {
$err = "multiple entry, contact support";
}
}
} else {
$err = "Thanks for the ip (" .$_SERVER['REMOTE_ADDR']. "), have a good day! (3)";
}
echo $err;
?>
So basically, I have this Connect DB file with a mysqli_connect called $link and I'm designing a liscence API for my program. My program will send a request with the "idkey" and "hwid" and is waiting for the hwid to come back. I have an entry in my sql databse with only a key registered and I've trying to make my program wotk by generating POST request with the id and a random hwid but I've found no success. If variables are weirdly moved around, It's because of the debugging.
Right now, with my current setup, I get the Contact the support response which I don't understand why?!? The request and the key are correct if I'm able to get this awnser.
It's probably a stupid mistake but I jsut can't figure it out...
Thanks in advance for your help
Edit: the if statement I'm referring to is this:
if($hwid !== $result["hwid"])
There was a typo in the code that I fixed but it wasn't the issue,
as for the elseif, that would destroy the order of execution of the code and destroy the logic behind it(If that made sense).
Weirdly, after some tests, I found out that the second SQL request I send doesn't want to be executed ($sql2) and there is no error in httpd logs... Can you execute two requests? I tried to create $link2 but it doesn't change anything
EDIT : Found solution
if($result["hwid"] == "")
{
$sql2 = "UPDATE money SET hwid = '" .$_POST["hwid"]. "' WHERE idkey = '" .$key. "'";
if(mysqli_query($link2, $sql2)) {
$newhwid = $_POST["hwid"];
mysqli_close($link2);
}
else {
$err = "Oops! Something went wrong. Contact the support.";
}
}
elseif ($_POST["hwid"] != $result["hwid"]) {
$err = "Contact the support";
}
if($_POST["hwid"] == $newhwid || $_POST["hwid"] == $result["hwid"] ) {
/// do other checks
}
The condition before that one, if($row['hwid'] = ""), is an assignment. This code is changing the value of $row['hwid'] to an empty string, causing the condition after it to be true. I assume you meant to write == to test if $row['hwid'] is empty; otherwise it doesn't make sense to write this as an if statement.
By the way, it's not clear whether this if statement shouldn't be an else if. The rest of the branches here are else if (or elseif, which is the same in PHP), so you should consider whether you have missed out an else on this one too.
When user clicks on the Save, check whether the data is successfully inserted record to the table, and display a proper message accordingly. If forms are empty then the error message should be shown and database should not have any record.
//SAVE
if (isset($_POST['SAVE'])) {
$Name = $_POST['name'];
$City = $_POST['city'];
$query = "Insert Into Info Values('$Name','$City')";
$result = mysqli_query($con, $query) or die ("query is failed" . mysqli_error($con));
$Name = '';
$City = '';
if(mysqli_affected_rows($con)>0) {
echo "record is saved";
}else {
echo "record is not saved";
}
I can only do validation through php. I am not sure if I am doing this right. So far I can get the "record is saved" message on my form, but I cannot get the latter if the form are empty. It just make an empty record in my database.
Untested Code:
if (!isset($_POST['SAVE'], $_POST['name'], $_POST['city'])) { // avoid Notices
echo "Missing required submission data";
} elseif (!strlen(trim($_POST['name']))) { // validate however you wish
echo "Name data is not valid"; // explain however you wish
} elseif (!strlen(trim($_POST['city']))) { // validate however you wish
echo "City data is not valid"; // explain however you wish
} elseif (!$con = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $con->connect_error <-- never show actual error details to public
} elseif (!$stmt = $con->prepare("INSERT INTO Info VALUES (?,?)")) {
echo "Error # prepare"; // $con->error; // don't show to public
} elseif (!$stmt->bind_param("ss", $_POST['name'], $_POST['city'])) {
echo "Error # bind"; // $stmt->error; // don't show to public
} elseif (!$stmt->execute()) {
echo "Error # execute"; // $stmt->error; // don't show to public
} else {
echo "Insert Successful";
}
The validation conditions on the submission data ensure that the values are not empty and they are not completely comprised of whitespace characters. If you wish to refine the validation requirement further, just update the conditions.
If you want to simply ensure that $_POST['name'] and $_POST['city'] are not empty, you can replace the first three conditionals with
if (empty($_POST['SAVE']) || empty($_POST['name']) || empty($_POST['city'])) {
echo "Submission data is missing/invalid";
}...
If you don't use a prepared statement, then name values like Paul O'Malley will break your query. Worse, if someone wants to try to run some injection attacks, your query is vulnerable.
Checking affected_rows() is unnecessary. If there is no error message from the query execution, the INSERT query was a success.
The above suggestions are all best practices which I urge you to adopt.
Checking isset($_POST['SAVE']) only tells you if "SAVE" is set. It does not tell you if the fields have values.
To do the validation in PHP, use something like the following:
if (isset($_POST['SAVE'])) {
$Name = $_POST['name'];
$City = $_POST['city'];
if ($Name && $City)
{
//...
//code to insert data into the database goes here
//...
if(mysqli_affected_rows($con)>0) {
echo "record is saved";
}else {
echo "record is not saved (error saving)";
}
} else {
echo "record is not saved (input was empty)";
}
}
The key being the if ($Name && $City) check.
Alternately, if you want to rely on mysql to reject the insert on blank values, then make sure the fields in the mySql table are not nullable and then change this part of your code: (but this would be moving the validation to MySql)
$Name = $_POST['name']?$_POST['name']:null;
$City = $_POST['city']?$_POST['city']:null;
This is what I have and it's not working. I need to check if the fields in Your_Location.php is empty. If it is, throw an error. If not; run the query as follow. It would work if I throw in //if (!mysqli_query($conn,$sqlinsert))
<?php
//session_start();
include 'dbConfig.php';
include 'Your_Location.php';
$childfirst = $_POST['element_1'];
$childlast = $_POST['element_2'];
$childdobyear = $_POST['element_3_3'];
$childdobmon = $_POST['element_3_1'];
$childdobday = $_POST['element_3_2'];
$childbaptize = $_POST['element_4'];
$childrelationship = $_POST['inputrelation'];
$childdob = "$childdobyear-$childdobmon-$childdobday";
$sqlinsert="INSERT INTO memchild (ID, FirstName, LastName, DOB, Baptize, Relationship)
VALUES
('$getid2','$childfirst','$childlast','$childdob','$childbaptize','$childrelationship')";
//Build arrays of fields
$required = array('element_1', 'element_2', 'element_3_3', 'element_3_2', 'element_3_1', 'elelment_4', 'inputrelation');
//Loop to check for empties
$error = false;
foreach($required as $fields) {
if(empty($_POST[$fields])){
$error = true;
}
}
if($error){
Sleep(3)
?>
<script>
document.getElementById('li_9').innerHTML = '* $childfirst Make sure the fields are not empty.';
</script>
<?php
exit();
}Else{
mysqli_query($conn,$sqlinsert)
?>
<script>
document.getElementById('li_9').innerHTML = '$childfirst $childlast has been added.';
</script>
<?php
sleep(3);
echo "<meta http-equiv='refresh' content='0'>";
}
?>
First try to check if the keys actually exist.
$childfirst = isset($_POST['element_1'])? $_POST['element_1'] : null;
secondly, you can check what field is not filled in:
$errorMessage = '';
foreach($required as $key) {
if(empty($_POST[$key])){
$error = true;
// break; // Uncomment if you want to exit the loop if one field is not set
// $errorMessage .= $key . ' is not filled in'; // Uncomment if you want to add message for every missing key
}
}
for your scripts, you are trying to combine PHP value with javascript, you need to actually echo or print the value like this:
<script>
document.getElementById('li_9').innerHTML += "* <?php echo $childfirst;?> Make sure the fields are not empty.";
</script>
and also for the second one
<script>
document.getElementById('li_9').innerHTML += "<?php echo $childFirst . ' ' . $childLast;?> has been added.";
</script>
Hey your error is you passing string values to check and its not empty already
change this line
$required = array('element_1', 'element_2', 'element_3_3', 'element_3_2', 'element_3_1', 'elelment_4', 'inputrelation');
to
$required = array("$element_1", "$element_2");
Add the other elements too
And change this too
foreach($required as $fields) {
if(empty($fields)){
$error = true;
}
}
Hope it works for You
so I have searched this problem and found similar ones, but I'm not sure of how to translate their solutions into mine - mainly because I'm a noob in PHP. I'm working on it. Bear with me. I appreciate the help!
Right now, I am trying to make it so my form will not allow duplicate entries for the email column in phpmysql. So far, I went into the structure tab there, and made it unique. Pretty much viola. However, I would like the error message to display on the same page when the form is submitted, instead of reloading it and giving the message. Also, I would like to customize the message. Seeing as its a phpmysql related error, I'm not sure if I would do that with PHP coding, or somewhere in there.
Thanks guys. I appreciate the help.
<?php
function checkField($v){
return (isset($v) && $v === false) ? true: false;
}
function startMysql(){
$con=mysqli_connect("localhost", "shiftedr_admin", "passwerd", "shiftedr_whosthedeeusers");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return null;
}
return $con;
}
// function closeMySql($connection){
// mysqli_close($connection);
// }
function formcheck(){
$con=mysqli_connect("localhost", "shiftedr_admin", "shithead1", "shiftedr_whosthedeeusers");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
if (isset($_POST['submitted'])){
$form = null;
if (empty($_POST['fullname'])){
$form['fullnameflag'] = false;
}
if (empty($_POST['email'])){
$form['emailflag'] = false;
}
if (empty($_POST['password'])){
$form['passwordflag'] = false;
}
if (empty($_POST['pwc'])){
$form['pwcflag'] = false;
}
if (empty($_POST['userbday'])){
$form['userbday'] = false;
}
if (empty($_POST['gender'])){
$form['genderflag'] = false;
}
if ($_POST['password'] != $_POST['pwc']){
$form['fixpasswordconfirm'] = false;
}
/*$query = mysql_query ("SELECT * FROM users2 WHERE email = '". Email'" ."'");
if (mysql_num_rows($query) > 0)
{
echo 'Email Address is Already In Use.';
}*/
if (empty($form)) { // all fields correct at this point, do database stuff
$sql="INSERT INTO Users2 (fullname, Email, Password, userbday, Gender) VALUES ('".$_POST['fullname']."','".$_POST['email']."','".$_POST['password']."','".$_POST['userbday']."','".$_POST['gender']."')";
if (!mysqli_query($con,$sql)){
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
}
mysqli_close($con);
return $form;
}
}
//// / include("myfunctions.php");
?>
I am guessing you have two pages - myform.php and process.php or something similar so try doing this
<?php
$error = null;
if( isset( $_POST['submitted'] ) ) // Same as your check is submitting if
{
// Below is an example fail
if( empty( $_POST['fullname'] ) ) $error = 1;
// So for the email address failing you would put
if( mysql_num_rows($query) > 0 ) $error = 2;
if(! $error )
{
// all good no errors here so do database stuff....
}
else
{
header("Location: form.php?error=$error"); // return the error code to previous page
}
}
?>
Were one could be an empty field or could be fullname is empty and two is used email address or something similar and on your myform.php page have
<?php
if( isset( $_GET['error'] ) )
{
switch ( $_GET['error'] )
{
case 1 : echo "One of the fields is empty"; break;
case 2 : echo "Your email address has already been used"; break;
default : echo "Unknown error occured";
}
}
?>
(Sorry for my bad english)
Well, I've 3 errors in my code.
Error's:
First of all it's show : Notice: Undefined index: form in C:\xampp\htdocs\evantechbd\index.php on line 461. When i run this form.
if any error found it's show error message, well, but correct field is empty. Example: In this form there is 4 fields. a) upload image, b) select discussion c) subject and d) message. Suppose you upload a image, select a discussion and write a subject but forgot to write message. Then It's show "Message Required" and every filed is empty. I don't want empty field which is correct.
After successfully submitted the form it's show "Discussion was submitted ". But after that if i refresh the page it's send the data to database. But I did not click submit button. why this happen?
Here is my code:
<?php
if ($_POST['form'] == "Submit") {
$err = array();
$filed = addslashes($_FILES['file']['tmp_name']);
$img_named = addslashes($_FILES['file']['name']);
$img_type = addslashes($_FILES['file']['type']);
#$imgd = addslashes(file_get_contents($_FILES['file']['tmp_name']));
function getExtension($str)
{
$i = strrpos($str, ".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str, $i + 1, $l);
return $ext;
}
$extension = getExtension($img_named);
$extension = strtolower($extension);
$image_named_uniq = uniqid() . '.' . $extension;
$upload_path_dis = 'user/manage/discussionimg/';
$diss = $_POST['type'];
$sub = $_POST['sub'];
$msg = $_POST['msg'];
$date = "On " . date("F Y h:i:s A");
if (!isset($_SESSION['uname']))
$err[] = "You need to login";
else {
$uname = $_SESSION['uname']; //session username
if (empty($sub) && empty($msg) && empty($filed))
$err[] = "All field required";
else {
if (empty($sub))
$err[] = "Subject Requried";
if (empty($msg))
$err[] = "Message Requried";
if (empty($filed))
$err[] = "SORRY, you have to be upload a image";
}
}
if (!empty($err)) {
foreach ($err as $er) {
echo "<font color=red>$er</font><br/>";
}
}
else {
$sql = mysql_query("INSERT INTO discussion VALUES ('', '$imgd', '$image_named_uniq',
'$diss', '$sub', '$msg', '$uname', '$date' ) ");
if (!$sql)
echo "Can't submit your discussion" . mysql_error();
if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_path_dis . $image_named_uniq)) {
die('File Not Uploading');
} else {
echo "Discussion was submitted";
}
}
}
?>
Many Thanks for your help!!
Kanta.
Try changing your first if condition as follows
if (isset($_POST['submit']))
Now most of web sites uses client side validations using javascript. You can use jquery frame work to make things easier. However since you already uses validations after the POST event. You have to set values to relevant fields as bellow code. It will set tha value of the subject.
<input type="text" name="sub" value="<?php if(isset($_POST["sub"])) echo $_POST["sub"]; ?>" size="46"/>
Yes if you refresh the code it will again do the post and insert. You have to do few controls. However these things depend on your data.
a. Make unique key indexes in the database
b. Check for existing record before the insertion.
c. Redirect your page to the same page after few seconds once the user see the successful message.