when i click on delete the page get refresh but data is not deleted can you tell me what’s the problem.tell me also how should i edit the data using edit.help me out in this ... i tried my best.
this is my delete page
<?php
$database = "example";
$conn = mysql_connect("localhost","root","root");
$db_found = mysql_select_db($database, $conn);
$id=$_REQUEST['ID'];
// sending query
mysql_query("DELETE FROM my WHERE ID = '$id'")
or die(mysql_error());
header("Location: main.php");
?>
this is my main page
<!DOCTYPE html>
<html>
<head>
<title>Employee</title>
</head>
<body>
<center><b><font size=20>Employee Detail</font></b></center>
<?php
$database = "example";
$conn = mysql_connect("localhost","root","root");
$db_found = mysql_select_db($database, $conn);
$SQL = "SELECT * FROM my";
$result = mysql_query($SQL);
print "<table border='1'>";
print "<tr>";
print "<th>ID</th>";
print "<th>First name</th>";
print "<th>Last name</th>";
print "<th>Gender</th>";
print "<th>Address</th>";
print "<th>Contact_no</th>";
print "<th>Picture</th>";
print "<th>User_name</th>";
print "<th>Password</th>";
print "<th>Email_id</th>";
while ( $db_field = mysql_fetch_assoc($result) )
{
print "<tr>";
print "<td>".$db_field['ID']."</td>";
print "<td>".$db_field['F_name']."</td>";
print "<td>".$db_field['L_name']."</td>";
print "<td>".$db_field['Gender']."</td>";
print "<td>".$db_field['Address']."</td>";
print "<td>".$db_field['Contact_no']."</td>";
print "<td>".$db_field['Picture']."</td>";
print "<td>".$db_field['U_name']."</td>";
print "<td>".$db_field['Password']."</td>";
print "<td>".$db_field['Email_id']."</td>";
echo"<td> <a href ='edit.php?ID=$id'>Edit</a>";
echo"<td> <a href ='delete.php?ID=$id'><center>Delete</center></a>";
print "</tr>";
}
print "</table>";
mysql_close($conn);
?>
<form>
<a href="test1.php">
<input type="button" value="Add">
</a>
</form>
</body>
</html>
this is my add page
<?php
?>
<html>
<head>
<title>Sign up Form</title>
<script type="text/javascript">
<!--
function validation()
{
if (document.login.fname.value==null || document.login.fname.value=="")
{
alert("First name must be filled out");
document.login.fname.focus();
return false;
}
if((document.login.fname.value.length<3))
{
alert("First name is too short");
document.login.psw.focus();
return false;
}
if (document.login.lname.value==null || document.login.lname.value=="")
{
alert("Last name must be filled out");
document.login.lname.focus();
return false;
}
if((document.login.lname.value.length<3))
{
alert("Last name is too short");
document.login.psw.focus();
return false;
}
if( document.login.select.selectedIndex==0)
{
alert( "Gender must be filled out" );
document.login.select.focus();
return false;
}
if (document.login.address.value==null || document.login.address.value=="")
{
alert("Address must be filled out");
document.login.address.focus();
return false;
}
if((document.login.address.value.length < 20))
{
alert(" Your address must be 20 characters");
document.login.address.select();
return false;
}
if (document.login.contact_no.value==null || document.login.contact_no.value=="")
{
alert("Contact number must be filled out");
document.login.contact_no.focus();
return false;
}
if(isNaN(document.login.contact_no.value))
{
alert("You use charecter in contact number");
document.login.contact_no.focus();
return false;
}
if((document.login.contact_no.value.length < 1) || (document.login.contact_no.value.length > 10))
{
alert("you enter more than 10 digit in contact");
document.login.contact_no.focus();
return false;
}
if (document.login.picture.value==null || document.login.picture.value=="")
{
alert("You must select an Image or Images");
document.login.picture.focus();
return false;
}
if (document.login.uname.value==null || document.login.uname.value=="")
{
alert("Login name must be filled out");
document.login.uname.focus();
return false;
}
if((document.login.psw.value.length<4))
{
alert("Password is too short");
document.login.psw.focus();
return false;
}
if (document.login.psw.value==null || document.login.uname.value=="")
{
alert("Password must be filled out");
document.login.psw.focus();
return false;
}
var emailfilter=/^\w+[\+\.\w-]*#([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i
var b=emailfilter.test(document.login.e_id.value);
if(b==false)
{
alert("Please Enter a valid Mail ID");
document.login.e_id.focus();
return false;
}
}
//-->
</script>
</head>
<body>
<form name="login" action="insert.php" onsubmit="return(validation())" method="post" enctype= multipart/form-data>
<table>
<tr>
<td>First Name:</td>
<td><input type="text" name="fname" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="lname" /></td>
</tr>
<tr>
<td>Gender:</td>
<td><select name="select">
<option value="-1" selected>[Select option]</option>
<option value="male">Male</option>
<option value="female">Female</option>
</td>
</tr>
<tr>
<td>Address:</td>
<td><textarea name="address" col="60" row="10"></textarea></td>
</tr>
<tr>
<td>Contact no:</td>
<td><input type="number" name="contact_no"></td>
</tr>
<tr>
<td>Picture:</td>
<td><input type="file" name="picture"> </td>
</tr>
<tr>
<td>User name:</td>
<td><input type="text" name="uname"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="psw"></td>
</tr>
<tr>
<td>Email id:</td>
<td><input type="email" name="e_id"></td>
</tr>
<tr>
<td><input type="reset" value="Reset"></td>
<td><input type="submit" name="submit"></td>
</tr>
</table>
</form>
</body>
</html>
this is my edit page
<?php
$database = "example";
$conn = mysql_connect("localhost","root","root");
$db_found = mysql_select_db($database, $conn);
$id =$_REQUEST['ID'];
$result = mysql_query("SELECT * FROM my WHERE ID = '$id'");
$db_field = mysql_fetch_array($result);
if (!$result)
{
die("Error: Data not found..");
}
$F_name=$db_field['F_name'];
$L_name=$db_field['L_name'];
$Gender=$db_field['Gender'];
$Address=$db_field['Address'];
$Contact_no=$db_field['Contact_no'];
$Picture=$db_field['Picture'];
$U_name=$db_field['U_name'];
$Password=$db_field['Password'];
$Email_id=$db_field['Email_id'];
if(isset($_POST['save']))
{
$fname_save = $_POST['fname'];
$lname_save = $_POST['lname'];
$gender_save = $_POST['select'];
$address_save = $_POST['address'];
$contactno_save = $_POST['contact_no'];
$picture_save = $_POST['picture'];
$uname_save = $_POST['u_name'];
$password_save = $_POST['psw'];
$emailid_save = $_POST['e_id'];
mysql_query("UPDATE my SET F_name='$fname_save', L_name='$lname_save', Gender='$gender_save', Address='$address_save', Contact_no='$contactno_save', Picture='$picture_save', U_name='$uname_save', Password='$password_save', Email_id='$emailid_save' WHERE ID = '$id'")
or die(mysql_error());
echo "Saved!";
header("Location: main.php");
}
mysql_close($conn);
?>
</head>
<body>
<form method="post">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" name="fname" value="<?php echo $F_name ?>" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="lname" value="<?php echo $L_name ?>" /></td>
</tr>
<tr>
<td>Gender:</td>
<td><select name="select" value="<?php echo $Gender ?>">
<option value="-1" selected>[Select option]</option>
<option value="male">Male</option>
<option value="female">Female</option>
</td>
</tr>
<tr>
<td>Address:</td>
<td><textarea name="address" col="60" row="10" value="<?php echo $Address ?>"></textarea></td>
</tr>
<tr>
<td>Contact no:</td>
<td><input type="number" name="contact_no" value="<?php echo $Contact_no ?>"></td>
</tr>
<tr>
<td>Picture:</td>
<td><input type="file" name="picture" value="<?php echo $Picture ?>"> </td>
</tr>
<tr>
<td>User name:</td>
<td><input type="text" name="uname" value="<?php echo $U_name ?>"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="psw" value="<?php echo $Password ?>"></td>
</tr>
<tr>
<td>Email id:</td>
<td><input type="email" name="e_id" value="<?php echo $Email_id ?>"></td>
</tr>
<tr>
<td><input type="submit" name="save" value="save"></td>
</tr>
</table>
</form>
</body>
</html>
this is my database
<?php
// Create connection
$conn = mysql_connect('localhost', 'root', 'root');
if (!$conn)
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected Successfully';
$sql = "CREATE TABLE my(
ID INT NOT NULL AUTO_INCREMENT,
F_name VARCHAR(20) NOT NULL,
L_name VARCHAR(20) NOT NULL,
Gender VARCHAR(10) NOT NULL,
Address VARCHAR(80) NOT NULL,
Contact_no INT NOT NULL,
Picture BLOB NOT NULL,
U_name VARCHAR(20) NOT NULL,
Password VARCHAR(25) NOT NULL,
Email_id VARCHAR(30) NOT NULL,
primary key ( ID ))";
mysql_select_db('example');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
echo "Table my created successfully\n";
mysql_close($conn);
?>
echo ("<td>Delete</td></tr>")
Add:
$id = $db_field['ID'];
to the beginning of the while loop on the main page. You're using this variable in the URLs in your echo statements, but never setting it.
Related
I am designing a website where beekeepers can register there shop details to a website and after they have registered their info to the database, they are logged in then redirected to the account management page where they can change their details if they want.
I am having a problem where after the user has entered there details, the website is directed to the register script which adds the user and their details to the database, it then takes them to a login script to log them in via the entry to the database that was just added. However it just gets stuck on the registerlogin script (yet still adds the new user). It adds them, but does not log them in after.
I have them able to log in via a log in page, which directs them to the account management page fine after a successful login, I have used similar code from the login script in the registerlogin script.
Can anyone see what I have done wrong?
register page(user side):
<?php
session_start();
?>
<html>
<head>
<title>Beekeeper</title>
<meta name="author" content="Nigel Kennington">
<meta name="description" content="Find local honey near you">
<meta name="keywords" content="honey, bees, bee, local">
<link href="bees.css" type="text/css" rel="stylesheet">
</head>
<body>
<div id="linkbar">
<table height="140px" ID="Table1">
<tr>
<td valign="bottom">Home |</td>
<td valign="bottom">About |</td>
<td valign="bottom">Contact</td>
</tr>
</table>
</div>
<div id="bulk">
<table width="100%" border="0" cellpadding="0" cellspacing="0" ID="Table1">
<tr id="spacer">
<td class="leftnav" align="right" valign="top" nowrap width="120px">
<h5>Find Honey from:</h5>
<p>Highlands and Islands</p>
<p>North Eastern Scotland</p>
<p>Eastern Scotland</p>
<p>South Western Scotland
<h5>List your produce:</h5>
<p>Keepers Page</p>
<p>Register</p>
</td>
<td>
<p class="first">To get a free account and start advertising your produce here, fill in the information below:</p>
<p>If you already have an account, you can login by clicking on the "Keepers Page" link on the left hand side.</p>
<fieldset>
<?php
$fullUrl = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if (strpos($fullUrl, "signup=empty") == true)
{
echo "<p class='error' >You did not fill in all fields,
please check you have filled all fields out!</p>";
//exit();
}
elseif (strpos($fullUrl, "signup=passwordnotmatch") == true)
{
echo "<p class='error'>Passwords entered do not match!</p>";
//exit();
}
elseif (strpos($fullUrl, "signup=bothnumbersnotentered") == true)
{
echo "<p class='error'>You must enter at least one phone number!</p>";
//exit();
}
elseif (strpos($fullUrl, "signup=usertaken") == true)
{
echo "<p class='error'>User is already on the system!</p>";
//exit();
}
elseif (strpos($fullUrl, "signup=success") == true)
{
echo "<p class='success'>You have been signed up!</p>";
//exit();
}
?>
<form method="POST" action="register.php">
<table border=0 id="flush">
<tr>
<td width="50"></td>
<td colspan="2"><div class="heading">About You</div></td>
</tr>
<tr>
<td width="50"></td>
<td>Your Name:</td>
<td><input type="text" name="keepername" size="32"></td>
</tr>
<tr>
<td width="50"></td>
<td>Password:</td>
<td><input type="password" name="password" size="16"></td>
</tr>
<tr>
<td width="50"></td>
<td>Re-enter Password:</td>
<td><input type="password" name="password2" size="16"></td>
</tr>
<tr>
<td width="50"></td>
<td>Your E-mail:</td>
<td><input type="text" name="accountemail" size="32"></td>
</tr>
<tr>
<td width="50"></td>
<td colspan="2"><div class="heading">About your produce</div></td>
</tr>
<tr>
<td width="50"></td>
<td>Shop Name:</td>
<td><input type="text" name="shopname" size="32"></td>
</tr>
<tr>
<td width="50"></td>
<td>Area:</td>
<td>
<input type="radio" name="area" value="HaI"> Highlands and Islands<br>
<input type="radio" name="area" value="NES"> North Eastern Scotland<br>
<input type="radio" name="area" value="ES"> Eastern Scotland<br>
<input type="radio" name="area" value="SWS"> South Western Scotland
</td>
</tr>
<tr>
<td width="50"></td>
<td>Address:</td>
<td><textarea rows="2" name="address" cols="27"></textarea></td>
</tr>
<tr>
<td width="50"></td>
<td>Town/City:</td>
<td><input type="text" name="town" size="32"></td>
</tr>
<tr>
<td width="50"></td>
<td>Postcode:</td>
<td><input type="text" name="postcode" size="32"></td>
</tr>
<tr>
<td width="50"></td>
<td>Phone Number:</td>
<td><input type="text" name="landline" size="32"></td>
</tr>
<tr>
<td width="50"></td>
<td>Mobile Number:</td>
<td><input type="text" name="mobile" size="32"></td>
</tr>
<tr>
<td width="50"></td>
<td>Shop E-mail:</td>
<td><input type="text" name="shopemail" size="32"></td>
</tr>
<tr>
<td width="50"></td>
<td>Describe your produce:</td>
<td><textarea rows="4" name="description" cols="27"></textarea></td>
</tr>
<tr>
<td width="50"></td>
<td></td>
<td><input type="submit" name="submit" value="Register"></td>
</tr>
</table>
</fieldset>
</form>
</td>
<td valign="top" align="right">
<img src="gfx/register.jpg" alt="honey pots" class="imgborder">
</td>
</tr>
</table>
</div>
<div id="footer">
© 2008 beekeeper.com | Privacy Policy |
Terms of Use
</div>
</body>
register script(server side):
<?php
session_start();
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root") or die(mysqli_error($db));
mysqli_select_db($link, "keepers")
or die(mysqli_error($link));
// Check connection
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
if (isset($_POST['submit']))
{
$name = mysqli_real_escape_string($link, $_REQUEST['keepername']);
$password = mysqli_real_escape_string($link, $_REQUEST['password']);
$password2 = mysqli_real_escape_string($link, $_REQUEST['password2']);
$email = mysqli_real_escape_string($link, $_REQUEST['accountemail']);
$shop = mysqli_real_escape_string($link, $_REQUEST['shopname']);
$area = mysqli_real_escape_string($link, $_REQUEST['area']);
$address = mysqli_real_escape_string($link, $_REQUEST['address']);
$town = mysqli_real_escape_string($link, $_REQUEST['town']);
$postcode = mysqli_real_escape_string($link, $_REQUEST['postcode']);
$landline = mysqli_real_escape_string($link, $_REQUEST['landline']);
$mobile = mysqli_real_escape_string($link, $_REQUEST['mobile']);
$shopemail = mysqli_real_escape_string($link, $_REQUEST['shopemail']);
$description = mysqli_real_escape_string($link, $_REQUEST['description']);
//Error Handlers
//Check for empty fields
if (empty($name) || empty($password) || empty($email) || empty($shop) ||
empty($area) || empty($address) || empty($town) || empty($postcode) ||
empty($shopemail) || empty($description))
{
header("Location: keeperregister.php?signup=empty");
exit();
}
else
{
if ($password != $password2)
{
header("Location: keeperregister.php?signup=passwordnotmatch");
exit();
}
else
{
if (empty($landline) && empty($mobile))
{
header("Location: keeperregister.php?signup=bothnumbersnotentered");
exit();
}
else
{
$sql = "SELECT * FROM keepers WHERE keeper_email = '$email'";
$results = mysqli_query($link, $sql) or die (mysqli_error($link));
$resultCheck = mysqli_num_rows($results);
if ($resultCheck > 0)
{
header("Location: keeperregister.php?signup=usertaken");
exit();
}
else
{
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
//Insert the user into the database
$sqlinsert = "INSERT INTO keepers VALUES ('NULL','$name', '$hashedPwd', '$email', '$shop', '$area' ,'$address' ,'$town' ,'$postcode' ,'$landline' ,'$mobile' ,'$shopemail', '$description')";
if(mysqli_query($link, $sqlinsert))
{
header("Location: registerlogin.php?");
exit();
}
else
{
echo "ERROR: Could not able to execute $sqlinsert. " . mysqli_error($link);
}
}
}
}
}
// close connection
mysqli_close($link);
}
else
{
header("Location: keeperregister.php");
exit();
}
registerlogin script(server side):
<?php
session_start();
if (isset($_POST['submit']))
{
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root") or die(mysqli_error($db));
mysqli_select_db($link, "keepers")
or die(mysqli_error($link));
// Check connection
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$name = mysqli_real_escape_string($_POST['keepername']);
//$password = mysqli_real_escape_string($link, $_REQUEST['password']);
$sql = "SELECT * FROM keepers WHERE keeper_name = '$name'";
$result = mysqli_query($link, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1)
{
header("Location: keeperlogin.php?login=error");
exit();
}
else
{
if ($row = mysqli_fetch_assoc($result))
{
//Log in the user here
$_SESSION['u_id'] = $row['ID'];
$_SESSION['u_name'] = $row['keeper_name'];
$_SESSION['u_keeperemail'] = $row['keeper_email'];
$_SESSION['u_shopname'] = $row['shop_name'];
$_SESSION['u_area'] = $row['area'];
$_SESSION['u_address'] = $row['address'];
$_SESSION['u_town'] = $row['town/city'];
$_SESSION['u_postcode'] = $row['postcode'];
$_SESSION['u_landline'] = $row['phone number'];
$_SESSION['u_mobile'] = $row['mobile number'];
$_SESSION['u_shopemail'] = $row['shop_email'];
$_SESSION['u_produce'] = $row['produce'];
header("Location: accountmanagement.php?login=success");
exit();
}
else
{
header("Location: keeperlogin.php?login=error");
exit();
}
}
}
?>
On successful registration, you're not passing a $_POST value as needed in registerlogin.php. Rather than $_POST you better use $_SESSION instead. Changes below.
In register.php:
Just above:
header("Location: registerlogin.php?");
Add:
$_SESSION['keeper_name'] = $name;
In registerlogin.php:
Replace:
isset($_POST['submit'])
With:
isset($_SESSION['keeper_name']) AND $_SESSION['keeper_name'] != ""
Replace:
$name = mysqli_real_escape_string($_POST['keepername']);
With:
$name = mysqli_real_escape_string($_SESSION['keeper_name']);
<?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
I am having problem in this following code.It says undefined index on line 83.The second problem is that there is a huge gap between the text fill the required form and the input textbox of the form during output.Please help me out.The code is posted below.
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$firstnameErr = $lastnameErr = $emailErr = "";
$firstname = $lastname = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["firstname"]))
{
$firstnameErr = "Name is required";
}
else
{
$firstname = test_input($_POST["firstname"]);
}
if (empty($_POST["lastname"]))
{
$lastnameErr = "Name is required";
}
else
{
$lastname = test_input($_POST["lastname"]);
}
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div text align =center><h1>Eventous Info</h1></div>
<h3>Fill the Required Form:</h3>
<p><span class="error">*required field</span></p>
<table>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<tr><?php// echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
<td>Firstname:</td>
<td><input type="text" name="firstname" ></td>
<td><span class="error">* <?php echo $firstnameErr;?></span></td><br><br>
</tr>
<tr>
<td>Lastname:</td>
<td><input type="text" name="lastname" ></td>
<td><span class="error">* <?php echo $lastnameErr;?></span></td><br><br>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"></td>
<td><span class="error">* <?php echo $emailErr;?></span></td><br><br>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="number"><td><br><br>
</tr>
</table>
<input type="submit" >
</form>
<?php
$con = mysql_connect("localhost","ashu123","bangalore");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("evantus", $con);
$sql="INSERT INTO employee (firstname, lastname, email, phone )
***LINE-83***
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[email]','$_POST[number]')";
$sql = "select * from employee";
$query = mysql_query( $sql );
echo "<table>";
echo "<tr><th>firstname</th>";
echo "<th>lastname</th>";
echo "<th>email</th>";
echo "<th>phone</th></tr>";
while( $row = mysql_fetch_assoc($query) )
{
echo "<tr><td>$row[firstname]</td>";
echo "<td>$row[lastname]</td>";
echo "<td>$row[email]</td>";
echo "<td>$row[phone]</td></tr>";
}
echo "</table>";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con)
?>
</body>
</html>
Your form has invalid html code. In short, just use:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>Firstname:</td>
<td><input type="text" name="firstname" ></td>
<td><span class="error">* <?php echo $firstnameErr;?></span><br /><br /></td>
</tr>
<tr>
<td>Lastname:</td>
<td><input type="text" name="lastname" ></td>
<td><span class="error">* <?php echo $lastnameErr;?></span><br /><br /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"></td>
<td><span class="error">* <?php echo $emailErr;?></span><br /><br /></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="number"><br /><br /><td>
<td></td>
</tr>
</table>
<input type="submit" >
</form>
More about it:
1. After opening the <table> element, next one must be table row, so <form> must be a wrapper to your table.
2. You have placed breaks after closing the </td> tag, which is wrong - they should be inside table cell.
3. Ref: undefined index, guess it is only a warning that you are using the $_POST variable that does not exist.
I feel your insert query is not right, try the query below.
$sql="INSERT INTO employee (firstname, lastname, email, phone ) VALUES ('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['email']."','".$_POST['number']."')";
I am trying to upload files from my PHP-based website to Google Drive. I searched, got google-api-php-client library. In documentation an example is given but that can be run on php shell (Command line). I tried to run that example in browser, I got error of curl extention, and fixed that.
Now I am getting error related to authenticating code to allow access. I do not need authentication at all in my project, but for the time being I can try with it.
I have the following code in www.mydomain.com/drive/index.php file:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('MY-CLIENT-ID');
$client->setClientSecret('MY-CLIENT-SECRET');
$client->setRedirectUri('http://www.MY-DOMAIN.com/drive/auth.php');
//AUTH.PHP should have code to authenticate code and return back another code.
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
//**********************authentication process for SHELL
//I want this authentication process to remove at all or convert to web based authentication
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//************************************************************
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
?>
Can I upload file without authentication need for each upload? If yes then how? If no then how to authenticate?
You can't use the exact same example that is meant for console development into web development.
You should do some changes, I'll give you mine as an example :
<?php
require_once 'googleapi/Google_Client.php';
require_once 'googleapi/contrib/Google_DriveService.php';
session_start();
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setApplicationName('Google+ PHP Starter Application');
$client->setClientId('ID');
$client->setClientSecret('Secret');
$client->setRedirectUri('Redirect');
//Voy a la dirección de la creación del permiso
$authUrl = $client->createAuthUrl();
print "<a href='$authUrl'>Connect Me!</a>";
//Regreso de la dirección con el código con el que puedo autenticarme
if (isset($_GET['code'])) {
$accessToken = $client->authenticate($_GET['code']);
file_put_contents('conf.json', $accessToken);
$client->setAccessToken($accessToken);
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
$client->setAccessToken(file_get_contents('conf.json'));
if ($client->getAccessToken()) {
//Significa que tengo derecho a manipular el servicio como quiera
// Elijo el servicio que quiero usar
$service = new Google_DriveService($client);
$file = new Google_DriveFile();
/*$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
print "test";*/
}
?>
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$email=$_POST['email'];
$address=$_POST['address'];
$country=$_POST['country'];
$gender=$_POST['gender'];
$hobby = implode(',', $_POST['hobby']);
echo $ins="insert into itech (`name`,`email`,`address`,`country`,`gender`,`hobby`)values('".$name."','".$email."','".$address."','".$country."','".$gender."','".$hobby."')";
mysql_query($ins);
//header('location:view.php');
}
?>
<html>
<head></head>
<body>
<form name="add.php" method="post" onSubmit="return validate()">
<table align="center" border="1">
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td>Address</td>
<td>
<textarea rows="5" cols="20" name="address" wrap="physical"</textarea>
</textarea>
</td>
</tr>
<tr>
<td>
Country:<br/></td>
<td>
<select name="country" id="country">
<option value="">Select Country</option>
<option value="India">India</option>
<option value="U.S.A">U.S.A</option>
<option value="Canada">Canada</option></select>:<br />
</td>
</tr>
<tr>
<td>Gender</td>
<td>
Male:<input type="radio" value="Male" name="gender">:<br />
Female:<input type="radio" value="Female" name="gender">:<br />
</td>
</tr>
<tr>
<td>Hobbies</td>
<td>
<input type="checkbox" name="hobby[]" value="cricket">cricket<br/>
<input type="checkbox" name="hobby[]" value="Music">Music<br/>
<input type="checkbox" name="hobby[]" value="Movie">Movie<br/>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
<script language="javascript" type="text/javascript">
function validate()
{
if(document.getElementById("name").value=="")
{
alert("Please Enter Your Name");
document.getElementById("name").focus();
return false;
}
if(document.getElementById("email").value=="")
{
alert("Please Enter Your Email Id");
document.getElementById("email").focus();
return false;
}
if(document.getElementById("address").value=="")
{
alert("Please Enter Your Address ");
document.getElementById("address").focus();
return false;
}
return true;
}
</script>
*****************************************************************************
edit.php
**************************************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
$id=$_GET['id'];
$qry="select * from itech where id=$id";
$data=mysql_query($qry);
$result=mysql_fetch_assoc($data);
echo $result['hobby'];
//echo $id;
if(isset($_POST['update']))
{
$name=$_POST['name'];
$email=$_POST['email'];
$address=$_POST['address'];
$gender=$_POST['gender'];
$hobby = implode(',', $_POST['hobby']);
echo $upd="update itech SET name='$name',email='$email',address='$address',gender='$gender',hobby='$hobby' where id=$id";exit;
mysql_query($upd);
header('location:view.php');
}
?>
<html>
<head></head>
<body>
<form name="edit.php" method="post">
<table align="center" border="1">
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name" value="<?php echo $result['name'];?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" id="email" value="<?php echo $result['name'];?>"></td>
</tr>
<tr>
<td>Address</td>
<td>
<textarea rows="5" cols="20" name="address" id="address" >
<?php echo $result['address'];?>
</textarea>
</td>
</tr>
<tr>
<td>
Country:<br/></td>
<td>
<select name="country">
<option value="">Select Country</option>
<option value="<?php echo $result["id"]; ?>"
<?//php if($result["id"]==$_REQUEST["cat_id"]) { echo "Selected"; } ?>>
<?//php echo $r["category_name"]; ?></option>
<option value="India" <?php if($result['country']=='India') { echo "Selected"; }?>>India</option>
<option value="U.S.A" <?php if($result['country']=='U.S.A') { echo "Selected"; }?>>U.S.A</option>
<option value="Canada"<?php if($result['country']=='Canada') { echo "Selected"; }?>>Canada</option></select>:<br />
</td>
</tr>
<tr>
<td>Gender</td>
<td>
<?php
if($result['gender']=='Male')
{ ?>
Male:<input type="radio" value="Male" name="gender" CHECKED><br />
Female:<input type="radio" value="Female" name="gender"><br />
<?php }elseif ($result['gender'] == 'Female') {?>
Male:<input type="radio" value="Male" name="gender" ><br />
Female:<input type="radio" value="Female" name="gender" CHECKED><br />
<?php }?>
</td>
</tr>
<tr>
<td>Hobbies</td>
<td>
<input type="checkbox" name="hobby[]" value="cricket" <?php if($result['hobby']=='cricket') { echo "checked=checked"; }?>>cricket<br/>
<input type="checkbox" name="hobby[]" value="Music" <?php if($result['hobby']=='Music') {echo "checked=checked";}?>>Music<br/>
<input type="checkbox" name="hobby[]" value="Movie" <?php if($result['hobby']=='Movie') { echo "checked=checked";}?>>Movie<br/>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="update" value="update"></td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
function validation()
{
if(document.getElementById(name).value="");
{
alert("Plz Enter Your Name");
document.getElementById(name).focus();
return false;
}
if(document.getElementById(email).value="");
{
alert("Plz enter Emailid");
document.getElementById(emailid).focus();
return false;
}
if(document.getElementById(address).value="");
{
alert("Plz Enter Your Address");
document.getElementById(address).focus();
return false;
}
if(document.getElementById(gender).value="");
{
alert("Plz Select your gender");
document.getElementById(gender).focus();
return false;
}
if(document.getElementById(hobby).value="");
{
alert("Plz Select your Hobby");
document.getElementById(hobby).focus();
return false;
}
return true;
}
</script>
**********************************************
view.php
******************************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
?>
<html>
<head></head>
<body>
<table align="center" border="1">
<tr>
<th>Name</th>
<th>EmailId</th>
<th>Address</th>
<th>Country</th>
<th>Gender</th>
<th>Hobby</th>
<th>Action</th>
</tr>
<?php
$sel="select * from itech";
$data=mysql_query($sel);
while($result=mysql_fetch_assoc($data))
{?>
<tr>
<td><?php echo $result['name'];?></td>
<td><?php echo $result['email'];?></td>
<td><?php echo $result['address'];?></td>
<td><?php echo $result['country'];?></td>
<td><?php echo $result['gender'];?></td>
<td><?php echo $result['hobby'];?></td>
<td>Edit
Delete
</td>
</tr>
<?php
}?>
</table>
</body>
</html>
**********************************************
pagination.php
******************************************
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
VIEW-PAGINATED.PHP
Displays all data from 'players' table
This is a modified version of view.php that includes pagination
*/
// connect to the database
include('connect-db.php');
// number of results to show per page
$per_page = 3;
// figure out the total pages in the database
$result = mysql_query("SELECT * FROM players");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p><a href='view.php'>View All</a> | <b>View Page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='view-paginated.php?page=$i'>$i</a> ";
}
echo "</p>";
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . mysql_result($result, $i, 'id') . '</td>';
echo '<td>' . mysql_result($result, $i, 'firstname') . '</td>';
echo '<td>' . mysql_result($result, $i, 'lastname') . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
// pagination
?>
<p>Add a new record</p>
</body>
</html>
login.php
***************************************
<?php
session_start();
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
if(isset($_POST['submit']))
{
$email=$_REQUEST['email'];
$pass=$_REQUEST['password'];
$sel="select * from elite where email='$email' and password='$pass'";
$res= mysql_query($sel);
$co= mysql_num_rows($res);
echo $co;
header("location:view.php");
if($co>0)
{
$row=mysql_fetch_array($res);
$_SESSION['email']=$row['email'];
header("location:view.php");
}
else
{
echo "Please enter correct username or password....";
header("location:login.php");
}
}
?>
<html>
<head>
</head>
<body>
<fieldset style="background-color: lightblue;height: 400px;width: 500px;margin-left: 400px;margin-top: 120px;">
<form action="" method="post">
<h1 align="center" style="color: red;">Login Page</h1>
<table align="center" border="1">
<tr>
<td><b>Email</b></td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td><b>PassWord</b></td>
<td><input type="password" name="password"></td>
</tr>
</table><br /><br />
<b><input type="submit" name="submit" value="submit" style="margin-left: 220px;color: red;"></b>
</form>
</fieldset>
</body>
</html>
*********************************************************
logout.php
**********************************************************
<?php
session_start();
session_destroy();
header("Location: login.php");
exit;
?>
******************************
add.php
**********************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
if(isset($_POST['submit']))
{
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$password=$_POST['password'];
move_uploaded_file($_FILES['image']['tmp_name'] ,"upload/".$_FILES['image']['name']);
$img = $_FILES['image']['name'];
$dob=$_POST['dob'];
$address=$_POST['address'];
echo $ins="insert into elite (`firstname`,`lastname`,`email`,`password`,`image`,`dob`,`address`)
values('".$firstname."','".$lastname."','".$email."','".$password."','".$img."','".$dob."','".$address."')";
mysql_query($ins);
header('location:view.php');
}
?>
<html>
<head>
</head>
<body>
<table align="center" border="1">
<form name="add.php" method="post" enctype="multipart/form-data" onsubmit="return validation()">
<tr>
<td>FirstName</td>
<td><input type="text" id="firstname" name="firstname"></td>
</tr>
<tr>
<td>LastName</td>
<td><input type="text" id="lastname" name="lastname"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" id="email" name="email"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="password" name="password"></td>
</tr>
<tr>
<td>Image</td>
<td><input type="file" id="image" name="image"> </td>
</tr>
<tr>
<td>Dob</td>
<td> <input type="text" name='dob' id="datepicker" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" id="address" name="address"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" id="submit"></td>
</tr>
</form>
</table>
</body>
</html>
<script type="text/javascript">
function validation()
{
if(document.getElementById("firstname").value=="")
{
alert("Please Enter FirstName");
document.getElementById("firstname").focus();
return false;
}
if(document.getElementById("lastname").value=="")
{
alert("Please Enter lastname");
document.getElementById("lastname").focus();
return false;
}
var email = document.getElementById('email');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value))
{
alert('Please provide a valid email address');
email.focus;
return false;
}
if(document.getElementById("password").value=="")
{
alert("Please Enter password");
document.getElementById("password").focus();
return false;
}
if(document.getElementById("image").value=="")
{
alert("Please upload image");
document.getElementById("image").focus();
return false;
}
if(document.getElementById("dob").value=="")
{
alert("Please enter date");
document.getElementById("dob").focus();
return false;
}
if(document.getElementById("address").value=="")
{
alert("Please Enter address");
document.getElementById("address").focus();
return false;
}
return true;
}
</script>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
</body>
</html>
***************************************
view.php
************************************
<?php
session_start();
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
echo $_SESSION['email'];
if(!isset($_SESSION['email']))
{
header("location:login.php");
}
?>
<html>
<head></head>
<body></body>
<table align="center" border="1">
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Email</th>
<th>Password</th>
<th>Image</th>
<th>D.O.B</th>
<th>Address</th>
<th>Action</th>
</tr>
<?php
$vs="select * from elite";
$data=mysql_query($vs);
while($result=mysql_fetch_assoc($data))
{?>
<tr>
<td><?php echo $result['firstname'];?></td>
<td><?php echo $result['lastname'];?></td>
<td><?php echo $result['email'];?></td>
<td><?php echo $result['password'];?></td>
<td><img src="<?php echo "upload/".$result['image']; ?>" alt="" width="50px" height="50px"></td>
<td><?php echo $result['dob'];?></td>
<td><?php echo $result['address'];?></td>
<td><a href="edit.php? id=<?php echo $result['id'];?>">Edit</td>
<td><a href="delete.php? id=<?php echo $result['id'];?>">Delete</td>
<td><a href="logout.php?">Logout</td>
</tr>
<?php
}
?>
</table>
</html>
********************************************************
edit.php
*********************************************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
$id=$_GET['id'];
echo $sel="select * from elite where id=$id";
$data=mysql_query($sel);
$res=mysql_fetch_assoc($data);
if(isset($_POST['update']))
{
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$password=$_POST['password'];
move_uploaded_file($_FILES['image']['tmp_name'] ,"upload/".$_FILES['image']['name']);
$img = $_FILES['image']['name'];
$dob=$_POST['dob'];
$address=$_POST['address'];
$upd="update elite SET firstname='$firstname',lastname='$lastname',email='$email',password='$password',image='$img',dob='$dob',address='$address' where id=$id";
mysql_query($upd);
header('location:view.php');
}
?>
<html>
<head>
</head>
<body>
<table align="center" border="1">
<form name="edit.php" method="post" enctype="multipart/form-data" onsubmit="return validation()">
<tr>
<td>FirstName</td>
<td><input type="text" id="firstname" name="firstname" value="<?php echo $res['firstname'];?>"></td>
</tr>
<tr>
<td>LastName</td>
<td><input type="text" id="lastname" name="lastname"value="<?php echo $res['lastname'];?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" id="email" name="email"value="<?php echo $res['email'];?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="password" name="password"value="<?php echo $res['password'];?>"></td>
</tr>
<tr>
<td>Image</td>
<td><input type="file" id="image" name="image"value="<?php echo $res['image'];?>"> </td>
</tr>
<tr>
<td>Dob</td>
<td><input type="text" id="datepicker" name="dob"value="<?php echo $res['dob'];?>"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" id="address" name="address"value="<?php echo $res['address'];?>"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="update" value="update"></td>
</tr>
</form>
</table>
</body>
</html>
<script type="text/javascript">
function validation()
{
if(document.getElementById("firstname").value=="")
{
alert("Please Enter FirstName");
document.getElementById("firstname").focus();
return false;
}
if(document.getElementById("lastname").value=="")
{
alert("Please Enter lastname");
document.getElementById("lastname").focus();
return false;
}
if(document.getElementById("email").value=="")
{
alert("Please Enter emailid");
document.getElementById("email").focus();
return false;
}
if(document.getElementById("password").value=="")
{
alert("Please Enter password");
document.getElementById("password").focus();
return false;
}
if(document.getElementById("image").value=="")
{
alert("Please upload image");
document.getElementById("image").focus();
return false;
}
if(document.getElementById("dob").value=="")
{
alert("Please enter date");
document.getElementById("dob").focus();
return false;
}
if(document.getElementById("address").value=="")
{
alert("Please Enter address");
document.getElementById("address").focus();
return false;
}
return true;
}
</script>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
****************************************************
delete.php
*************************************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
$id=$_GET['id'];
$del="delete from elite where id=$id";
mysql_query($del);
header('location:view.php');
?>
I wonder is it possible to keep the user input inside form field after form submitted, so that the user can update the entry. I've a html registration form [with some JS validation], then a php file to insert data to sql & meanwhile display back the inserted data in a table view. i also include the form's html code in php file so i can see the form after being submitted. but i couldn't keep the data in the field after form submitted! here is the form:
<!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>
<script type="text/javascript">
<!--
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == ""){
alert( "IC Number cann't be empty!" );
document.myForm.ic.focus() ;
return false;}
else if(isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12){
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;}
if( document.myForm.name.value == "") {
alert( "Name cann't be empty!" );
document.myForm.name.focus() ;
return false;
}
if( document.myForm.contact.value == ""){
alert( "Contact number cann't be empty!");
document.myForm.contact.focus() ;
return false;
} else if(isNaN( document.myForm.contact.value ))
{
evt.preventDefault();
alert( "Please provide your correct Contact Number!" );
document.myForm.contact.focus() ;
return false;
}
if( document.myForm.address.value == "" ){
alert( "Please provide your Address!" );
document.myForm.address.focus() ;
return false;
}
}
//-->
</script>
</head>
<style type="text/css">
h2 {
color: #06C;
}
body {
background-color: #FFC;
}
</style>
<body>
<form name="myForm" method="post" action="insert.php" onsubmit="return(validate(event));">
<div align="center"><br>
<table width="453" border="0">
<tr>
<th colspan="4" bgcolor="#99FFFF" scope="col">
<h3>Workshop Name: PHP! </h3></th>
</tr>
<tr bgcolor="#99FF99">
<td width="142"> IC Number</td>
<td width="15"><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Full Name</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="name" type="text" id="name" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td>Contact No.</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="contact" type="text" id="contact" size="45" onkeypress='validateNum(event)' />
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Email</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="mail" type="text" id="mail" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td height="60">Address</td>
<td><div align="center">:</div></td>
<td colspan="2">
<div align="right">
<textarea name="address" id="address" cols="35" rows="3"></textarea>
</div>
</td>
</tr>
<tr bgcolor="#99FFFF">
<td colspan="2"> </td>
<td width="231"><input type="reset" value="Clear" /></td>
<td width="47"><div align="right">
<input type="submit" value="Submit" />
</div></td>
</tr>
</table>
<br>
</div>
</form>
</body>
</html>
here is the insert.php file:
<!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>
<script type="text/javascript">
<!--
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == ""){
alert( "IC Number cann't be empty!" );
document.myForm.ic.focus() ;
return false;}
else if(isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12){
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;}
if( document.myForm.name.value == "") {
alert( "Name cann't be empty!" );
document.myForm.name.focus() ;
return false;
}
if( document.myForm.contact.value == ""){
alert( "Contact number cann't be empty!");
document.myForm.contact.focus() ;
return false;
} else if(isNaN( document.myForm.contact.value ))
{
evt.preventDefault();
alert( "Please provide your correct Contact Number!" );
document.myForm.contact.focus() ;
return false;
}
if( document.myForm.address.value == "" ){
alert( "Please provide your Address!" );
document.myForm.address.focus() ;
return false;
}
}
//-->
</script>
</head>
<style type="text/css">
h2 {
color: #06C;
}
body {
background-color: #FFC;
}
</style>
<body>
<form name="myForm" method="post" action="update.php" onsubmit="return(validate(event));">
<div align="center"><br>
<table width="453" border="0">
<tr>
<th colspan="4" bgcolor="#99FFFF" scope="col">
<h3>Workshop Name: PHP! </h3></th>
</tr>
<tr bgcolor="#99FF99">
<td width="142"> IC Number</td>
<td width="15"><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Full Name</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="name" type="text" id="name" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td>Contact No.</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="contact" type="text" id="contact" size="45" onkeypress='validateNum(event)' />
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Email</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="mail" type="text" id="mail" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td height="60">Address</td>
<td><div align="center">:</div></td>
<td colspan="2">
<div align="right">
<textarea name="address" id="address" cols="35" rows="3"></textarea>
</div>
</td>
</tr>
<tr bgcolor="#99FFFF">
<td colspan="2"> </td>
<td width="231"><input type="reset" value="Clear" /></td>
<td width="47"><div align="right">
<input type="submit" value="Update" />
</div></td>
</tr>
</table>
<br>
</div>
</form>
<br>
</div>
</form>
<div align="center">
<?php
if (!mysql_connect('localhost', 'root', '')) {
echo "Connected";
}
mysql_select_db("workshop");
// Get values from form
$ic = mysql_real_escape_string($_POST['ic']);
$name = mysql_real_escape_string($_POST['name']);
$contact = mysql_real_escape_string($_POST['contact']);
$mail = mysql_real_escape_string($_POST['mail']);
$address = mysql_real_escape_string($_POST['address']);
if (staff_detail_exist($ic) == "available") {
insert_staff_detail($ic, $name, $contact, $mail, $address, $paytype);
echo "<p style='text-align:center; color:green;'>" . "Workshop application successful! You will be notified shortly via E-mail after confirmation! Thank You!";
} else if (staff_detail_exist($ic) == "exist") {
echo "<p style='text-align:center; color:red;'>" . "Record already exists! Please enter another Staff ID. Thank You!" . "</p>";
}
function insert_staff_detail($ic, $name, $contact, $mail, $address, $paytype) {
$sql = "INSERT INTO apply (staffid, staffname, staffno, staffemail, staffaddress, paytype) VALUES ('$ic', '$name', '$contact', '$mail', '$address','$paytype')";
mysql_query($sql);
}
function staff_detail_exist($ic) {
$result = null;
$sql = "SELECT * FROM apply WHERE staffid = '$ic'";
$data = mysql_query($sql);
if (mysql_num_rows($data) == 0) {
$result = "available";
} else {
$result = "exist";
}
return $result;
}
$staffid = $_POST['ic'];
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("workshop", $con);
$result = mysql_query("SELECT * FROM apply where staffid = '$ic'");
echo "<table width=400 border=1 cellpadding=0 align=center>";
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<th>Staff/IC Number: </th><td>" . "<center>" . $row['staffid'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Name: </th><td>" . "<center>" . $row['staffname'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Email: </th><td>" . "<center>" . $row['staffemail'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Contact No.: </th><td>" . "<center>" . $row['staffno'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Address: </th><td>" . "<center>" . $row['staffaddress'] . "</center>" . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</body>
</html>
I've tried to add like value="<? echo "$row['staffid']"?>" in the form's field at php file but no luck! I've only basic in php. So, any help? thank you!
thanks all, its finally working :) i've used value="<?php echo isset($_POST['myField']) ? $_POST['myField'] : 'myField_db' ?>" inside the input tag. so, its like: <input type="text" name="myField" value="<?php echo isset($_POST['myField']) ? $_POST['myField'] : 'myField_db' ?>" /> where myField is input name & myField_db is the column name from database.
Take the form posted values just above your html code like this
<?php
if (isset($_POST["submit"]) && $_POST["submit"]=='Submit') {
$name=$_POST["name"];
}
?>
And echo it in your html form.
<input name="name" type="text" id="name" size="45" value="<? echo $name?>"/>
I've used this function a few times; quite handy
function getPost($field){
return (isset($_POST[$field]) && $_POST[$field] != "" ? $_POST[$field] : "");
}
Usage
<input type="text" name="contact" value="<?php echo getPost("contact"); ?>" />
This is for the cases where a user submits information and is for some reason sent back to the form again - perhaps their entries didn't pass PHP validation, for example.