I have this code which is an assignment given to us and is really giving me a hard time, what i want to achieve is simple, if the user inputs either an already taken email or date then the program will not continue and will echo an error. But my he also wants us to output "Date is already taken!" if the date the user trying to insert is already in the database and "Email is already taken!" if the email is taken and "Sorry, Email and date are both taken!"..
What I'm trying to say is like this:
-INPUT # 1-
Enter Date: Example Date // Assuming date is already taken.
Enter Email: john#example.com
-OUTPUT # 1-
Sorry! Date is already taken!
-INPUT # 2-
Enter Date: Example Date
Enter Email: john#example.com // Assuming email is already taken.
-OUTPUT # 2-
Sorry! Email is already taken!
-INPUT # 3-
Enter Date: Example Date // Assuming date is already taken.
Enter Email: john#example.com // Assuming email is also taken.
-OUTPUT # 3-
Sorry, Email and date are both taken!
$emailadd = $_POST['eadd'];
$rdate = $_POST['date'];
try {
$stmt = $conn->prepare("SELECT tblclient.ClientID,
tblreservation.ReservationID,
tblclient.EmailAdd,
tblreservation.Date
FROM tblclient
INNER JOIN tblreservation
ON tblclient.ClientID = tblreservation.ReservationID
WHERE EmailAdd = ?
OR Date = ? ");
$result = $stmt->execute([$emailadd, $rdate]);
if ($stmt->execute([$emailadd, $rdate]) > 0 ) {
echo "Email already exist!";
}
try {
$sql = "INSERT INTO tblclient(
Fname,
Lname,
MI,
Address,
ContactNo,
EmailAdd)
VALUES (
'" . urldecode(trim($_POST['fname'])) . "',
'" . urldecode(trim($_POST['lname'])) . "',
'" . urldecode(trim($_POST['mname'])) . "',
'" . urldecode(trim($_POST['add'])) . "',
'" . urldecode(trim($_POST['telno'])) . "',
'" . urldecode(trim($_POST['eadd'])) . "')";
$conn->exec($sql);
try {
$sql = "INSERT INTO tblreservation(
ReservationPrice,
ReservationDate,
ReservationTime,
ReservationStatus)
VALUES (
'" . urldecode(trim($_POST['price'])) . "',
'" . urldecode(trim($_POST['date'])) . "',
'" . urldecode(trim($_POST['time'])) . "',
'" . urldecode(trim($_POST['status'])) . "')";
$conn->exec($sql);
} catch (PDOException $e) {
echo $e;
}
} catch (PDOException $e) {
echo $e;
}
} catch (PDOException $e) {
echo $e;
}
I also tried using
if ($stmt->execute([$emailadd]) > 0 ) {
echo "Email already exist!";
} elseif ($stmt->execute([$rdate]) > 0 ) {
echo "Date already exist!";
}
Also no luck :( any help would be very appreciated.
I would like to suggest this way
$ERROR = 0;
$ARR_ERROR = array();
if ($stmt->execute([$emailadd]) > 0 ) {
$ERROR = 1;
$ARR_ERROR['error'][] = "Email already exist!";
}
if ($stmt->execute([$rdate]) > 0 ) {
$ERROR = 1;
$ARR_ERROR['error'][] = "Date already exist!";
}
// You can add more if statement here
// Show errors if there is
if($ERROR == 1){
foreach($ARR_ERROR['error'] as $singleError){
echo $singleError;
}
}
In this way you will be able to show multiple errors.
Related
Hi and thanks for reading.
I have been using this for a while on an old php5 running on a Windows XP box. Recently I moved everything to a php7.0 running on a linux box.
It still runs fine in the old environment but not on the new one. Any suggestions as to where I am going wrong?
Here is the data going in;
http://192.168.0.2/test/index2.php?doing=advicepart3&from=advicepart3update&id=5096&delivered=5&delivered1&delivered3=&discount=0.00&carriage=0.00
Basically it is delivering part of an order.
if (preg_match("/^delivered([0-9]+)$/", $key, $matches) == 1) {
$id = $matches[1];
$sql1a = "SELECT QUANTITY, DELIVERED FROM salesitems WHERE ID = '" . $id . "' ORDER BY ID DESC LIMIT 1";
$result1a = $conn->query($sql1a);
if (mysqli_query($conn, $sql1a))
{
}
else
{
print "Error: " . $sql1a . "<br>" . mysqli_error($conn) . " Contact support";
}
if ($result1a->num_rows > 0) {
while($row1a = $result1a->fetch_assoc())
{
$ordered = $row1a['QUANTITY'];
$alreadydelivered = $row1a['DELIVERED'];
}
}
$updatedelivered = $alreadydelivered + $value;
if ($updatedelivered > $ordered)
{
$updatedelivered = $ordered;
}
$outstanding = $ordered - $updatedelivered;
$sql = "UPDATE salesitems SET DELIVERED = '". $updatedelivered ."', OUTSTANDING = '". $outstanding ."' WHERE ID = '" . $id . "'";
if (mysqli_query($conn, $sql))
{
}
else
{
print "Error: " . $sql . "<br>" . mysqli_error($conn) . " Contact support";
}
}
Many thanks in advance for any suggestions.
No wonder there wasn't an error - there wasn't anything wrong with it. Problem was the php I wrote had a problem. Each of the delivered should have had a number appended to them (taken from a query) but the query wasn't reading properly.
Thank you for making me look elsewhere.
I Am trying to check if the REF number added when creating a new mysql row is already in use. I don't have problems in adding a new row however, the script does not check the database first.
if ($_POST['add_new_bus']){
if (($_POST['add_ref'] != "")&&($_POST['add_name'] != "")&&($_POST['add_address'] != "")&&($_POST['add_area'] != "")){
$add_ref = $_POST['add_ref'];
$add_name = $_POST['add_name'];
$add_address = $_POST['add_address'];
$add_area = $_POST['add_area'];
$chech_sql = "INSERT INTO `Details` (`REF`) VALUES ('$add_ref')";
if (!($conn->query($chech_sql))) {
echo "REF is already in use";
}else{
mysqli_query($conn, "INSERT INTO `Details` (`REF`, `NAME`, `ADDRESS`, `AREA`) VALUES ('$add_ref', '$add_name', '$add_address', '$add_area')");
echo "<p style='float:right;'>" . $_POST['add_name'] . " " . "has been added to the register with REF number:" . " " . $_POST['add_ref'] . "</p>";
}
}
Any Idea how to check if the REF number is already in use?
For giving you a correct idea how to do it, Please check below code:-
<?php
if (isset($_POST['add_new_bus']){
if (($_POST['add_ref'] != "") &&($_POST['add_name'] != "")&&($_POST['add_address'] != "")&&($_POST['add_area'] != "")){
$add_ref = $_POST['add_ref'];
$add_name = $_POST['add_name'];
$add_address = $_POST['add_address'];
$add_area = $_POST['add_area'];
$chech_sql = "SELECT add_ref FROM Details WHERE add_ref = '".$add_ref."'";
$result = $conn->query($chech_sql);
if (mysqli_num_rows($result) > 0) {
echo "REF is already in use";
}else{
mysqli_query($conn, "INSERT INTO `Details` (`REF`, `NAME`, `ADDRESS`, `AREA`) VALUES ('$add_ref', '$add_name', '$add_address', '$add_area')");
echo "<p style='float:right;'>" . $_POST['add_name'] . " " . "has been added to the register with REF number:" . " " . $_POST['add_ref'] . "</p>";
}
}
}
?>
Note:- checking variables value and other things is up to you. because you only have them in your code.thanks.
Ok i am very stuck here and i am might be looking at this completely wrong (still kind of a newbie) or super close just missing something small i cant tell.
At the bottom here you will find my code with a If ElseIf Else statement. That i just cant get to do what i want. so i am hoping someone can help guide me in the right direction.
On the If it checks to make sure that the promocode that was entered is in the database and that part works.
on the elseif i want it to look through the database and find the promocode and confirm that there isnt an email address associated with that promocode. The way that it is below with the IS NOT NULL in the query works for when there is an email address in that promocode but when there isnt anything for that promocode it is still saying that there is and gives the submit data of today but i can assure that there isnt anything in the database.
This is where my problem lies am i doing this completely wrong is there a better way to accomplish what i am trying to do here? Or have i just overlooked something small?
$promosql = "SELECT * FROM formdata WHERE (promoCode = '$varPromo')";
$promoraw = $mysqli->query($promosql);
$dupesql = "SELECT * FROM formdata WHERE (promoCode = '$varPromo' AND email IS NOT NULL)";
$duperaw = $mysqli->query($dupesql);
if($promoraw->num_rows <> 1) {
//echo ("$varName already exists in $varAddress \n");
$promo .= "$varPromo is not a valid promocode \n";
}
elseif($duperaw->num_rows > 0) {
//echo ("$varName already exists in $varAddress \n");
$dupe .= "$varPromo has already been used on $varDate \n";
}
else {
$sql = "INSERT INTO formdata (promoCode, name, email, address, city, state, zip, submitDate) VALUES (".
PrepSQL($varPromo) . ", " .
PrepSQL($varName) . ", " .
PrepSQL($varEmail) . ", " .
PrepSQL($varAddress) . ", " .
PrepSQL($varCity) . ", " .
PrepSQL($varState) . ", " .
PrepSQL($varZip) . ", " .
PrepSQL($varDate) . ")";
$mysqli->query($sql);
header("location: index.php?success=1");
exit();
}
Try this query:
SELECT email IS NULL or email = '' has_email FROM formdata WHERE promoCode = '$varPromo'
Then your PHP can do:
if ($promoraw->nul_rows == 0) {
// Not a valid promo code
} else {
$row = $promoraw->fetch_assoc();
if ($row['has_email']) {
// Promo code has been used
} else {
// Insert into table
}
}
I am having two problems with my code below.
<?php
$validSubmission = isset($_POST['resetpass']) && $_POST['students'] && $_POST['newpass'] && $_POST['confirmpass'];
$sql = "SELECT StudentUsername, StudentForename, StudentSurname FROM Student ORDER BY StudentUsername";
$sqlstmt = $mysqli->prepare($sql);
$sqlstmt->execute();
$sqlstmt->bind_result($dbStudentUsername, $dbStudentForename, $dbStudentSurname);
$students = array(); // easier if you don't use generic names for data
$studentHTML = "";
$studentHTML .= '<select name="students" id="studentsDrop">' . PHP_EOL;
$studentHTML .= '<option value="">Please Select</option>' . PHP_EOL;
$outputstudent = "";
while ($sqlstmt->fetch())
{
$student = $dbStudentUsername;
$firstname = $dbStudentForename;
$surname = $dbStudentSurname;
if (!$validSubmission && isset($_POST['students']) && $student == $_POST['students'])
{
$studentHTML .= "<option value='" . $student . "' selected='selected'>" . $student . " - " . $firstname . " " . $surname . "</option>" . PHP_EOL;
}
else
{
$studentHTML .= "<option value='" . $student . "'>" . $student . " - " . $firstname . " " . $surname . "</option>" . PHP_EOL;
}
}
$studentHTML .= '</select>';
$errormsg = (isset($errormsg)) ? $errormsg : '';
if (isset($_POST['resetpass']))
{
//get the form data
$studentdrop = (isset($_POST['students'])) ? $_POST['students'] : '';
$newpass = (isset($_POST['newpass'])) ? $_POST['newpass'] : '';
$confirmpass = (isset($_POST['confirmpass'])) ? $_POST['confirmpass'] : '';
//make sure all data was entered
if ($studentdrop != "")
{
if ($newpass)
{
if (strlen($newpass) <= 5)
{
$errormsg = "Your Password must be a minimum of 6 characters or more";
}
else
{
if ($confirmpass)
{
if ($newpass === $confirmpass)
{
//Make sure password is correct
$query = "SELECT StudentUsername FROM Student WHERE StudentUsername = ?";
// prepare query
$stmt = $mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s", $username);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbStudentUsername);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
if ($numrows == 1)
{
//encrypt new password
$newpassword = md5(md5("93w" . $newpass . "ed0"));
//update the db
$updatesql = "UPDATE Student SET StudentPassword = ? WHERE StudentUsername = ?";
$update = $mysqli->prepare($updatesql);
$update->bind_param("ss", $newpassword, $username);
$update->execute();
//make sure the password is changed
$query = "SELECT StudentUsername, StudentPassword FROM Student WHERE StudentUsername = ? AND StudentPassword = ?";
// prepare query
$stmt = $mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("ss", $username, $newpassword);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbStudentUsername, $dbStudentPassword);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
if ($numrows == 1)
{
$errormsg = "<span style='color: green'>Student " . $student . " - " . $firstname . " " . $surname . " has been Registered</span>";
}
else
{
$errormsg = "An error has occured, the Password was not Reset";
}
}
}
else
{
$errormsg = "Your New Password did not Match";
}
}
else
{
$errormsg = "You must Confirm your New Password";
}
}
}
else
{
$errormsg = "You must Enter your New Password";
}
}
else if ($studentdrop == "")
{
$errormsg = "You must Select a Student";
}
}
I am trying to create a rest password page where an admin can reset a student's password.
PROBLEM 1:
In my code what I am trying to do is that if a php validation message appears (one of the $errormsg appears except for the $errormsg which displays the sucess message), then the students drop down menu should still display the option that was selected after the submission of the form occurs. Now this works for all the validation message where the user has left a text input blank, but the only validation message it doesn't work for is when the user has not typed in matching passwords for the new and confirm passwords. If the $errormsg = "Your New Password did not Match";
occurs then the students drop down menu goes back to the Please Select option. How come it goes back to the Please Select option everytime this validation message appears and how can I keep the selected student still selected if this validation occurs?
PROBLEM 2:
If I successfully enter in all the details and submit, it does not perform the insert, yet it does not display the fail message $errormsg = "An error has occured, the Password was not Reset";
or the success message $errormsg = "<span style='color: green'>Student " . $student . " - " . $firstname . " ". $surname . " has been Registered</span>";, why is this occuring? I know the UPDATE statement is correct as I tested this in phpmyadmin.
$username (line 72 and onwards) is never set. I presume this should come from '$studentdrop'?
This means you update where StudentUsername == '', which will fail.
To help you debug:
1. Turn on warning and notices in the error handler for writing code ( error_reporting(E_ALL); ) as it will reveal problems like this
2. As opposed to constantly counting the rows, you can save time in that the bind_result/store_value won't work unless you got a result. So you can check that value you get in bind_result - and if you had checked that `$dbStudentUsername == $username` in line 78, then it would have also thrown a wobbly at that stage.
3. When you've done the "update", you can check the number of "affected rows"; if this > 0 then the password has been updated; no need for a secondary DB query.
Hope that helps
I have a form with user details and an update statement that will update such details if the user wants to, i added validation so that an email cannot be associated with another account hence the if($checkuser != 0)
The issue with the statement is that if the user doesn't change their email and updates their details, they will get an error saying email already exist.
I wanted to integrate after the email existence check something like else if(($_POST["myusername"]) == ($row['email'])) then continue updating.(myusername variable name contains the email) meaning that if the posted email is the same as their current email then continue updating.
But i am getting lost, since i am relatively new with PHP i am having trouble with parenthesis and brackets.
Here is my code
if($_POST['usubmit']=='Update')
{
$Uerr = array();
if (!$_POST['fullname'] || !$_POST['myusername'])
{
$Uerr[] = '» Name or Email must be filled in!';
}
if (!checkEmail($_POST['myusername']))
{
$Uerr[]='» Your email is not valid!';
}
// If there are no errors
if(!count($Uerr))
{
/* Now we will check if username is already in use or not */
$queryuser=mysql_query("SELECT * FROM customer WHERE email='" . mysql_real_escape_string($_POST["myusername"]) . "'");
$checkuser=mysql_num_rows($queryuser);
if($checkuser != 0)
{
$Uerr[]='» Sorry this email is already registered!';
}
else
{
$updateDetails = mysql_query("UPDATE customer SET
name = '" . mysql_real_escape_string($_POST["fullname"]) . "',
dob = '" . mysql_real_escape_string($_POST["dob"]) . "',
address = '" . mysql_real_escape_string($_POST["address"]) . "',
email = '" . mysql_real_escape_string($_POST["myusername"]) . "',
telephone = '" . mysql_real_escape_string($_POST["telephone"]) . "'
WHERE cus_id = '$cus_id'");
if ($updateDetails)
$_SESSION['Umsg']['Ureg-success']="» Your details have been updated successfully!";
else {
$Uerr[]='» error updating your account'.mysql_error();
}
}
}
if(count($Uerr))
{
$_SESSION['Umsg']['Ureg-err'] = implode('<br />',$Uerr);
}
header("Location: account.php");
exit;
}
this should work
if($_POST['usubmit']=='Update')
{
$Uerr = array();
if (!$_POST['fullname'] || !$_POST['myusername'])
{
$Uerr[] = '» Name or Email must be filled in!';
}
if (!checkEmail($_POST['myusername']))
{
$Uerr[]='» Your email is not valid!';
}
// If there are no errors
if(!count($Uerr))
{
/* Now we will check if username is already in use or not */
$queryuser=mysql_query("SELECT * FROM customer WHERE email='" . mysql_real_escape_string($_POST["myusername"]) . "' AND cus_id !=" . $cus_id(mysql_real_escape_string));
$checkuser=mysql_num_rows($queryuser);
if($checkuser != 0)
{
$Uerr[]='» Sorry this email is already registered!';
}
else
{
$updateDetails = mysql_query("UPDATE customer SET
name = '" . mysql_real_escape_string($_POST["fullname"]) . "',
dob = '" . mysql_real_escape_string($_POST["dob"]) . "',
address = '" . mysql_real_escape_string($_POST["address"]) . "',
email = '" . mysql_real_escape_string($_POST["myusername"]) . "',
telephone = '" . mysql_real_escape_string($_POST["telephone"]) . "'
WHERE cus_id = '$cus_id'");
if ($updateDetails)
$_SESSION['Umsg']['Ureg-success']="» Your details have been updated successfully!";
else {
$Uerr[]='» error updating your account'.mysql_error();
}
}
}
if(count($Uerr))
{
$_SESSION['Umsg']['Ureg-err'] = implode('<br />',$Uerr);
}
header("Location: account.php");
exit;
}
I have a form with user details and an update statement that will
update such details if the user wants to, i added validation so that
an email cannot be associated with another account hence the
The issue with the statement is that if the user doesn't change their
email and updates their details, they will get an error saying email
already exist.
Why don't you just check if there is existed email with another account except his account which can be solved with a few changes to your query.
$queryuser=mysql_query("SELECT * FROM customer WHERE email='" .
mysql_real_escape_string($_POST["myusername"]) . "' AND cus_id!=" . intval($cus_id));
I do something ugly but works great.
I add the actual info on some hidden inputs like:
<input type="hidden" name="actual_email" value="<?php echo $object->email; ?>" />
Now you just need to check if the email on the user input (the visible one) is the same on the hidden input, if yes, just ignore the email validation because it means the user hasn't changed his email.
When you are having a user change their information, they should only have access to their account (for security & privacy purposes). Therefore you should use their e-mail as the identifier when getting their information.