I have a form with file upload and user name exits checking conditions.
What im facing it the data are not getting insert in mysql db. file as been successfully saved in given path. kindly help me on this im wasted already 2days with that i tried a lot myself.
form.php
<table style="text-align:right">
<form id="add" method="POST" action="action.php" enctype="multipart/form-data">
<tr>
<h4 class='bg-info'>
<br/>         Become a Member of jobportal and find the right job. Create your Profile now, Free!<br/><br/>
</h4>
</tr>
<tr>
<td></td>
<td> * Mandatory Fields </td>
</tr>
<tr>
<div class="col-md-1"></div>
<td>Enter Your Email-ID: *</td>
<td><input class="form-control input-sm" placeholder="Email ID" type="textfield" name="email"required></td>
</tr>
<tr>
<td>Choose password *</td>
<td><input class="form-control input-sm" placeholder="Enter Your Password" type="password" name="password"required/></td>
</tr>
<td>Re-Enter Your password *</td>
<td><input class="form-control input-sm" placeholder="Enter Your Password" type="password" name="repassword"required/></td>
</tr>
<tr>
<td> Please Enter Your Full Name:</td>
<td> <input class="form-control input-sm" placeholder="Enter Full Name" type="textfield" name="name"required></td>
</tr>
<tr>
<td>Your Current Location: *<td>
<select class="form-control input-sm" required name="location">
<option value='' disabled selected style='display:none;'>Select location *</option>
<option>Andhra Pradesh</option>
<option>Arunachal Pradesh</option>
<option>Assam</option>
<option>Bihar</option>
<option>Chhattisgarh</option>
<option>Goa</option>
<option>Gujarat</option>
<option>Haryana</option>
<option>Himachal Pradesh</option>
<option>Jammu and Kashmir</option>
<option>Jharkhand</option>
<option>Karnataka</option>
<option>Kerala</option>
<option>Madhya Pradesh</option>
<option>Maharashtra</option>
<option>Maharashtra</option>
<option>Manipur</option>
<option>Meghalaya</option>
<option>Mizoram</option>
<option>Nagaland</option>
<option>Odisha</option>
<option>Punjab</option>
<option>Rajasthan</option>
<option>Sikkim</option>
<option>Tamil Nadu</option>
<option>Telangana</option>
<option>Tripura</option>
<option>Uttar Pradesh</option>
<option>Uttarakhand</option>
<option>West Bengal</option>
</select></td>
</td>
</tr>
<tr>
<td>Enter Your Mobile Number: *</td>
<td><input class="form-control input-sm" placeholder="mobile number" type="textfield" name="mobilenumber" required/></td>
</tr>
<tr>
<td>Experience:</td>
<td>
<select class="form-control input-sm" required name="experience">
<option value='' disabled selected style='display:none;'>Select Experience</option>
<option>Fresher</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</td>
</tr>
<tr>
<td>Key Skill: *</td>
<td>
<input class="form-control input-sm" placeholder="Enter Your Skill" type="textfield" name="keyskill"/>
</td>
</tr>
<tr>
<td>Please Select your PG Degree</td>
<td>
<select class="form-control input-sm" required name="degree">
<option value='' disabled selected style='display:none;'>Select Degree</option>
<option>B.sc</option>
<option>B.E</option>
<option>B.Com</option>
<option>others</option>
</select>
</td>
</tr>
<tr>
<td>Please Select Higher Studies:</td>
<td>
<select class="form-control input-sm" required name="hsc">
<option value='' disabled selected style='display:none;'>Select Higher Studies</option>
<option>HSC</option>
<option>Diploma</option>
<option>ITI</option>
<option>others</option>
</select>
</td>
</tr>
<tr>
<td>Please Select your Gender: *</td>
<td>
<select class="form-control input-sm" required name="gender">
<option value='' disabled selected style='display:none;'>Select</option>
<option>Male</option>
<option>Female</option>
<option>others</option>
</select>
</td>
</tr>
<tr>
<td>Upload your Resume :</td>
<td><input type="file" name="filep"></td>
</tr>
<tr>
<td> </td>
<td>by clicking register u accepting our terms and condtions. click here !</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="add" class="btn btn-info btn-sm" id="add" value="Register With JobPortal">
</td>
</tr>
</form>
</table>
action.php
$con = mysqli_connect('localhost','root','');
if (!$con) {
die('Could not connect: ' . mysql_error());
} else {
echo 'connected';
}
if (isset($_POST['add']) ) {
if (!get_magic_quotes_gpc() ) {
$email = addslashes ($_POST['email']);
} else {
$email = $_POST['email'];
}
$email = $_POST['email'];
$password = md5 ($_POST['password']);
$name = $_POST['name'];
$location = $_POST['location'];
$mobilenumber = $_POST['mobilenumber'];
$experience = $_POST['experience'];
$keyskill = $_POST['keyskill'];
$degree = $_POST['degree'];
$hsc = $_POST['hsc'];
$gender = $_POST['gender'];
$resume = $_FILES['filep']['name'];
$folder = "C:/wamp/www/userlogin/pic/";
$name="SELECT emailid FROM userregistration WHERE emailid='$email'";
mysqli_select_db($con, 'login');
$result = mysqli_query($con, $name);
if (mysqli_num_rows($result)!=0) {
echo "Username already exists";
} else {
echo"data entered done";
}
if (move_uploaded_file($_FILES["filep"]["tmp_name"], $folder . $_FILES["filep"]["name"])) {
echo "images moved sus";
} else {
echo "not done";
}
echo "<p align=center>File ".$_FILES["filep"]["name"]."loaded...";
$sql = "INSERT INTO userregistration "
. "(email, password, name, location, mobilenumber, experience, keyskill, degree, hsc, gender, resume)"
. "VALUES('$email', '$password', '$name', '$location', '$mobilenumber', '$experience', '$keyskill',
'$degree', '$hsc', '$gender', '$resume')";
mysqli_select_db($con, 'login');
$retval = mysqli_query($con, $sql);
if (!$retval) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
echo' insert more data ';
mysqli_close($con);
}
What I exactly need is: I want to upload form data with the file url into database and need to check email id or name already exits.
I only get error in $sql = "insert into" portion other than else working fine.
Thanks in advance.
echo your sql query before
mysqli_select_db($con, 'login');
and execute it in your Mysql phpmyadmin...
I guess there is some problem in your query formation, spacing between words or something.
Errors
Missing database name
mysqli_connect("localhost","root","","login");
And error in $sql query
So final well-From code is
<?php
$con= mysqli_connect("localhost","root","","login");;//missing database
if (! $con)
{
die('Could not connect: ' . mysql_error());
}
else{
echo 'connected';
}
if(isset($_POST['add']))
{
if(! get_magic_quotes_gpc() )
{
$email = addslashes ($_POST['email']);
}
else
{
$email = $_POST['email'];
}
$email = $_POST['email'];
$password = md5 ($_POST['password']);
$name = $_POST['name'];
$location = $_POST['location'];
$mobilenumber = $_POST['mobilenumber'];
$experience = $_POST['experience'];
$keyskill = $_POST['keyskill'];
$degree = $_POST['degree'];
$hsc = $_POST['hsc'];
$gender = $_POST['gender'];
$resume = $_FILES['filep']['name'];
$folder = "C:/wamp/www/userlogin/pic/";
$query001="SELECT emailid FROM userregistration WHERE emailid='$email'";
$result = mysqli_query($con, $query001);
if(mysqli_num_rows($result)!=0){
echo "Username already exists";
}
else
{
echo"data entered done";
if (move_uploaded_file($_FILES["filep"]["tmp_name"], $folder . $_FILES["filep"]["name"]))
{
echo "images moved sus";
}
else
{
echo "not done";
}
echo "<p align=center>File ".$_FILES["filep"]["name"]."loaded...";
$sql = "INSERT INTO userregistration (email, password, name, location, mobilenumber, experience, keyskill,
degree, hsc, gender, resume) VALUES('$email','$password','$name','$location','$mobilenumber','$experience','$keyskill','$degree','$hsc','$gender','$resume')";
$retval = mysqli_query($con, $sql);
if(!$retval )
{
die('Could not enter data: ' . mysql_error());
}
else
{
echo "Entered data successfully\n";
echo' insert more data ';
mysqli_close($con);
}
}
}
?>
and be aware with MySQL Injection.
simply you can use mysqli_real_escape_string()
Example
$name = mysqli_real_escape_string($_POST['name']);
Tip from(Comment)
You have $name declared twice in your code - rename the $name select statement. ($name = $_POST['name']; and also $name="SELECT emailid FROM userregistration WHERE emailid='$email'"; ) – Jesse C
Related
I'm learning PHP and I struggle to find solutions to my issue. I've created a page where membership data can be edited. All my 'type=text' fields display the current value of the member correctly. But the values selected on the 2 drop down fields (Language and Interest) do not display in the edit field. They do update though to MySql but the 'Select One...' option display when I want to edit the members 'Language' and 'Interest' fields.
What should I do so that the current value of the 2 drop downs that is stored in the db, displays on the ui when a member needs to get edited?
Here is my PHP code:
<?php
$id = isset($_GET['id']) ? $_GET['id'] : die('ERROR: Record ID not Found');
include('dbconnect.php');
try{
$sql = "SELECT id, firstName, lastName, idNumber, mobileNumber, email, birthDate, languageType, interest FROM members WHERE id = ? LIMIT 0,1";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$idNumber = $row['idNumber'];
$mobileNumber = $row['mobileNumber'];
$email = $row['email'];
$birthDate = $row['birthDate'];
$languageType = $row['languageType'];
$interest = $row['interest'];
}
catch(PDOException $exception){
die('ERROR: '.$exception->getMessage());
}
?>
<?php
$id = isset($_GET['id']) ? $_GET['id'] : die('ERROR: Record ID not found.');
include 'dbconnect.php';
if($_POST){
try{
$sql = "UPDATE members SET
firstName=:firstName,
lastName=:lastName,
idNumber=:idNumber,
mobileNumber=:mobileNumber,
email=:email,
birthDate=:birthDate,
languageType=:languageType,
interest=:interest
WHERE id=:id";
$stmt = $conn->prepare($sql);
$firstName = htmlspecialchars(strip_tags($_POST['firstName']));
$lastName = htmlspecialchars(strip_tags($_POST['lastName']));
$idNumber = htmlspecialchars(strip_tags($_POST['idNumber']));
$mobileNumber = htmlspecialchars(strip_tags($_POST['mobileNumber']));
$email = htmlspecialchars(strip_tags($_POST['email']));
$birthDate = htmlspecialchars(strip_tags($_POST['birthDate']));
$languageType = $_POST['languageType'];
$interest = $_POST['interest'];
$stmt->bindParam(':firstName', $firstName);
$stmt->bindParam(':lastName', $lastName);
$stmt->bindParam(':idNumber', $idNumber);
$stmt->bindParam(':mobileNumber', $mobileNumber);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':birthDate', $birthDate);
$stmt->bindParam(':languageType', $languageType);
$stmt->bindParam(':interest', $interest);
$stmt->bindParam(':id', $id);
if($stmt->execute()){
echo "<div class='alert alert-success'>Member was updated.</div>";
}else{
echo "<div class='alert alert-danger'>Unable to update member. Please try again.</div>";
}
}
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
}
?>
And here is the html:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"] . "?id={$id}");?>" method="post">
<table class='table table-hover table-responsive table-bordered'>
<tr>
<td>First Name</td>
<td><input type='text' name='firstName' value="<?php echo htmlspecialchars($firstName, ENT_QUOTES); ?>" class='form-control' /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type='text' name='lastName' value="<?php echo htmlspecialchars($lastName, ENT_QUOTES); ?>" class='form-control' /></td>
</tr>
<tr>
<td>ID Number</td>
<td><input type='text' name='idNumber' value="<?php echo htmlspecialchars($idNumber, ENT_QUOTES); ?>" class='form-control' /></td>
</tr>
<tr>
<td>Mobile Number</td>
<td><input type='text' name='mobileNumber' value="<?php echo htmlspecialchars($mobileNumber, ENT_QUOTES); ?>" class='form-control' /></td>
</tr>
<tr>
<td>Email</td>
<td><input type='text' name='email' value="<?php echo htmlspecialchars($email, ENT_QUOTES); ?>" class='form-control' /></td>
</tr>
<tr>
<td>Birth Date</td>
<td><input type='date' name='birthDate' value="<?php echo htmlspecialchars($birthDate, ENT_QUOTES); ?>" class='form-control' /></td>
</tr>
<tr>
<td>Language</td>
<td>
<select name='languageType' class='form-control' value="<?php echo $languageType; ?>" />
<option>Select One...</option>
<option>Afrikaans</option>
<option>English</option>
<option>Zulu</option>
<option>Xhosa</option>
<option>Venda</option>
<option>French</option>
</td>
</tr>
<tr>
<td>Interest</td>
<td>
<select name='interest' class='form-control' value="<?php echo htmlspecialchars($interest, ENT_QUOTES); ?>" />
<option>Select One...</option>
<option>Golf</option>
<option>Rugby</option>
<option>Tennis</option>
<option>Cricket</option>
<option>Swimming</option>
<option>Hiking</option>
<option>Surfing</option>
<option>Movies</option>
<option>Swords</option>
</td>
</tr>
<tr>
<td></td>
<td>
<input type='submit' value='Save Changes' class='btn btn-primary' />
<a href='index.php' class='btn btn-danger'>Back to read members</a>
</td>
</tr>
</table>
</form>
This is all wrong :
<select name='languageType' class='form-control' value="<?php echo $languageType; ?>" />
<option>Select One...</option>
<option>Afrikaans</option>
<option>English</option>
<option>Zulu</option>
<option>Xhosa</option>
<option>Venda</option>
<option>French</option>
<select name='interest' class='form-control' value="<?php echo htmlspecialchars($interest, ENT_QUOTES); ?>" />
<option>Select One...</option>
<option>Golf</option>
<option>Rugby</option>
<option>Tennis</option>
<option>Cricket</option>
<option>Swimming</option>
<option>Hiking</option>
<option>Surfing</option>
<option>Movies</option>
<option>Swords</option>
The Select does not have a value attribute, the value attribute belong to option.
this is how your select should look :
<select name='languageType' class='form-control' />
<option value="Afrikaans">Afrikaans</option>
... <!-- Other options just like I did the first one -->
</select>
if you want the value from the database to be selected then you will need to check if the option is not equal to the db value then select it with the selected attribute of option.
like :
<select name='languageType' class='form-control' />
<option value="">Select One...</option>
<option value="Afrikaans"<?php if($languageType == "Afrikaans"){echo "selected='selected'";?>>Afrikaans</option>
<option value="English" <?php if($languageType == "English"){echo "selected='selected'";?>>English</option>
<option value="Zulu" <?php if($languageType == "English"){echo "selected='selected'";?>>Zulu</option>
<option value="Xhosa" <?php if($languageType == "Xhosa"){echo "selected='selected'";?>>Xhosa</option>
<option value="Venda" <?php if($languageType == "Venda"){echo "selected='selected'";?>>Venda</option>
<option value="French" <?php if($languageType == "French"){echo "selected='selected'";?>>French</option>
</select>
Then do your second dropdown following the above as a guide, also don't forget to close the select option </select>
<?php include("header.php")?>
<?php include("menu.php")?>
<div id="registrationPage">
<div id="registrationDiv" ></div>
<fieldset id="registrationFieldPos">
<legend><h3>Register</h3></legend>
<form id="registrationForm" action="registrationaction.php" method="POST" enctype="multipart/form-data">
<table>
<tr>
<td><label>First Name :</label></td>
<td><input type="text" name="fname" /></td>
</tr>
<tr>
<td><label>Last Name :</label></td>
<td><input type="text" name="lname" /></td>
</tr>
<tr>
<td><label>Username :</label></td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td><label>Password :</label></td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td><label>Confirm Password :</label></td>
<td><input type="password" name="passwordconfirm" /></td>
</tr>
<tr>
<td><label>Email :</label></td>
<td><input type="email" name="email" /></td>
</tr>
<tr>
<td><label>Image :</label></td>
<td><input type="file" name="fileUpload" /></td>
</tr>
<tr>
<td><label>Country :</label></td>
<td>
<select name="country">
<?php
$connection = mysqli_connect('localhost', 'root', '', 'mutetistore') or die('connection error'. mysql_error());
mysqli_select_db($connection, 'mutetistore');
$sql = "SELECT * FROM apps_countries" ;
$results = mysqli_query($connection, $sql);
while($result = mysqli_fetch_array($results)):;
?>
<option value=" <?php echo $result['country_name']; ?> "> <?php echo $result['country_name'];?> </option>
<?php endwhile; ?>
</select>
</td>
</tr>
<tr>
<td><label>Languages :</label></td>
<td>
<label>English <input type="checkbox" name="Languages[]" value = "English" /></label>
<label>French<input type="checkbox" name="Languages[]" value = "French" /></label>
<label>Swahili<input type="checkbox" name="Languages[]" value = "Swahili" /></label>
</td>
</tr>
<tr>
<td><label>Gender:</label></td>
<td>
<label>Male <input type="radio" name="gender" value = "male"/></label>
<label>Female</label><input type="radio" name="gender" value = "female"/>
</td>
</tr>
<tr>
<td><input type="submit" name="save" value = "registered"/></td>
</tr>
</table>
</form>
</fieldset>
<div id="divEnd">
</div>
</div>
<?php include("footer.php")?>
<?php
require('databaseconn.php');
if(isset($_POST['save']) ) {
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$username = $_POST['username'];
$password = $_POST['password'];
$passwordconfirm = $_POST['passwordconfirm'];
$country = $_POST['country'];
$gender = $_POST['gender'];
$Languages = $_POST['Languages'];
$imagename = $_FILES['fileUpload']['name'];
$imagesize = $_FILES['fileUpload']['size'];
$imagetmp = $_FILES['fileUpload']['tmp_name'];
if(empty( $firstname)) {
echo "please enter username";
}else if(empty( $lastname)) {
echo "please enter lastname";
}else if(empty( $username)) {
echo "please enter username";
}else if(empty( $password)) {
echo "please enter password";
}else if(empty( $password !== $passwordconfirm)) {
echo "password do not match";
}else if(empty( $country)) {
echo "please select your country ";
}else if(empty( $gender)) {
echo "please select your gender ";
}else if(empty( $imagename)) {
echo "please select image";
}else {
$uploadFolder = "Uploads/";
$filename = rand(1000,100000)."-".$imagename;
$filenameUpload = move_uploaded_file($imagetm, $uploadFolder, $filename);
$sql = "INSERT INTO `register` (`id`, `firstname`, `lastname`, `username`, `password`, `country`, `gender`, `language`, `imageName`, `imageSize`, `imageTemp`)
VALUES (NULL, '$firstname', '$lastname', '$username', '$password', '$country', '$gender', '$Languages', '$filenameUpload', '$imagesize', '$imagetmp')";
}
}
?>
<?php echo $_POST["fname"]; ?><br>
<?php echo $_POST["lname"]; ?><br>
<?php echo $_POST["username"]; ?><br>
<?php echo $_POST["password"]; ?><br>
<?php echo $_POST["passwordconfirm"]; ?><br>
<?php echo $_POST["country"]; ?><br>
<?php echo $_POST["gender"]; ?><br>
<?php echo $_POST["password"]; ?><br>
<?php echo $_POST["passwordconfirm"]; ?><br>
<?php echo $_POST["country"]; ?><br>
This code is giving me headache. Could someone spot the error? I have tried it for a day without a solution. I want it to submit data to database (image ,checkbox,radio,etc). I want it to put all the selected checkboxs to database. I will later learn about the implode, exlode, to add commas to the code.
First two lines:
<?php include("header.php")?> <---- End the statement with ;
<?php include("menu.php")?> <---- Here too!
On Other Lines:
while($result = mysqli_fetch_array($results)):; <---What is this? It should be { //Code here
and The closing of while loop should be this! ->} not <?php endwhile; ?>
Here:
}else if(empty( $password !== $passwordconfirm)) { // Your Operation should be != and not !==
Maybe your id should be declared as an Auto-increment. And not to be added as NULL.
Youre full of headaches.. hahaha
This question already has answers here:
What does enctype='multipart/form-data' mean?
(9 answers)
Closed 6 years ago.
I have a simple registration form, in which I accept inputs from the user that includes an image, and insert the values in a table : temporary_employees table . In my code, I check whether the email id and the user id entered by the user already exists and if they dont , i go ahead and perform the insert after moving the image to a folder named 'images' . While running the code , I am getting an error Undefined index: image, on the line where I have the following piece of code :
$target_file = $target_path . basename ($_FILES['image']['name']);
The most interesting thing is the same line of code has worked perfectly well in another php file . I had given the same name for the input in the html form . . How is it possible ? Any help will be appreciated .
Here is my code :
//start the session before anything is echoed to the browser
if (session_status()===PHP_SESSION_NONE) {
session_start();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>
Login form
</title>
</head>
<body>
<h3>Registration Form</h3>
<form action ="" method="POST">
<table align="center" cellpadding="10">
<tr>
<td>Name</td>
<td><input type="text" maxlength='100' name="empname" id="empname" required></td>
</tr>
<tr>
<td>Email Id</td>
<td><input type="text" maxlength='100' name="emailid" id="emailid" required>
</td>
</tr>
<tr>
<td>User Id</td>
<td><input type="text" maxlength='100' name="userid" id="userid" required ></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" maxlength='100' name="pwd" id="pwd" required ></td>
</tr>
<tr>
<td>Date of Birth</td>
<td>
<select name='year'>
<option value='2015'>2015</option>
<option value='2016'>2016</option>
</select>
<select name='month'>
<option value='01'>January</option>
<option value='02'>February</option>
<option value='03'>March</option>
<option value='04'>April</option>
<option value='05'>May</option>
</select>
<select name='day'>
<option value='01'>1</option>
<option value='02'>2</option>
<option value='03'>3</option>
<option value='04'>4</option>
<option value='05'>5</option>
</select></td>
</tr>
<tr>
<td>Designation</td>
<td><input type="text" maxlength='100' name="designation" id="designation" required></td>
</tr>
<tr>
<td>Department</td>
<td><input type="text" maxlength='100' name="department" id="department" required></td>
</tr>
<tr>
<td>Image</td>
<td><input type="file" maxlength='100' name="image" required></td>
</tr>
<tr>
<td>
<input type="submit" name="login" value="Register Yourself">
</td>
</tr>
</table>
</form>
</body>
</html>
<?php
//create a connection
$conn = mysqli_connect('localhost', 'root', '', 'attendance');
//on the click of submit button
if (isset($_POST['login'])) {
//capture the $_POST values
$name = $_POST['empname'];
$name = trim($name);
$email = $_POST['emailid'];
$email = trim($email);
$userid = $_POST['userid'];
$userid = trim($userid);
$pwd = $_POST['pwd'];
$pwd = trim($pwd);
$desg = $_POST['designation'];
$desg = trim($desg);
$dept = $_POST['department'];
$dept = trim($dept);
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$date = $year.$month.$day;
//display a message if there is a blank entry for email
if ($email=="") {
echo "Please enter a valid email id";
}
//display a message if there is a blank entry for userid
if ($userid=="") {
echo "Please enter a valid User Id";
}
//check if the email id exists
$sql_check_email = "select * from employee where emp_email='$email';";
mysqli_query($conn, $sql_check_email);
$aff_email = mysqli_affected_rows($conn);
// if email id exists ..display message
if ($aff_email==1) {
$msgemail = "The email id exists";
echo $msgemail;
//display error message if there is an error
} else if ($aff_email>1) {
$msgemail = "There are multiple employees with the same email";
echo $msgemail;
//display message if there is an error firing the query
} else if ($aff_email<0) {
echo "There is an error ..Try again";
}
//check if the user id exists
$sql_check_userid = "select * from employee_login where emp_uid='$userid';";
mysqli_query($conn, $sql_check_userid);
$aff_userid = mysqli_affected_rows($conn);
if ($aff_userid==1) {
$umsg = "User id already exist";
echo $umsg;
//display error message if there is an error when the query is fired
} else if ($aff_userid<0) {
echo "There is an error ..Try again";
}
//if neither the user id nor the email id exist, upload image and do the insert
if ($aff_userid==0 && $aff_email==0) {
$target_path = "images/";
$target_file = $target_path . basename ($_FILES['image']['name']);
//if the image is moved to the images folder , do the insert
if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
$image = basename($_FILES['image']['name']);
$sql_ins = "INSERT INTO temporary_employee(emp_uid,emp_pwd,
emp_name,emp_email,emp_dob,emp_designation,
emp_department,emp_image)
VALUES('$userid','$pwd','$name','$email','$date',
'$desg','$dept','$image')";
mysqli_query($conn, $sql_ins);
$aff_insert = mysqli_affected_rows($conn);
//display success message if insert is successfull
if ($aff_insert==1) {
echo "You have successfully registered ...awaiting approval by admin";
//display message if there were no insert
} else if ($aff_insert==0) {
echo "The registration has failed ..Try again";
//diplay error message if there was an error while firing the insert query
} else if ($aff_insert<0) {
echo "There was an error ..Try again";
}
}
}
}
?>
While using Image Uploading in the form you have to use the enctype in the form attribute.
<form action ="" method="POST" enctype="multipart/form-data">
</form>
Change
<form action ="" method="POST">
to
<form enctype="multipart/form-data">
And try again.
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.
At present I have set 4 variables, the values of which are then stored into mysql. This works fine. However, I don't want to set the values but write a line of code that takes these values from my form (on the same page). I have set the form method to POST and added specialchars to help security. Can someone pretty please show me one or two lines of code so I don't have to write ="John Doe". Please remember that I am very new all of this
<?php
// Connect to the Database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "topsecretDontTell";
$dbname = "gaming";
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
// Show error if connection fails
if(mysqli_connect_errno()){
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() .")"
);
}
?>
<?php
// ordertbl
$customer_name = "John Doe";
$game_id = 3;
$reservation_start = "2015-01-05";
$requested_days = 1;
// removes single quotes (escapes strings)
$customer_name = mysqli_real_escape_string($connection, $customer_name);
//add into ordertbl
$query = "INSERT INTO ordertbl (customer_name,game_id,reservation_start,requested_days) VALUES ('{$customer_name}',{$game_id},'{$reservation_start}', {$requested_days})";
//Run query and test if there was a query error
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed.");
}
?>
<?php
//determine the name of the game via its id using a function
function GameTitle ($game_id){
$message = "";
if ($gameid ==1){
$message = "Fantasy World";
}
else if ($gameid ==2){
$message = "Sir Wags A Lot";
}
else if ($gameid ==3){
$message = "Take a Path";
}
else if ($gameid ==4){
$message = "River Clean Up";
}
else if ($gameid ==5){
$message = "PinBall";
}
else if ($gameid ==6){
$message = "Ghost girl";
}
else if ($gameid ==7){
$message = "Dress up";
}
else if ($gameid ==8){
$message = "Where is my hat?";
}
else {
$message = "Invalid ID";
}
return $message;
}
?>
</body>
</html>
<!--Link to the style sheet-->
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<!--Create Header (logo, title and navigation bar)-->
<body>
<div id='main'>
<div id='titleImage'><img title='Home' src='images/GLLogo.png' width='700' height='190' alt='Games Library Title' /></div>
<div id='menu-wrapper'>
<div id='menu'>
<ul>
<li><a href='index.html'>Home</a></li>
<li class='current_page_item'><a href='#'>Reservations</a></li>
</ul>
</div>
</div>
<!--Make the form-->
<div class="form">
<h1>Reservations</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="755" border="3" cellpadding="6">
<tr>
<td width="195" align="right" bgcolor="#FF0000"><label for="customer_name">Name:</label></td>
<td width="370"><input name="customer_name" autofocus type="text" id="customer_name" size="35" maxlength="90" required autocomplete="off" /></td>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="game_id">Game's ID:</label></td>
<td><input name="game_id" type="number" id="game_id" size="35" maxlength="50" min="1" /></td>
</tr>
<tr>
<td width="195" align="right" bgcolor="#FF0000"><button onClick="GameTitle(); return false">Search</button></td>
<td><input name="Result" type="text" id="demo" size="35" maxlength="50" /></td>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="Loan">Number of Days you wish to borrow the Game</label></td>
<td><select name="requested_days" id="requested_days">
<option selected="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
</tr>
<tr> <!--put date into value field to get a calendar-->
<td align="right" bgcolor="#FF0000"><label for="reservation">Reservation Date:</label></td>
<td><input id="reservation_start" input name="reservation_start" type="" value="" placeholder="YYYY/MM/DD" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" title="The date should be in the exact format: YYYY-MM-DD with leading zeros where necessary"/>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="mysearch2">Enter your search string here : </label></td>
<td><input {background-colour: #E5F5EF;} id="mysearch2" type="search" placeholder="search"size="35" maxlength="50"/>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><input type="reset" name="Reset" id="button" value="Reset Form" /></td>
<td><input type="submit" name="button2" id="button2" value="Submit Form" /></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
<?php
// get rid of data in cache and close
mysqli_close($connection);
?>
Use the following, taking the POST variable from your form's <input name="customer_name"... element:
$customer_name=stripslashes($_POST['customer_name']);
$customer_name=mysqli_real_escape_string($connection,$_POST['customer_name']);
which will allow for names containing apostrophes like John O'Reilly.
Plus, you have function GameTitle ($game_id) therefore you most likely meant to use function GameTitle ($gameid)
You should use $_POST. In that array are post data. For example:
$customer_name = $_POST['name'];
before anyone make a negative vote and criticize me i am new to the development and i need some hep in my queries using php and mysql
so i am trying to make the user insert some information in the register page that will submit information to the table named user that have these fields :
user_name,
first_name,
last_name,
address,
district_name,
village_name,
birth_date,
email_address,
specialization_name,
password,
registered_date
and i have another table with name specialization
that have these fields :
specialization_id
specilaization_name
what i need is that the user select the specialization in the register page but in the user table i need to use the specialization_id as a foreign key to the specialization table
the insert query that i use is :
$query = mysql_query("INSERT INTO user(user_name, first_name, last_name, address, district_name, village_name, birth_date, email_address, specialization_name, password, registered_date)VALUES('$username', '$fname', '$lname', '$country', '$district', '$village', '$bdate', '$email', '$specialization', '$pass1', now())")or die("could not insert data");
register.php
<?php require_once('for members/scripts/connect.php'); ?>
<?php
ob_start();
function countryQuery(){
$countryData = mysql_query("SELECT * FROM country") or die("could select database");
while($record = mysql_fetch_array($countryData)){
echo'<option value="' . $record['country_name'] . '">' . $record['country_name'] . '</option>';
}
}
function specializationQuery(){
$specData = mysql_query("SELECT * FROM specialization");
while($recordJob = mysql_fetch_array($specData)){
echo'<option value="' . $recordJob['specialization_name'] . '">' . $recordJob['specialization_name'] . '</option>';
}
}
function districtQuery(){
$distData = mysql_query("SELECT * FROM districts");
while($recorddist = mysql_fetch_array($distData)){
echo'<option value="' . $recorddist['district_name'] . '">' . $recorddist['district_name'] . '</option>';
}
}
function villageQuery(){
$villageData = mysql_query("SELECT * FROM village");
while($recordvillage = mysql_fetch_array($villageData)){
echo'<option value="' . $recordvillage['village_name'] . '">' . $recordvillage['village_name'] . '</option>';
}
}
//default value
$message = "Fields Marcked with an [*] are Required";
$username = "";
$fname = "";
$lname = "";
$specialization = "";
$email = "";
$pass1 = "";
$pass2 = "";
$district = "";
$village = "";
if(isset($_POST['username'])){
$username = mysql_real_escape_string($_POST['username']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$pass1 = mysql_real_escape_string($_POST['pass1']);
$pass2 = mysql_real_escape_string($_POST['pass2']);
$bdate = mysql_real_escape_string($_POST['birthdate']);
$country = mysql_real_escape_string($_POST['country']);
//$local_adress = $_POST['adress'];
$specialization = mysql_real_escape_string($_POST['specialization']);
$district = mysql_real_escape_string($_POST['district']);
$village = mysql_real_escape_string($_POST['village']);
//error handeling
if((!$username)||(!$fname)||(!$lname)||(!$email)||(!$pass1)||(!$pass2)||(!$specialization)||(!$district)||(!$village)){
$message = "**** Please insert the Required Fields below ****<br />";
if($fname == "")
{
$message = $message . "Enter First name<br/>";
}
if($lname == "")
{
$message = $message . "Enter Last name<br/>";
}
if($specialization == 0)
{
$message = $message . "Select Your Job<br />";
}
if($district == 0)
{
$message = $message . "Select Your District<br />";
}
if($village == 0)
{
$message = $message . "Select Your Village<br />";
}
if($email == "")
{
$message = $message . "Enter Email Adress<br/>";
}
if ($username == "") {
$message = $message . "Enter User Name<br/>";
}
if($pass1 == "")
{
$message = $message . "Enter password<br/>";
}
if($pass2 == "")
{
$message = $message . "rechek the password <br/>";
}
}
elseif(strlen($pass1) <= 8)
{
$message = $message . "Your Password must be at least 8 charachters<br />";
}
else if($pass1!=$pass2){
$message = "your password do not match!";
}else{
//securing the data
$username = preg_replace("#[^0-9a-z]#i","",$username);
$fname = preg_replace("#[^0-9a-z]#i","",$fname);
$lname = preg_replace("#[^0-9a-z]#i","",$lname);
//$pass1 = sha1($pass1);
$email = mysql_real_escape_string($email);
// checking for duplicate
$user_query = mysql_query("SELECT user_name FROM user WHERE user_name = '$username'LIMIT 1") or die("could not check the username");
$count_username = mysql_num_rows($user_query);
$email_query = mysql_query("SELECT email_address FROM user WHERE email_address = '$email'LIMIT 1") or die("could not check the email");
$count_email = mysql_num_rows($email_query);
if($count_username > 0){
$message = " your username is alredy in use";
}elseif($count_email > 0){
$message = "your email is alredy in use";
}
else{
$query = mysql_query("INSERT INTO user(user_name, first_name, last_name, address, district_name, village_name, birth_date, email_address, specialization_name, password, registered_date)VALUES('$username', '$fname', '$lname', '$country', '$district', '$village', '$bdate', '$email', '$specialization', '$pass1', now())")or die("could not insert data");
//var_dump($query);
//exit();
$message = "Registered Success <a href='profile.php'>Your Profile</a> ";
//from the social website
if ($query)
{
$_SESSION['user_id'] = mysql_insert_id();
$_SESSION['login'] = 'true';
$_SESSION['login_user'] = $username;
}
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Register Page</title>
<link href="style/stylesheet.css" rel="stylesheet" type="text/css" />
<link href="style/imagesGallery.css"rel="stylesheet" type="text/css"/>
<script src="js/main.js" type="text/javascript"></script>
<script src="js/jquery.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<table width="200" border="0" align="center">
<tr>
<tr>
<td><img src="web_header copy.jpg" alt="visitor header" width="1080" height="128" /></td>
</tr>
<tr>
<td>
<marquee direction="left" width="99%" behavior="alternate">
<img src="imggallery/images/akoura/akoura_small.jpg" width="119" height="91">
<img src="imggallery/images/ballaa2/ballaa2_small.jpg" width="119" height="91">
<img src="imggallery/images/baalbeck/baalbek_small.jpg" height="92">
<img src="imggallery/images/barouk/cedre_barouk_small.jpg" width="119" height="91">
<img src="imggallery/images/batroun/batroun_small.jpg" width="119" height="91">
<img src="imggallery/images/bchareh/bchareh_small.jpg" width="119" height="91">
<img src="imggallery/images/beiteldin/beiteldine_small.jpg" width="119" height="91">
<img src="imggallery/images/beyrouth/beyrouth_small.jpg" width="119" height="91">
<img src="imggallery/images/beyrouth/beyroyj frm sky/beyrouthfromSky_small.jpg" width="119" height="91">
<img src="imggallery/images/deir el mara/deirelamar_small.jpg" width="119" height="91">
</marquee>
<hr />
<h2 class="registerTitle">Registration Fields</h2>
<h4 class="registerTitle">Sign Up Today....</h4>
<!-- <div class="container center"> -->
<p style="color:#FF0000" align="center"><?php print("$message")?></p>
</td>
<tr>
<table width="680" border="0" align="center">
<form action="register.php" method="post">
<tr>
<td><span class="Fields">First Name</span> <span class="requiredField">*</span></td>
<td>
<input type="text" name="fname" placeholder="Firstname" /></td>
<td><span class="Fields">Last Name</span><span class="requiredField">*</span></td>
<td><input type="text" name="lname" placeholder="Lastname" /></td>
</tr>
<tr>
<td><label for="birthdate" class="Fields">Birth Date </label></td>
<td><input type="date" name="birthdate" value= "YYYY_MM_DD" onfocus="if (this.value == 'YYYY_MM_DD') {this.value = '';}" onblur="if (this.value == '') {this.value = 'YYYY_MM_DD';}" />
<br /></td>
</tr>
<tr>
<td class="Fields"><label for="country">Country</label></td>
<td><select name="country" class="select">
<option value="0">-- Select Your Country --</option>
<?php countryQuery(); ?>
</select></td>
<td class="Fields"><label for="specialisation">Specialisation <span class="requiredField">*</span></label></td>
<td><select name="specialization" class="select">
<option value="0">-- Select Your Specialization --</option>
<?php specializationQuery(); ?>
</select></td>
</tr>
<tr>
<td class="Fields"><label for="district">District<span class="requiredField">*</span></label></td>
<td><select name="district" class="select">
<option value="0">-- Select Your District --</option>
<?php districtQuery(); ?>
</select></td>
<td class="Fields"><label for="village">Village<span class="requiredField">*</span></label></td>
<td><select name="village" class="select">
<option value="0">-- Select Your Village --</option>
<?php villageQuery(); ?>
</select></td>
</tr>
<tr>
<td class="Fields"><label for="email">Email Adress<span class="requiredField">*</span></label></td>
<td><input type="text" name="email" placeholder="Email Adress" />
<br /></td>
<td><label for="username"><span class="Fields">User Name</span> <span class="requiredField">*</span></label></td>
<td><input type="text" name="username" placeholder="Username" />
<br /></td>
</tr>
<tr>
<td class="Fields"><label for="password">Password<span class="requiredField">*</span></label></td>
<td><input type="password" name="pass1" placeholder="Password" />
<br /></td>
<td class="Fields"><label for="password2">Re_Password<span class="requiredField">*</span></label></td>
<td><input type="password" name="pass2" placeholder="Validate Password" />
<br /></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" value="Register"/></td>
<td></td>
</tr>
</form>
</table>
<!--</div>-->
</tr>
<tr>
<td><?php require_once('footer.php'); ?></td>
</tr>
</tr>
</tr>
</table>
</div>
</body>
</html>
<?php ob_end_flush(); ?>
so anyone can help me ???
The "**specialization_name**" is definitely causing a problem. * is a statement in an SQL query, and it represents basically everything (for example, SELECT * FROM someTable... means select everything from someTable). You should remove the asterisks and your query will work assuming you set it up correctly
To make things simpler from what i can see i believe you could use an ENUM field within your user table, instead of using another table. This could be an alternative for you perhaps.
Try PHP PDO, mysql_ functions in php are going to be depreciated and plus PDO is safer, and is best practice to port your application to other databases. Can't do that with Mysql_
Like this :
//We connect to the database
$host="xxxxxx"; // Host name
$username="xxxxxxx"; // Mysql username
$password="xxxxxxxxxx"; // Mysql password
$db_name="xxxxxxxx"; // Database name
// Connect to server via PHP Data Object
$dbh = new PDO("mysql:host=localhost;dbname=DBFinaid", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
try {
$query = $dbh->prepare("
INSERT INTO user(user_name,
first_name,
last_name,
address,
district_name,
village_name,
birth_date,
email_address,
specialization_name,
password,
registered_date)
VALUES(':username',
':fname',
':lname',
':country',
':district',
':village',
':bdate',
':email',
':specialization',
':pass1',
now())"
);
$query->bindParam(':YOURVALUES', $YOURVALUE); // Make sure the number values in bindParam equal your values in the query
.....................................
$query->execute();
catch (PDOException $e) {
error_log($e->getMessage());
die($e->getMessage());
}
$dbh= null;
[1]: http://php.net/manual/en/book.pdo.php
Your specializationQuery function should print strings like <option value="' . $recordJob['specialization_id'] . '">' . $recordJob['specialization_name'] . '</option> instead of <option value="' . $recordJob['specialization_name'] . '">' . $recordJob['specialization_name'] . '</option>, so you get the specialization_id value that you have to insert into the user database.
I think you shouldn't use specialization_name but specialization_id in your user-table. I assume specialization_id is the key in the table specialization and you should have in your table user a foreign key (user.specialization_id) referencing the primary key of specialization table (specialization.id).
Let's say you have following specializations:
Spec1
Spec2
Spec3
then your Selection element in HTML should look like this:
<select name="specialization" class="select">
<option value="0">-- Select Your Specialization --</option>
<option value="1">Spec1</option>
<option value="2">Spec2</option>
<option value="3">Spec3</option>
</select>
Now if the user selects let's say Spec2, then your variable $specialization should have the value 2 and you should be able to insert it into the database.
Hope it helps!