require_once('mysqli_connect.php');
$errors = array();
if(empty($_POST['senFirstName']) && empty($_POST['senLastName'])
&& empty($_POST['recFirstName']) && empty($_POST['recLastName'])
&& empty($_POST['proName']) && empty($_POST['proWeight'])
&& empty($_POST['traNo']) && empty($_POST['shipDate'])
&& empty($_POST['deliDate'])) {
$errors[] = 'Please make sure you type in all the information.';
}
else {
$sfn = mysqli_real_escape_string($dbc, trim($_POST['senFirstName']));
$sln = mysqli_real_escape_string($dbc, trim($_POST['senLastName']));
$rfn = mysqli_real_escape_string($dbc, trim($_POST['recFirstName']));
$rln = mysqli_real_escape_string($dbc, trim($_POST['recLastName']));
$pn = mysqli_real_escape_string($dbc, trim($_POST['proName']));
$pw = mysqli_real_escape_string($dbc, trim($_POST['proWeight']));
$traNo = mysqli_real_escape_string($dbc, trim($_POST['traNo']));
$shipDate = mysqli_real_escape_string($dbc, trim($_POST['shipDate']));
$deliDate = mysqli_real_escape_string($dbc, trim($_POST['deliDate']));
$status = mysqli_real_escape_string($dbc, trim($_POST['status']));
$shiptype = mysqli_real_escape_string($dbc, trim($_POST['shiptype']));
}
if(empty($errors)) { // If everything's OK.
$query = "SELECT traNo, CONCAT(recFirstName, ' ', recLastName) AS recieverName, proName, CONCAT(senFirstName, ' ', senLastName) AS senderName, status, shiptype FROM tracking, rel_tracking_reciever, reciever, product, sender
WHERE traNo='$traNo' AND tracking.traId = rel_tracking_reciever.traId AND reciever.recId = rel_tracking_reciever.recId AND tracking.proId = product.proId AND tracking.senId = sender.senId";
$result = #mysqli_query($dbc, $query);
$num = mysqli_num_rows($result);
if ($num) { // tracking number was found
while ($row = mysqli_fetch_array($result,MYSQL_ASSOC)) {
echo '<div id="error">';
echo "<p>This tracking number <b>{$row['traNo']}</b> has already been assigned to <b>{$row['senderName']}</b></p>\n";
echo '</div>';
}
mysqli_free_result ($result); // Free up the resources.
}
1) I want to validate input box with the multiple IF conditions using && Logical expression but instead, it submits empty forms into the database.
Note: I purposely left out the shipment and status input box because the options cannot be empty by default.
2) Is there a way i can generate the tracking number automatically without typing it manually. I have tried GUID but am not getting it.
Thanks..
You have to set ids that you want to validate - there is no complain.
You can do this with:
$ids = array('senFirstName', 'senLastName', 'recFirstName', 'recLastName' /* ... and more */);
$valid = true;
foreach ( $ids as $id ) {
if ( empty($_POST[$id]) ) {
$valid = false;
}
}
if ( $valid === true ) {
// everything's ok
} else {
$errors[] = 'Please make sure you type in all the information.';
}
You need ||, not && if you want to test, if one is empty.
Otherwise you would proove, if all of them are empty.
(Sorry for bad english)
if(empty($_POST['senFirstName']) || empty($_POST['senLastName']) ...
Related
i have code like this
<?php
require('../config.php');
require_once($CFG->dirroot . '/user/editlib.php');
$errorMessage = '';
$successMessage = '';
if(isset($_SESSION['successMessage']))
{
$successMessage = $_SESSION['successMessage'];
unset($_SESSION['successMessage']);
}
if (isset($_POST['register'])) {
if(!preg_match("/^(?=.*[0-9])(?=.*[a-z])(\S+)$/i", $_POST['password']))
{
$errorMessage="don't allow spaces";
}
$errors = array();
$data = array();
$chk_sql = "SELECT * FROM {user} u where username = ?";
if (!empty($chk_sql) ) {
$errorMessage='Username already taken';
}
if(!$chk_username = $DB->get_record_sql($chk_sql, array($_POST['username'])) )
{
$secret = $_POST['secret'];
$access_code_sql = "SELECT * FROM {accesscode} WHERE random_no= ? and status=1";
if($chk_secret = $DB->get_record_sql($access_code_sql, array($secret)) )
{
if ( $chk_secret->used >= $chk_secret->number ) {
$errorMessage = "your access code limit completed..";
}
else
{
$cadminid = $chk_secret->cadmin_id;
$clientid = $chk_secret->clientid;
$DB->execute("UPDATE {accesscode} SET used = used+1 WHERE random_no = '$secret'");
$insert_record = new stdClass();
$insert_record->firstname = $_POST['firstname'];
$insert_record->lastname = $_POST['lastname'];
$insert_record->username = $_POST['username'];
$insert_record->secret = $secret;
$insert_record->password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$insert_record->timecreated = time();
$insert_record->maildigest = $cadminid;
$insert_record->maildisplay = $clientid;
$insert_record->idnumber = 1;
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$insert_record->email = $_POST['email'];
if($result = $DB->insert_record('user', $insert_record))
{
$_SESSION['successMessage'] = "record created successfully";
header('Location: register.php');
}
else
$errorMessage = "error! can you please try again";
}
}
else
$errorMessage = "your access code is wrong..";
}
}
?>
so i want to write condition like another if condition
if ( $chk_secret->status='0' ) {
$errorMessage = "your access code deactivated..";
}
if not they can register
i tried..but i didn't get idea where i have to add that if..
before i have condition like if number>used it will show some error message like your accesscode limit completed
can anyone help me..
thanks in advance..
= is for value assignment
== is compare two operands
so you need to change
if ( $chk_secret->status='0' ) {
to
if ( $chk_secret->status=='0' ) {
UPDATE:
your query SELECT * FROM {accesscode} WHERE random_no= ? and status=1
which means it going to return only status == 1
you can check with number of rows returned is ZERO then through status zero error message.
Or else
Get rows only based on random_no exists and then check status key
I am working with a form. Where user enters their email, I can validate the email through regex. But what I need is like this. After searching, I found a solution here. The as it checks the MX record of the email. But still it does not work for me fine, because when I gave a rough email like : ahhhhhhhhhhhhhhhhh#yahoo.com my form accepted it, and when I gave the same email on the other website, it rejected the email. It might be the problem with my logic I don't know, below is my code where I am verifying the email.
if(isset($_GET["saveData"])){
$_appid = $_GET["appid"];
$_name = $_GET["name"];
$_email = $_GET["email"];
$_pass = $_GET["pass"];
$_applink = $_GET["applink"];
function domain_exists($email, $record = 'MX'){
list($user, $domain) = explode('#', $email);
return checkdnsrr($domain, $record);
}
if(!empty($_appid) && !empty($_name) && !empty($_email) && !empty($_pass) && !empty($_applink)){
if(!domain_exists($_email) OR !filter_var($_email, FILTER_VALIDATE_EMAIL)) {
echo "email_prb";
} else{
$sl = "SELECT * FROM fb_data WHERE useremail = '$_email' OR fbappid = '$_appid' ";
$count = $con->query($sl);
if(mysqli_num_rows($count)>0){
echo "exists";
}else{
$in = "INSERT INTO fb_data VALUES(NULL,'$_name','$_email','$_pass','$_applink','$_appid',1,0)";
if ($con->query($in)) {
echo "Inserted";
}
}
}
} else{
echo "empty";
}
}
Kindly Use mysqli or Pdo.. your code is vulnerable to sql injection, try to add mysql escape. but i have rewritten your PHP below without changing query.
Filter validate email will check for the correct email format, so you dont need checking for #. but if you filter the #example.com you need a custom filter for that.
<?php
if(isset($_GET["saveData"])){
$_appid = $_GET["appid"];
$_name = $_GET["name"];
$_email = $_GET["email"];
$_pass = $_GET["pass"];
$_applink = $_GET["applink"];
function domain_exists($email, $record = 'MX'){
list($user, $domain) = explode('#', $email);
return checkdnsrr($domain, $record);
}
if(!empty($_appid) && !empty($_name) && !empty($_email) && !empty($_pass) && !empty($_applink)){
if((!domain_exists($_email)) && (!filter_var($_email, FILTER_VALIDATE_EMAIL))) {
echo "email_prb";
} else{
$sl = "SELECT * FROM `fb_data` WHERE `useremail` = '$_email' OR `fbappid` = '$_appid' ";
$count = $con->query($sl);
if(mysqli_num_rows($count)>0){
echo "exists";
}else{
$in = "INSERT INTO `fb_data` VALUES(NULL,'$_name','$_email','$_pass','$_applink','$_appid',1,0)";
if ($con->query($in)) {
echo "Inserted";
}
}
}
} else{
echo "empty";
}
}
?>
on this part of your code
if(!domain_exists($_email) OR !filter_var($_email, FILTER_VALIDATE_EMAIL))
change the "OR" to ||. Like this
if(!domain_exists($_email) || !filter_var($_email, FILTER_VALIDATE_EMAIL))
I'm using a fetchAll and a for loop to do the trick. In the if statement with $validate as result I tried numbers, boolean and now strings to get the result. Nothing worked so far. Here is my code:
$groep_naam = $_POST['groep'];
$naam = $_POST['naam'];
$adres = $_POST['adres'];
$mail2 = $_POST['mail2'];
$pass1 = md5($_POST['pass1']);
$pass2 = md5($_POST['pass2']);
$select = $db->prepare("SELECT * FROM deelnemers");
$select->execute();
$result = $select->fetchAll();
$len = count($result);
for ($x=0;$x<$len;$x++) {
$mail1 = $_POST['mail1'];
$db_mail = $result[$x][mail];
if ($db_mail != $mail1) {
$validate = "true";
}
if ($db_mail == $mail1) {
$validate = "false";
}
}
if (isset($_POST['submit'])) {
if ($mail1 == $mail2 && $pass1 == $pass2) {
if ($validate == "true") {
$add = $db->prepare("INSERT INTO deelnemers (groep_naam, naam, adres, mail, pass, rechten) VALUES ('$groep_naam', '$naam', '$adres', '$mail1', '$pass1', 'user')");
$add->execute();
} if ($validate == "false") {
echo '
<script>
$("#duplicateEntry").modal("show");
</script>
';
}
You are doing it wrong. Instead of fetching all emails, you should do a query to check if that particular email exists in db.
Pseudocode:
$select = $db->prepare("SELECT 1 FROM deelnemers WHERE mail = :email");
$select->bindValue(':email', $_POST['mail1']);
$select->execute();
$validate = $select->rowCount() > 0; //rowCount/rowExists/whatever to check if the query returned anything
Looking at your current code, probable mistake is on line
$db_mail = $result[$x][mail];
It probably should've been
$db_mail = $result[$x]['mail'];
Another thing, you loop through all emails comparing them with the one from request, so even if you find the one email matching it, later in another loop you rewrite your $validate value.
I am trying to make a registration form and doing some checks before running SQL queries, but as i test and try to generate multiple errors, i am getting only the error that comes first, or sometimes no error at all. I am unable to locate where i have made error.
The following is the code in PHP.
//function to filter only phone numbers
function get_phone($number) {
return preg_replace('#[^0-9]#', '', $number);
}
//function to take only alphabets.
function get_alpha($alphabets){
return preg_replace('#[^a-z]#', '', $alphabets);
}
//function to check email.
function isValidEmail($email){
if (strlen ($email) > 50){
$errors[] = 'email address too long, please use a shorter email address..!';
} else {
return (filter_var($email, FILTER_VALIDATE_EMAIL));
}
}
function output_errors($errors){
$output = array();
foreach($errors as $error) {
$output[] = '<li>' . $error . '</li>';
}
return '<ul>' . implode('', $output) . '</ul>';
}
if (empty($_POST) === false) {
//store the text box field names of the form to local variables.
$cust_name = $_POST['name1'];
$cust_email = $_POST['email'];
$cust_phone = $_POST['phone'];
$cust_addr1 = $_POST['addr1'];
$cust_addr2 = $_POST['addr2'];
$cust_city = $_POST['city'];
$cust_state = $_POST['state'];
$cust_country = $_POST['country'];
$username = $_POST['uname'];
$password = $_POST['passwd'];
$cnf_passwd = $_POST['cnf_passwd'];
$sec_que = $_POST['sec_que'];
$sec_ans = $_POST['sec_ans'];
//sanitize the inputs from the users end.
$cust_name = sanitize($username);
$cust_phone = get_phone($cust_phone);
$cust_addr1 = sanitize($cust_addr1);
$cust_addr2 = sanitize($cust_addr2);
$cust_city = get_alpha($cust_city);
$cust_state = get_alpha($cust_state);
$cust_country = get_alpha($cust_country);
$username = sanitize($username);
$password = md5($password);
$cnf_passwd = md5($cnf_passwd);
$sec_que = sanitize($sec_que); //put up dropdown menu
$sec_ans = sanitize($sec_ans);
$cust_email = isValidEmail($cust_email);
//check for error handling in form data
//1. check for empty fields,
if ($cust_name == "" || $cust_phone == "" ||
$cust_addr1 == "" || $username == "" ||
$password == "" || $cnf_passwd == "" ||
$sec_que == "" || $sec_ans == ""
) {
$errors[] = 'No blank fields allowed, please fill out all the required fields..!';
//2.check for field lengths
} else if (strlen($cust_name) < 3 || strlen($cust_name > 20)) {
$errors[] = 'The name length should be between 3 to 20, please check & correct..!';
//3. check for phone number length
} else if (strlen($cust_phone) < 10 || strlen($cust_phone) > 11) {
$errors[] = 'The phone number must be 10 or 11 digits..!';
//4. check for address input lengths.
} else if (strlen($cust_addr1) < 5 || strlen($cust_addr1) > 50) {
$errors[] = 'Please provide a valid address..to serve you better..!';
//5. check if the password fields content match.
//length is not checked because the entered values will be converted to MD5 hash
// of 32 characters.
} else if ($password != $cnf_passwd) {
$errors[] = 'The passwords do not match. Please enter your passwords again..!';
// 6. check for length of the security answers.
} else if (strlen($sec_ans) < 5 || strlen($sec_ans) > 50) {
$errors[] = 'Please enter a proper security answer..!';
} //7. check for valid email address
else if($cust_email == false){
$errors[] = 'The email address you entered is not valid, please check and correct..!';
} else {
execute the SQL queries and enter the values in the database.
echo 'GOOD...TILL NOW..!!!';
}
} else {
$errors [] = 'No data received, Please try again..!!';
}
if(empty($errors) === false) {
?>
<h2>The Following errors were encountered:</h2>
<?php
echo output_errors($errors); //output the errors in an ordered way.
}
?>
When you use this structure:
if () {
} else if () {
} else if () {
}
// etc.
then only one condition can be satisfied. As soon as one of those if conditions is true, the rest of the else if blocks and the final else block are ignored.
If your conditions aren't mutually exclusive, put them in their own separate blocks:
if () {
}
if () {
}
if () {
}
// etc.
I have this script that checks a submitted form. It checks if all fields are all filled out, and checks if the user has submitted the form before. It also checks if the entered data is already in the database or not. When I try to check if the entered data is in the database, it always returns false. My question is: How can I efficiently check if the POST values are the same?
Code:
<?php
error_reporting(E_NOTICE ^ E_ALL);
$Name = $_POST['name'];
$ID = $_POST['id'];
$Topic_1 = $_POST['1'];
$Topic_2 = $_POST['2'];
$Topic_3 = $_POST['3'];
$Topic_4 = $_POST['4'];
$Topic_5 = $_POST['5'];
$Topic_6 = $_POST['6'];
$Topic_7 = $_POST['7'];
$Topic_8 = $_POST['8'];
$Topic_9 = $_POST['9'];
$Topic_10 = $_POST['10'];
$Topic_11 = $_POST['11'];
$Topic_12 = $_POST['12'];
$Topic_13 = $_POST['13'];
$Topic_14 = $_POST['14'];
$Topic_15 = $_POST['15'];
$IP = $_SERVER['REMOTE_ADDR'];
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Check = 'SELECT * FROM Submissions WHERE School_ID = "'.$ID.'" AND IP = "'.$IP.'"';
$Insert = 'INSERT INTO Submissions (Name, School_ID, Topic_1, Topic_2, Topic_3, Topic_4, Topic_5, Topic_6, Topic_7, Topic_8, Topic_9, Topic_10, Topic_11, Topic_12, Topic_13, Topic_14, Topic_15, IP) VALUES ("'.$Name.'", "'.$ID.'", "'.$Topic_1.'", "'.$Topic_2.'", "'.$Topic_3.'", "'.$Topic_4.'", "'.$Topic_5.'", "'.$Topic_6.'", "'.$Topic_7.'", "'.$Topic_8.'", "'.$Topic_9.'", "'.$Topic_10.'", "'.$Topic_11.'", "'.$Topic_12.'", "'.$Topic_13.'", "'.$Topic_14.'", "'.$Topic_15.'", "'.$IP.'")';
if($Name && $ID != "")
{
if($Result = $Connect->query($Check))
{
$Rows = $Result->num_rows;
if($Rows == 0)
{
if($_POST != $_POST)
{
if($Go = $Connect->prepare($Insert))
{
if($Go->execute())
{
echo 'Thanks';
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'No Two Values Can Match.';
}
}
else
{
echo 'You Cant Vote Twice.';
}
$Result->close();
}
else
{
echo 'There Was An Error.';
}
}
else
{
echo 'Please Fill Out All Fields';
}
$Connect->close();
Your if statement should look like
if($name != "" && $check != "")
Here's the error:
if($_POST != $_POST)
You do probably want to compare the result from the db with the $_POST instead.
$Row = $Result->fetch_assoc();
if($Row != $_POST)
Prior to doing a comparison use var_dump() on the variables to check what they actually contain.
var_dump($Name);
var_dump($ID);
exit();
Then check for a negative or positive match.
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
You can even spoof that in a separate file.
<?php
$Name = 'Bob';
$ID = ''; // or use 0 or any test you want
var_dump($Name);
var_dump($ID);
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
Isolating problems like this will help you develop incrementally, get something working, then add more lines till you arrive at your destination.
To check if not two POST values are the same:
array_diff($_POST, array_unique($_POST));
What you looking for is following
$_POST['1'] = 'a';
$_POST['2'] = 'b';
$_POST['3'] = 'c';
$_POST['4'] = 'a';
$_POST['5'] = 'd';
$results = array_unique($_POST);
var_dump($results);
returns:
array
1 => string 'a' (length=1)
2 => string 'b' (length=1)
3 => string 'c' (length=1)
5 => string 'd' (length=1)
You can't really so easily check if a person did submit a form before.
One way is to add one more hidden field to form if the request came with POST.
Something like that:
<form method="POST" action="">
<?php
if(isset($_POST['submit'])) {
echo '<input type="hidden" name="second_post" value="1">';
} ?>
<!-- Other form items -->
<input type="submit" name="submit" value="1">
</form>
Then you can check is it a second time with:
if(isset($_POST['second_post'])) {
// Second time of form post;
} else {
// First (or zero) time post.
}