Popup appears that warns me of the unavailability for that country - php

I'm having some problems with this PHP script for managing a db of an elusive travel agency
Basically what I would like to do is:
check that the form fields have all been filled in, if so
then, I check the number of travel packages available for that country...
if there are any then the booking request has been completed successfully and I will reduce the packages available for that country by 1, if there are none then a popup will appear that will warn of unavailability for that country.
The problem is that when I complete the form by putting a country X as a destination, even if there are packages available for that country X, the popup appears that warns me of the unavailability for that country.
<?php
$msg1 = 'You have not filled in all fields!' ;
$msg2 = 'Booking request made successfully' ;
$msg3 = 'There are no packages available for this destination';
$connection = mysqli_connect('localhost','root','','book_db');
if(isset($_POST['send'])){
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$location = $_POST['location'];
$guests = $_POST['guests'];
$arrivals = $_POST['arrivals'];
$leaving = $_POST['leaving'];
$request1 = "SELECT n_package FROM destination
WHERE country= '$location' ";
$res = mysqli_query($connection, $request1);
if(empty($name) || empty($email) || empty($phone)
|| empty($address) || empty($location) || empty($guests)
|| empty($arrivals) || empty($leaving))
{
echo '<script>
alert("'.$msg1.'");
</script>';
} else if($res>0) {
//scala di 1
$request2 = "UPDATE destination
SET n_package=n_package-1
WHERE country= '$location' ";
mysqli_query($connection, $request2);
echo '<script>
alert("'.$msg2.'");
</script>';
}else if($res<1){
echo '<script>
alert("'.$msg3.'");
</script>';
}
} else {
echo 'something went wrong try again';
}
?>

You need to fetch the rows from the resultset created by a query.
You need to watch out for SQL Injection Attack
<?php
$msg1 = 'You have not filled in all fields!' ;
$msg2 = 'Booking request made successfully' ;
$msg3 = 'There are no packages available for this destination';
$connection = mysqli_connect('localhost','root','','book_db');
if(isset($_POST['send'])){
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$location = $_POST['location'];
$guests = $_POST['guests'];
$arrivals = $_POST['arrivals'];
$leaving = $_POST['leaving'];
$request1 = "SELECT n_package FROM destination WHERE country= ?";
$stmt = $connection->prepare($request1);
$stmt->bind_param("s", $_POST['location']);
$stmt->execute($connection, $request1);
$res = $stmt->get_result();
$row = $res->fetch_assoc();
Now $row['n_package'] is the number of packages available. Use that in your number checks.
In your tests though, you echo a little piece of javascript but that is ALL you echo, so that will be the complete content of the page. No <html> no <head> no <body> basically not a valid piece of HTML for the browser to build a page from.

Related

How to end PHP process if variable is blank/null

I have a form submission page that POSTS the fields to a confirmation page that sends an email using PHP but I keep getting blank emails when the page is ran as a stand alone page instead of from the form submission page. The form has 'required', but I want to add a statement to the PHP that stops the process if the $email variable is blank/null.
<?php
// variables start
$team = $_POST['team'];
$manager = $_POST['manager'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$classification = $_POST['classification'];
$registration = $_POST['registration'];
$division = $_POST['division'];
// variables end
// email start
$subject = "Thank you for registering you team";
$message = "<html>...
In addition to stopping the process if the $email variable is blank/null, I also want to redirect the user to our home page.
You should be able to do something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['email'])) {
// variables start
$team = $_POST['team'];
$manager = $_POST['manager'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$classification = $_POST['classification'];
$registration = $_POST['registration'];
$division = $_POST['division'];
// variables end
// email start
$subject = 'Thank you for registering you team';
$message = '<html>...';
} else {
header('Location: https://example.com');
}
Simplest way:
...
// variables end
if( ! (!isset($email) || trim($email) === '') ){
header("Location: homepage.php");
exit();
}
// email start
...
Note the exit() statement after the redirection: without exit() or die() the PHP script could be continue the execution resulting in possible unexpected behaviour.

PHP error posting form data to database

I am trying to make a post-ad form add data to a database. The page keeps reloading and asking to fill in all the details. I cannot seem to find the error and i have done a lot of searching on google and youtube, all to no avail. Please help!!!
<?php
session_start();
include'db.php';
$name = $_POST['name'];
$email = $_POST['email'];
$phoneNumber = $_POST['mobile-num'];
$photos = $_POST['fileselect'];
$town = $_POST['location'];
$category = $_POST['category'];
$adTitle = $_POST['title'];
$adDescription = $_POST['description'];
if(isset($_SESSION['email']))
{
if($email != "" && $name != "" && $phoneNumber != "" && $photos != "" && $town != "" && $category != "" && $adTitle !="" && $adDescription != "")
{
$name = stripslashes($name);
$email = stripslashes($email);
$phoneNumber = stripslashes($phoneNumber);
$photos = stripslashes($photos);
$town = stripslashes($town);
$adTitle = stripslashes($adTitle);
$category = stripslashes($category);
$adDescription = stripslashes($adDescription);
$name = mysqli_real_escape_string($connection,$name);
$email = mysqli_real_escape_string($connection,$email);
$phoneNumber = mysqli_real_escape_string($connection,$phoneNumber);
$photos = mysqli_real_escape_string($connection,$photos);
$town = mysqli_real_escape_string($connection,$town);
$adTitle = mysqli_real_escape_string($connection,$adTitle);
$category = mysqli_real_escape_string($connection,$category);
$adDescription = mysqli_real_escape_string($connection,$adDescription);
$imagePath = "images/".basename($_FILES['fileselect']['MAX_FILE_SIZE']);
$photo = $_FILES['fileselect']['MAX_FILE_SIZE'];
$date = date("j F Y");
if(filter_var($email,FILTER_VALIDATE_EMAIL))
{
mysqli_query($connection, "SELECT email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date from ads");
$insertQuery = mysqli_query($connection, "INSERT INTO ads(email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date)
VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
header("Location: /profile.php");
}
else
$_SESSION['errorMessage'] = "Please check email pattern";
header("Location: /post-ad.php");
}
else
$_SESSION['errorMessage'] = "Please input all the required details";
header("Location: /post-ad.php");
}
else
header("Location: /login.php");
?>
That's the PHP code.
Since I am not very good with Stackoverflow, I am having issues formatting the html form code i wanted to post here. I will attach an image instead. Html form code for the post-ad form
Not sure why you are running the SELECT, as you seem to do nothing with it and no parameters. But the INSERT should be...
$insertQuery = mysqli_query($connection, "INSERT INTO ads(email,`ad-title`,`ad-category`,`ad-description`,`Photos`,`Name`,`Mobile-Num`,`Town`,`date`)
VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
When you have column names with hyphens in them it should be enclosed in back-ticks, either that of I would recommend (if not tooo late ) to remove the hyphens and use an underscore instead.
You should also check for errors when running any SQL and do some sort of processing with them.
Thanks Guys for the help. Sorry for putting you all through the stress. I went through my database structure and found a column with the wrong type that was preventing the sql insert query. My apologies....

How to echo Empty Entry Prohibited Message generated from a query in php?

I have a form which when submitted, checks this query ->
if(isset($_POST['update']) && !empty($_POST['name']) && !empty($_POST['reg_name']))
I want to echo a message "Please fill up all the required fields." if the required fields are not filled up.
In short, it should highlight the field name which is not filled up.
The Full Code:
include ('database/abcd.php');
if ($con->connect_error)
{
die("Connection failed: " . $con->connect_error);
}
if(isset($_POST['update']))
{
$error = array();
if(empty($_POST['name']))
$error[] = 'Please fill name field';
if(empty($_POST['reg_name']))
$error[] = 'Pleae fill reg_name field';
if(count($error) < 1)
{
$name = $_POST['name'];
$reg_name = $_POST['reg_name'];
$established = $_POST['established'];
$industry = $_POST['industry'];
$about = $_POST['about'];
$website = $_POST['website'];
$mail = $_POST['mail'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$facebook = $_POST['facebook'];
$wiki = $_POST['wiki'];
$twitter = $_POST['twitter'];
$google = $_POST['google'];
$member_username = $_SESSION['username'];
$process="INSERT INTO notifications (member_username, process, icon, class) VALUES ('$_POST[member_username]','$_POST[process]','$_POST[icon]','$_POST[class]')";
if (!mysqli_query($con,$process))
{
die('Error: ' . mysqli_error($con));
}
$sql = "UPDATE `company_meta` SET `name` = '$name', reg_name = '$reg_name', wiki = '$wiki', established = '$established', industry = '$industry', about = '$about', website = '$website', mail = '$mail', phone = '$phone', address = '$address', city = '$city', facebook = '$facebook', twitter = '$twitter', google = '$google' WHERE `member_username` = '$member_username'";
if ($con->query($sql))
{
header('Location: edit.php');
}
}
else
{
$errors = implode(',' $error);
echo $errors;
}
$con->close();
}
I think what you are pass in name or reg_name is check first .may be name or reg_name can content white space so that it not showing message otherwise above code is working correctly..
if(isset($_POST['update'])) // This first check whether it is an update call
{
$error = array(); // Here we initialize an array so that we can put the messages in it.
if(empty($_POST['name'])) // If the name field is empty, push a message in $error array.
$error[] = 'Please fill name field';
if(empty($_POST['reg_name'])) // Same as above field
$error[] = 'Pleae fill reg_name field';
if(count($error) < 1) // Now this checks if the $error array has no value. If it has value it means that either or both of the above fields are empty and the else block will be executed.
{
// Submit your form
}
else
{
$errors = implode(',' $error);
echo $errors;
}
}
else
{
// Update not triggered.
}

How to Set HTML Text to Server Information

I've tried things like setting a $var to the MySQL information (such as name or password), then pulling it with PHP, but I cannot figure the PHP out to do so. I use the server connect code as well. I have checked ASP.net out, but don't find any information on altering HTML text to equal SQL information. How might I go about accomplishing this?
One example: The account balance on my website is displayed in the bottom right corner, but I need to pull the balance from a column of my table from my database. What code would I use to set that paragraph element to the server value of account_balance?
My PHP/SQL for Registration:
<?php
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
$email = $_POST['email'];
$emailConfirm = $_POST['confirmemail'];
$password = $_POST['password'];
$passwordConfirm = $_POST['confirmpassword'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$countryCode = $_POST['countrycode'];
$phoneNumber = $_POST['phone'];
$address = $_POST['address'];
$zipCode = $_POST['zipcode'];
$city = $_POST['city'];
$state = $_POST['state'];
$country = $_POST['country'];
$dateOfBirth = $_POST['birthdate'];
$registerDate = "CURDATE()";
$registerTime = "CURTIME()";
$paymentMethod = $_POST['moneymethod'];
if($email == $emailConfirm && $password == $passwordConfirm){
if(!empty($email) && !empty($_POST['confirmemail']) && !empty($password) && !empty($_POST['confirmpassword']) && !empty($fname) && !empty($lname) && !empty($countryCode) && !empty($phoneNumber) && !empty($address) && !empty($zipCode) && !empty($city) && !empty($state) && !empty($country) && !empty($paymentMethod)){
$query = "INSERT INTO user_information (email,password,f_name,l_name,country_code,phone_number,address,city,state,zip_code,country,money_option,join_date,join_time) VALUES ('$email','$password','$fname','$lname','$countryCode','$phoneNumber','$address','$city','$state','$zipCode','$country','$paymentMethod','$registerDate','$registerTime')";
$data = mysql_query ($query)or die(mysql_error());
if($data){
header( 'Location: http://www.madmater.com/register/success.php' );
}else{
echo "Unknown Error!";
}
}else{
echo 'Please fill out all required fields before completing your registration!';
}
}else{
echo 'Your passwords or emails do not match!';
}
?>
I have only tried a simple PHP command, as it is the only thing I could think of, being new to MySQL.
$fname = $_POST['fname']; //From form
echo "<script type="text/javascript">document.getElementById("fname-holder").innerHTML($fname);</script>";
Even a hint of where to start would help, and thank you in advanced.
Since I don't know which row your account balance is called, I've used account_balance as an example in order to get you started.
Here is a basic method to retrieve information from your database:
$fname = stripslashes($_POST['fname']);
$fname = mysql_real_escape_string($_POST['fname']);
// or if DB connnection is required
// $fname = mysql_real_escape_string($_POST['fname'], $db);
$query = "SELECT * FROM user_information WHERE f_name = '$fname'";
while($row = mysql_fetch_array($query)){
$user = $row['f_name'];
$balance = $row['account_balance'];
echo "Username: " . $user;
echo "<br>";
echo "Balance: " . $balance;
}
or mysql_fetch_assoc() depending on what method you wish to use.
For more information on MySQL's SELECT, visit:
http://dev.mysql.com/doc/refman/5.0/en/select.html
You can also try:
$row = mysql_fetch_array($query);
foreach($row as $r) {
echo $r . "<br>";
}
or:
$row = mysql_fetch_assoc($query);
foreach($row as $r) {
echo $r . "<br>";
}
Footnotes:
I have to state that your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
There is no sql code in this example. Besides the error i found in this code of PHP for ' is not used.
$fName = $_POST['fname'] //This is from my register form
echo "<script type='text/javascript'>document.getElementById('fname-field').innerHTML(".$fname.");</script>";
and try to give some insert/update code also.
Use form submit your values,
In that form in action give register.php
echo "<pre>";
print_r($_post);
echo"</pre>;
use that you got value
then $name= $_post['name']
$query = "INSERT INTO "Tablename" set name= '".$name."',addeddate=now();
This way you can write.

Registration module in php error when uploaded on server

I am using registration module in which i first collect data from user and store it to a temporary database('tmp_users') and send a link via email,on clicking link via email user can activate their account(i am moving data to permanent table 'users').i have following files
studentregistration.php(A UI for registration)
processlogin.js (processing form data via jquery)
register.php (script for moving user data to 'tmp_users' and sending them link)
confirm.php(making user permanent,moving 'tmp_users' data to 'users')
in register.php i am seting two session variable $_session['email'],$_session['confirmation'] and i am generating one random unique num via
uniqid(rand()) and sending this in email as passkey which i again use in confirm.php and getting it from url by $_GET['passkey'] if passkey matched than confirming registration otherwise not.
now the problem is that this script executed successfully on my local machine but does not executed on my server.
thank in advance.......
Code for confirm.php
<?php
error_reporting(0);
require 'db/connect.php';
if(session_start())
{
$confirmation = $_GET['passkey'];
$result=$db->query("select * from tmp_users where passkey = '$confirmation'");
$count = $result->num_rows;
if($count == 1)
{
$rows = $result->fetch_all(MYSQLI_ASSOC);
/*print_r($rows);*/
foreach($rows as $row)
{
$eno = $row['eno'];
$fname = $row['fname'];
$lname = $row['lname'];
$sem = $row['sem'];
$branch = $row['branch'];
$mail = $row['mail'];
$contact = $row['contact'];
$password =$row['password'];
}
//making user permenant
$insert=$db->prepare("insert into users(eno,fname,lname,sem,branch,mail,contact,password) values(?,?,?,?,?,?,?,?)");
$insert->bind_param('ississss',$eno,$fname,$lname,$sem,$branch,$mail,$contact,$password);
$insert->execute();
$rowsaffected = $insert->affected_rows;
if($rowsaffected==1){
if($delete=$db->query("delete from tmp_users where passkey='$confirmation'"))
echo"<script>alert('Activated!!! Login Now');document.location='studentlogin.php';</script>";
else
echo "error";
}else{
echo"<script>alert('Error activating account');document.location='index.php';</script>";
}
}else{
echo"<script>alert('You are not registered');document.location='studentregistration.php';</script>";
}
}else
{
header('location:index.php');
}
?>
code for register.php
<?php
session_start();
require '../db/connect.php';
require '../phpmailer/class.phpmailer.php';
require '../mailfunction.php';
$confirmation = md5(uniqid(rand()));
$eno = $_POST['eno'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sem = $_POST['sem'];
$branch= $_POST['branch'];
$mail = $_POST['mail'];
$contact = $_POST['contact'];
$pw = $_POST['pw'];
$password = md5($pw);
$query = ("insert into tmp_users(passkey,eno,fname,lname,sem,branch,mail,contact,password) values (?,?,?,?,?,?,?,?,?);");
$result = $db->prepare($query);
$result->bind_param('sississss',$confirmation,$eno,$fname,$lname,$sem,$branch,$mail,$contact,$password);
if($result->execute()){
$_SESSION['mail']= $mail;
$_SESSION['confirmation'] = $confirmation;
$ToEmail = $mail;
$subject = "Activate your account";
$header = 'FROM:VGECG-LIBRARY <noreply#vgecg.ac.in>';
$MessageHTML = "Click link below to activate your account \r\n";
$MessageHTML.="<a href='localhost/projectlibrary/confirm.php?passkey=$confirmation'>Click here</a>";
$MessageTEXT='';
if(SendMail($ToEmail, $MessageHTML, $MessageTEXT))
{
print "1";
}
else {
print "";
}
}
?>

Categories