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.
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'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
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.
So i already have a database of locations of every city, state, zip.
I am currently working on how to do a search and get results of surrounding zip codes x miles away, and have run into some trouble.
I successfully have the search working for you to type in the zip code, since it is a predefined value. But am having trouble with results of a city, state. Currently it only works if you type in just the city name ex "Chicago"... But Does not work if you type in "Chicago, IL".
Here is the code for the $_GET of the search form, searchval
Please Help!
$searchval = $mysql->escape_data($_GET['searchval']);
if (!empty($searchval))
{
if(preg_match("~\d{5}~", $searchval)) {
$zip = $searchval;
}
else {
$city = $searchval;
}
} else
{
$error .= "<div id='Error'>Please enter zip</div>";
$zip = false;
}
Below is the code that actually takes the $zip or $city and gets the surrounding zip codes. if you enter a zip code, it works successfully. If you enter just a city name, it works successfully. If you enter "Chicago, IL" it does not work.
<?php
//if user entered a city ex. "Chicago"
if(isset($city)) {
$q = 'SELECT City, State, ZipCode FROM zipcodes WHERE City like "'. $city .'%" ORDER BY ZipCode ASC Limit 0,10';
$result = $mysql->query($q);
$row = mysqli_fetch_array($result);
$zip = $row[2];
if(mysqli_num_rows($result) != 1) {
echo"Did you mean...<br />";
while($row = mysqli_fetch_array($result)) {
echo "<a href='" .$_SERVER['PHP_SELF'] . "?searchval=".$row[2]."&miles=".$miles."'>" . $row[0] . " " . $row[1] . " " . $row[2] . "</a><br />";
}
}
}
$zcr = new ZipCodesRange($mysql,$zip,$miles);
$zcr->setNewOrigin($zip);
//if user entered a zip code ex. "08026"
if($zcr->validateZipCode($zip)) {
$citystate=$zcr->getCityState($zip);
echo "Zip Codes Within " . $miles ." miles of " . $citystate[0] . ", " . $citystate[1] . " " . $zip;
}
$zcr->setZipCodesInRange();
$zipArray = $zcr->getZipCodesInRange();
asort($zipArray);
$z = implode(",", array_keys($zipArray));
$q = "SELECT * FROM " . TBL_PUBS . " WHERE zip IN ($z) AND( status = 'Pending' OR status = 'Active' )";
$result = $mysql->query($q);
while ($row = $result->fetch_object()) {
$lonlat=$zcr->getLonLat($row->zip);
$distance = $zcr->calculateDistance($lonlat[1], $lonlat[0], $zip);
?>
Was able to solve it using this function...
returns an array of $arr[city] $arr[state] $arr[zip]
function retcszarr($loc){
$usstatenames=array('ALABAMA','ALASKA','AMERICAN SAMOA','ARIZONA','ARKANSAS','CALIFORNIA','COLORADO','CONNECTICUT','DELAWARE','DISTRICT OF COLUMBIA','FEDERATED STATES OF MICRONESIA','FLORIDA','GEORGIA','GUAM','HAWAII','IDAHO','ILLINOIS','INDIANA','IOWA','KANSAS','KENTUCKY','LOUISIANA','MAINE','MARSHALL ISLANDS','MARYLAND','MASSACHUSETTS','MICHIGAN','MINNESOTA','MISSISSIPPI','MISSOURI','MONTANA','NEBRASKA','NEVADA','NEW HAMPSHIRE','NEW JERSEY','NEW MEXICO','NEW YORK','NORTH CAROLINA','NORTH DAKOTA','NORTHERN MARIANA ISLANDS','OHIO','OKLAHOMA','OREGON','PALAU','PENNSYLVANIA','PUERTO RICO','RHODE ISLAND','SOUTH CAROLINA','SOUTH DAKOTA','TENNESSEE','TEXAS','UTAH','VERMONT','VIRGIN ISLANDS','VIRGINIA','WASHINGTON','WEST VIRGINIA','WISCONSIN','WYOMING');
$usstateabbrs=array('AL','AK','AS','AZ','AR','CA','CO','CT','DE','DC','FM','FL','GA','GU','HI','ID','IL','IN','IA','KS','KY','LA','ME','MH','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','MP','OH','OK','OR','PW','PA','PR','RI','SC','SD','TN','TX','UT','VT','VI','VA','WA','WV','WI','WY');
if(strpos($loc,',')!==false){
$parts=array_map('trim',explode(',',$loc));
$location['city']=strtoupper($parts[0]);
preg_match('/([^ ]*)(?: +([^ ]+))?/',$parts[1],$statezip);
if(isset($statezip[1])){
$location['state']=strtoupper($statezip[1]);
}
if(isset($statezip[2])){
$location['zip']=$statezip[2];
}
} else {
$parts=array_map('trim',explode(' ',$loc));
while(count($parts)>0){
$part=strtoupper(array_pop($parts));
if(in_array($part,$usstateabbrs)){
$location['state']=$part;
} elseif (in_array($part,$usstatenames)){
$location['state']=$usstateabbrs[array_search($part,$usstatenames)];
} elseif (preg_match('/\d+(?:-\d+)?/',$part,$zip)){
$location['zip']=$zip[0];
} else {
$location['city']=strtoupper(implode(' ',$parts)."$part");
break;
}
}
}
ksort($location);
return $location;
}