PHP/MYSQL Update Statement advice - php

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.

Related

How to set multiple if/elseif conditions with multiple execute parameters

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.

Email Verification process not working

I'm trying to build a registration page with email verification, but the verification process does not seem to work.
After typing all the user data, the user will get an email with an id and a code.
When he clicks the link, he will run through the following code:
<?php
if(isset($_GET['id']) && isset($_GET['code']))
{
$id=$_GET['id'];
$code=$_GET['code'];
include("activate_user.php");
}
?>
activate_user.php looks like that:
<?php
include("db_connect.php");
$sql = "select * from users where "
. "id = " . $id
. " and code = '" . $code . "')";
$res = mysqli_query($con, $sql);
$num = mysqli_num_rows($res);
if ($num == 1)
{
$validate = "update users set valid = 1 where "
. "id = " . $id
. " and code = '" . $code . "')";
$validate_user = mysqli_query($con, $validate);
}
mysqli_close($con);
?>
Something must be wrong with the second php file, but I'm not sure, what the problem could be. db_connect should be fine since I'm using the same when I add the user to my database. My file is still not able to change valid from 0 to 1.
Thanks in advance for your help!
UPDATE: change mysqli_affected_row to mysqli_num_rows and added '-marks before $code, but it still doesn't work

All-in-One Web form

I'm learning PHP and I am now on creating an all in one web form that adds a new subscriber record to the subscribers table in the newsletter database. This is my first time on this site, so excuse any n00biness.
The comments explain the portion of code which determines whether the form will be processed. I'm not sure if it needs to go inside the if..else statement that validates the submitted form data, or if it goes after the validation in its own if..else.
When I put it inside the validation, the html form shows, but when I hit submit, all the info refreshes and nothing happens.
When I put it after the validation, the html form does not show, I get an error saying undefined variable: FormErrorCount. It then tells gives me the id number I'm supposed to get, but I did not enter a name or email (due to the html form not showing) and that is left blank.
There is an include file, but that is just fine.
I'm sure once this gets figured out, I will have the feeling to want to slap myself, but I have been staring at the screen way too long. Thank you
<?php
$ShowForm = FALSE;
$SubscriberName = "";
$SubscriberEmail = "";
if (isset($_POST['submit'])) {
$FormErrorCount = 0;
if (isset($_POST['SubName'])) {
$SubscriberName = stripslashes($_POST['SubName']);
$SubscriberName = trim($SubscriberName);
if (strlen($SubscriberName) == 0) {
echo "<p>You must include your name</p>\n";
++$FormErrorCount;
}
}else{
echo "<p>Form submittal error (No 'SubName' field)!</p>\n";
++$FormErrorCount;
}
if (isset($_POST['SubEmail'])) {
$SubscriberEmail = stripslashes($_POST['SubEmail']);
$SubscriberEmail = trim($SubscriberEmail);
if (strlen($SubscriberEmail == 0)) {
echo "<p>You must include your email address!</p>\n";
++$FormErrorCount;
}
}else{
echo "<p>Form submittal error (No 'SubEmail' field)!</p>\n";
++$FormErrorCount;
}
//CODE BELOW IS THE SAME AS THE COMMENTED OUT CODE TOWARDS THE END. NOT SURE WHERE IT GOES.
if ($FormErrorCount == 0) {
$ShowForm = FALSE;
include("inc_db_newsletter.php");
if ($DBConnect !== FALSE) {
$TableName = "subscribers";
$SubscriberDate = date("Y-m-d");
$SQLstring = "INSERT INTO $TableName " .
" (name, email, subscribe_date) " .
" VALUES('$SubscriberName', '$SubscriberEmail', '$SubscriberDate')";
$QueryResult = #mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE) {
echo "<p>Unable to insert the values into the subscriber table.</p>" .
"<p>Error code " . mysql_errno($DBConnect) . ": " .
mysql_error($DBConnect) . "</p>";
}else{
$SubscriberID = mysql_insert_id($DBConnect);
echo "<p>" . htmlentities($SubscriberName) . ", you are now subscribed to our
newsletter.<br />";
echo "Your subscriber ID is $SubscriberID.<br />";
echo "Your email address is " . htmlentities($SubscriberEmail) . ".</p>";
}
mysql_close($DBConnect);
}
}else{
$ShowForm = TRUE;
}
//CODE ABOVE IS THE SAME AS THE COMMENTED OUT CODE TOWARDS THE END. NOT SURE WHERE IT GOES.
}else{
$ShowForm = TRUE;
}
/* CODE BELOW IS SAME AS THE CODE BETWEEN THE COMMENTS ABOVE, BUT NOT SURE WHERE IT BELONGS
if ($FormErrorCount == 0) {
$ShowForm = FALSE;
include("inc_db_newsletter.php");
if ($DBConnect !== FALSE) {
$TableName = "subscribers";
$SubscriberDate = date("Y-m-d");
$SQLstring = "INSERT INTO $TableName (name, email, subscribe_date) " .
"VALUES ('$SubscriberName', '$SubscriberEmail', '$SubscriberDate')";
$QueryResult = #mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE) {
echo "<p>Unable to insert the values into the subscriber table.</p>" .
"<p>Error code " . mysql_errno($DBConnect) . ": " .
mysql_error($DBConnect) . "</p>";
}else{
$SubscriberID = mysql_insert_id($DBConnect);
echo "<p>" . htmlentities($SubscriberName) . ", you are now subscribed to our
newsletter.<br />";
echo "Your subscriber ID is $SubscriberID.<br />";
echo "Your email address is " . htmlentities($SubscriberEmail) . ".</p>";
}
mysql_close($DBConnect);
}
}else{
$ShowForm = TRUE;
}
*/CODE ABOVE IS SAME AS THE CODE BETWEEN THE COMMENTS ABOVE SECTION, BUT NOT SURE WHERE IT BELONGS
//HTML PORTION
if ($ShowForm) {
?>
<form action = "NewsletterSubscribe.php" method = "POST">
<p><strong>Your Name: </strong>
<input type = "text" name = "SubName" value = "<?php echo $SubscriberName; ?>" /></p>
<p><strong>Your Email Address: </strong>
<input type = "text" name = "SubEmail" value = "<?php echo $SubscriberEmail; ?>" /></p>
<p><input type = "Submit" name = "Submit" value = "Submit" /></p>
</form>
<?php
}
?>
Your code, ignoring for now the ShowForm part at the end, is structured like this:
if this is a submit {
validate the form data
if there are no errors {
save the form data
}
}
This looks reasonable. Maybe your form isn't being submitted as a POST? Check your <form action> and also use Firebug to make sure the form data is being submitted.
If you were to move the error check, you would have:
if this is a submit {
validate the form data
}
if there are no errors {
save the form data
}
And that's wrong because if the form were not being submitted, then you'd have no errors (hence the "undefined variable" error) and then it would attempt to save the nonexistent form data.

Session ID changes on saved to DB

I have this small problem on Session. Ill show you the codes below.
//checking session orderid if not created
$setSession = $_SESSION['neworderid'];
if (empty($setSession)) {
$neworderid = mt_rand(1000000000, 9999999999);
$_SESSION['neworderid'] = $neworderid;
}
//check if order_id exists in the database
$db->setQuery("SELECT * FROM mn_orderitems WHERE order_id =" . $_SESSION['neworderid']);
$query = $db->loadResult();
if (!empty($query)) {
//if exists, do nothing
echo 'Not Empty';
} else {
//if order id doesn't exist, save the new order item
$qry = "INSERT INTO mn_orderitems (order_id, product_id, orderitem_name, orderitem_quantity, orderitem_price, orderitem_final_price) VALUES
('" . $_SESSION['neworderid'] . "', '" . $item->product_id . "', '" . $item->orderitem_name . "', '" . $item->orderitem_quantity . "', '" . $item->orderitem_price . "', '" . $item->orderitem_final_price . "')";
$result = mysql_query($qry);
if (!$result) {
echo "Error";
} else {
echo "Saved";
}
echo 'Empty';
}
Problem:
"When I try to echo the $_SESSION['neworderid']; it outputs = 8152269414
But when it is being save to database the order_id changes to 2147483647".
This only happens in live server. No problem in my localhost Apache.
The problem you are having is not with the PHP script itself, but your database structure. In MySQL the biggest number you can store (declared as INT) is 2147483647. If you want to store bigger numbers, you'll have to either change the script to generate a lower number OR change the DB to use BIGINT.
Change first order_id's structure in phpMyAdmin from INT into BIGINT
/* checking session orderid if not created */
session_start();
if (empty($_SESSION['neworderid'])) {
$neworderid = mt_rand(1000000000, 9999999999);
$_SESSION['neworderid'] = $neworderid;
$setSession = $_SESSION['neworderid'];
}
else {
$setSession = $_SESSION['neworderid'];
}
/* check if order_id exists in the database and convert the code to mysqli */
/* have your connection store into $db variable */
$result=mysqli_query($db, "SELECT * FROM mn_orderitems WHERE order_id ='$setSession'");
if (mysqli_num_rows($result)!=0) {
/* If a record has been found, do nothing */
echo "Not Empty";
} else {
/* if order id doesn't exist, save the new order item */
$insert=mysqli_query($db,"INSERT INTO mn_orderitems (order_id, product_id, orderitem_name, orderitem_quantity, orderitem_price, orderitem_final_price)
VALUES ('$setSession', '$product_id', '$orderitem_name', '$orderitem_quantity', '$orderitem_price', '$orderitem_final_price')");
if($insert){
echo "Successfully Added item no. ".$setSession;
}
}

PHP If Else Not working like i thought it would

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
}
}

Categories