Uploading files to Google Drive - php

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');
?>

Related

Access the content of page if session is activated else activate session first

please help me solve this problem. I want to access content of a page only when Session is activated, else redirect user to activate session first. But when I redirect user to session page, it is stuck and cannot go back to content page. I am new here so please help me out from this problem.
<?php
session_start();
if(!isset($_SESSION['username'])){
echo "cookie is not activated" ;
header('Location: http://localhost/CC/Loginsession.php');
die;
}
else {
?>
<!doctype html>
<html>
<head>
<title>Update in PHP</title>
</head>
<body>
<?php
$servername="localhost";
$username="root";
$password="";
$conn=mysql_connect($servername,$username,$password);
if(!$conn ) {
die('Could not connect: ' . mysql_error());
}
$sq1 = 'select * from biodata';
mysql_select_db('firstdb');
$display=mysql_query($sq1,$conn);
if(!$display ) {
die('Could not get data: ' . mysql_error());
exit;
}
if (mysql_num_rows($display) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
?>
<table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
<thead>
<tr>
<th>ID</th>
<th>Fname</th>
<th>Lname</th>
<th>Email</th>
<th>Phone</th>
<th>Message</th>
<th>Update</th>
</tr>
</thead>
<tbody>
<?php
while( $row = mysql_fetch_assoc( $display ) ){
echo
"<form method= 'post' />
<tr>
<td ><input name='UID' value='{$row['ID']}' readonly/></td>
<td ><input name='upfname' value='{$row['fname']}' /></td>
<td ><input name='uplname' value='{$row['lname']}' /></td>
<td ><input name='upemail' value='{$row['email']}' /></td>
<td ><input name='upphone' value='{$row['phone']}' /></td>
<td ><input name='upmessage' value='{$row['message']}' /></td>
<td><input type='Submit' name='update' value='Update' id='".$row["ID"]."' </td>
</tr>
</form>";
}
?>
</tbody>
</table>
<?php
if(isset($_REQUEST['update']))
{
$id = $_REQUEST['UID'];
$upfn = $_REQUEST['upfname'];
$upln = $_REQUEST['uplname'];
$upem = $_REQUEST['upemail'];
$upph = $_REQUEST['upphone'];
$upms = $_REQUEST['upmessage'];
$up="UPDATE biodata
SET
fname='$upfn',
lname='$upln',
email='$upem',
phone='$upph',
message='$upms'
WHERE ID = $id";
$updbb=mysql_query($up,$conn);
if($updbb){
header('Location: http://localhost/Prac/updateinsamepage.php');
}
}
}
?>
</body>
</html>>
and My session Login form code is here
<?php
session_start();
if(isset($_SESSION['username'])){
echo "Already registered as $_SESSION[username]" ;
}
else if($_SERVER['REQUEST_METHOD'] == 'POST'){
$uname=htmlentities($_POST['username']);
$pass=htmlentities($_POST['password']);
if(!empty($uname) && !empty($pass)) {
$_SESSION['username']=$uname;
echo "Thanks<br />" . "UserName: $uname " . "Password: $pass";
}
else{
echo "Please fill out the both fields";
}
}
else {
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Loginsession</title>
</head>
<body>
<form method="post">
Username:<input type="text" id="username" name="username" /> <br /><br />
Password:<input type="password" id="password" name="password"/><br /><br />
<input type="hidden" name="hiddenvalue" value="<?php http://localhost/CC/Loginsession.php?username=overwritten ?>"/>
<input type="Submit" value="Login" name="Submit" id="submit" />
</form>
<?php }?>
<?php
session_unset();
session_destroy();
?>
</body>
</html>
You can try this script in place of header
echo '<script>window.location="localhost/CC/Loginsession.php"</script>';

PHP $_POST Form validation and Postback

I am working on an assignment for my PHP1 Class and we are working on sticky forms, my assignment is to write an order form that validates that both a name is entered and a phone model is selected and if both are filled posts that data back to the page and if one or both is missing an error message is posted back to the page. Accessories are Optional. Currently the script will post an error if no phone is selected and a name is input into the form, it will post an error if both are missing, but if a name is missing and a phone is selected then it will not flag as an error and continue processing the script back to the page. I attempted to right a function to validate that both the userName text field AND a phones radio button are selected to be true or if false then the error message is presented. Can anyone tell me why my form is processing the data when only a phone model is selected and the name field is blank?
Script(OrderForm):
<!DOCTYPE html>
<html>
<head>
<title>Order Form</title>
</head>
<body>
<h1>Order Your Smartphone</h1>
<?php
/**
* Created by PhpStorm.
* User: Daniel Vermillion
* Date: 10/27/2014
* Time: 7:59 PM
*/
$isValid = false;
//function totalAcc() {
// foreach($_POST['acc'] as $item) {
// $accPrice[] = $item;
// }
// array_sum($accPrice);
// return $accPrice;
//}
//function totalCost() {
// $subtotal = $phonePrice + $accPrice;
// $tax = 0.08;
// $taxTotal = $subtotal * $tax;
// $total = $subtotal + $taxTotal;
// return $subtotal;
// return $taxTotal;
// return $total;
//}
function validData() {
if(isset($_POST['userName']) && isset($_POST['phones'])) {
return true;
}
else {
return false;
}
}
function calcResults() {
$isValid = validData();
if($isValid) {
echo "Full Name: {$_POST['userName']} <br />";
echo "Phone Model: {$_POST['phones']} <br />";
echo "Accessories: {$_POST['acc']} <br />";
// echo "Subtotal: $subtotal <br />";
// echo "Tax: '$taxTotal' <br />";
// echo "Total Cost: $total <br />";
}
else {
echo "Please enter your name and select a phone model.";
}
}
?>
<form method="post" action="index.php">
Full Name: <input type="text" name="userName" value="<?php if(isset($_POST['userName'])) echo $_POST['userName']; ?>" /><br />
<h4>Add Smartphone</h4>
<table cellspacing="4" cellpadding="4" border="1">
<tr>
<td></td>
<td>Phone</td>
<td>Model</td>
<td>Storage</td>
<td>Price</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="SP8" <?php if(isset($_POST['phones']) && $_POST['phones'] == "SP8") echo 'checked'; ?> /></td>
<td>SuperPhone</td>
<td>SP8</td>
<td>8 GB</td>
<td>$400</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="SP16" <?php if(isset($_POST['phones']) && $_POST['phones'] == "SP16") echo 'checked'; ?> /></td>
<td>SuperPhone</td>
<td>SP16</td>
<td>16 GB</td>
<td>$450</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="MP8" <?php if(isset($_POST['phones']) && $_POST['phones'] == "MP8") echo 'checked'; ?> /></td>
<td>MegaPhone</td>
<td>MP8</td>
<td>8 GB</td>
<td>$500</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="MP16" <?php if(isset($_POST['phones']) && $_POST['phones'] == "MP16") echo 'checked'; ?> /></td>
<td>MegaPhone</td>
<td>MP16</td>
<td>16 GB</td>
<td>$550</td>
</tr>
</table>
<h4>Add Accessories</h4>
<table cellspacing="4" cellpadding="4" border="1">
<tr>
<td></td>
<td>Accessory</td>
<td>Price</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="handstrap" <?php if(isset($_POST['acc']) && in_array('handstrap', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Hand Strap</td>
<td>$6.25</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="leathercase" <?php if(isset($_POST['acc']) && in_array('leathercase', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Leather Case</td>
<td>$14.50</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="headphones" <?php if(isset($_POST['acc']) && in_array('headphones', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Headphones</td>
<td>$18.75</td>
</tr>
</table>
<br />
<input type="submit" name="submit" value="Click to Finalize Order" /><br /><br />
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
calcResults();
}
?>
</body>
</html>
isset() for strings returns true for an empty string.
https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
Try Empty()
edit: please note that if the field has a space in it, it will not be counted as empty. You should probably use Trim() on the result to ensure that there is no whitespace.
You need to echo the result..
replace
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
calcResults();
}
with
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo calcResults();
}
UPDATE:
<!DOCTYPE html>
<html>
<head>
<title>Order Form</title>
</head>
<body>
<h1>Order Your Smartphone</h1>
<?php
/**
* Created by PhpStorm.
* User: Daniel Vermillion
* Date: 10/27/2014
* Time: 7:59 PM
*/
$isValid = false;
//function totalAcc() {
// foreach($_POST['acc'] as $item) {
// $accPrice[] = $item;
// }
// array_sum($accPrice);
// return $accPrice;
//}
//function totalCost() {
// $subtotal = $phonePrice + $accPrice;
// $tax = 0.08;
// $taxTotal = $subtotal * $tax;
// $total = $subtotal + $taxTotal;
// return $subtotal;
// return $taxTotal;
// return $total;
//}
function validData() {
if(isset($_POST['userName']) && !empty($_POST['userName'])) {
if(isset($_POST['phones']) && !empty($_POST['phones'])) {
$acc = (isset($_POST['acc']) && !empty($_POST['acc'])) ? " <br />Accessories: " . implode(" and ",$_POST['acc']) . " <br />" : "";
return "Full Name: " . $_POST['userName'] . " <br />Phone Model: " . $_POST['phones'] . $acc;
} else {
return "Please enter the phone model.";
}
} else {
return "Please enter your name and select a phone model.";
}
}
function calcResults() {
$isValid = validData();
return $isValid;
}
?>
<form method="post" action="form.php">
Full Name: <input type="text" name="userName" value="<?php if(isset($_POST['userName'])) echo $_POST['userName']; ?>" /><br />
<h4>Add Smartphone</h4>
<table cellspacing="4" cellpadding="4" border="1">
<tr>
<td></td>
<td>Phone</td>
<td>Model</td>
<td>Storage</td>
<td>Price</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="SP8" <?php if(isset($_POST['phones']) && $_POST['phones'] == "SP8") echo 'checked'; ?> /></td>
<td>SuperPhone</td>
<td>SP8</td>
<td>8 GB</td>
<td>$400</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="SP16" <?php if(isset($_POST['phones']) && $_POST['phones'] == "SP16") echo 'checked'; ?> /></td>
<td>SuperPhone</td>
<td>SP16</td>
<td>16 GB</td>
<td>$450</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="MP8" <?php if(isset($_POST['phones']) && $_POST['phones'] == "MP8") echo 'checked'; ?> /></td>
<td>MegaPhone</td>
<td>MP8</td>
<td>8 GB</td>
<td>$500</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="MP16" <?php if(isset($_POST['phones']) && $_POST['phones'] == "MP16") echo 'checked'; ?> /></td>
<td>MegaPhone</td>
<td>MP16</td>
<td>16 GB</td>
<td>$550</td>
</tr>
</table>
<h4>Add Accessories</h4>
<table cellspacing="4" cellpadding="4" border="1">
<tr>
<td></td>
<td>Accessory</td>
<td>Price</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="handstrap" <?php if(isset($_POST['acc']) && in_array('handstrap', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Hand Strap</td>
<td>$6.25</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="leathercase" <?php if(isset($_POST['acc']) && in_array('leathercase', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Leather Case</td>
<td>$14.50</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="headphones" <?php if(isset($_POST['acc']) && in_array('headphones', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Headphones</td>
<td>$18.75</td>
</tr>
</table>
<br />
<input type="submit" name="submit" value="Click to Finalize Order" /><br /><br />
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo calcResults();
}
?>
</body>
</html>

Updata And delete from table

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.

for update code in same page need ajax or else?

when i press on edit link on detail.php it will show me data.php page with data filled in form... now if i want to edit something then press edit button it would be update.. code of data.php is given as below
<?php if(isset($_GET['name']) && !empty($_GET['name'])):?>
<script>
window.onload=function()
{
document.getElementById("sbmt").style.visibility="hidden";
};
function editform()
{
i need code at this place _what should it be?? i guess i need ajax. when i press edit button it would be edit record i tried below something like below bt for that i need value name=??? how can i get that value _
<?php
$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_query($con,"UPDATE user_detail SET name=,address=,gender=,hoby=,country=,place=,
//WHERE name='$_GET['name']'");
mysqli_close($con);
?>
};
</script>
<?php
$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$p= $_GET['name'];
//echo "$p";
$result = mysqli_query($con,"SELECT * FROM user_detail where name ='$p' ");
$data =mysqli_fetch_array($result);
mysqli_close($con);
?>
<?php else:?>
<script>
window.onload=function()
{
document.getElementById("edit").style.visibility="hidden";
};
</script>
<?php $data =array();?>
<?php endif;?>
<!DOCTYPE html>
<?php
session_start();
if (!isset($_SESSION['txt_user'])) {
header('Location: Login.php');
}
?>
<html>
<head>
<title> Form with Validation </title>
<script language="JavaScript">
var flag=0;
var file_selected = false;
var file_selected1 = false;
function validform()
{
var x=document.forms["form1"]["tname"].value;//Name
var y=document.forms["form1"]["address"].value;//Address
if (x==null || x=="")
{
flag = 1;
document.getElementById('tn').value="Please! Enter name ";
//alert("Please Enter Name:");
//return false;
}
else
{
flag=0;
}
if (y==null || y==" ")
{
flag=flag+1;
document.getElementById('ta').innerHTML="Please! Enter address ";
//alert("Please Enter Address");
//return false;
}
else
{
flag=0;
}
if ((form1.gender[0].checked == false) && (form1.gender[1].checked == false))
{
flag +=1;
document.getElementById('gne').innerHTML="Please! Select gender ";
//alert("Pleae Select Gender");
//return false;
}
else
{
flag =0;
document.getElementById('gne').innerHTML="";
}
if (form1.hobby.checked == false && form1.hobby.checked == false && form1.hobby.checked == false)
{
flag +=1;
document.getElementById('hbe').innerHTML="Please! Select hobby ";
//alert ('Please!!!, Select any hobby!');
//return false;
}
else
{
flag =0;
document.getElementById('hbe').innerHTML="";
}
var psel=document.getElementById('fp'); //Favourite place
var valid = false;
for(var i = 0; i < psel.options.length; i++) {
if(psel.options[i].selected) {
valid = true;
break;
}
}
if(valid==false)
{
flag +=1;
document.getElementById('fp_error').innerHTML="Please! Select Any Favourite Place ";
//return false;
// alert("Please! Select Any Favourite Place ");
}
else
{
flag =0;
document.getElementById('fp_error').innerHTML="";
}
if(!file_selected)
{
flag +=1;
document.getElementById('f_pic').innerHTML="Please! Select Any Picture ";
//alert('Please Select any Picture');
//return false;
}
else
{
flag =0;
document.getElementById('f_pic').innerHTML="";
}
if(!file_selected1)
{
flag +=1;
document.getElementById('f_doc').innerHTML="Please! Select Document";
//alert('Please Select any Document');
//return false;
}
else
{
flag =0;
}
if(flag ==0)
{
document.getElementById('data_form').action = "Data_con.php";
document.getElementById('data_form').submit();
}
else
{
return true;
}
return false;
}
function Logout()
{
document.getElementById('data_form').action = "Logout.php";
}
</script>
</head>
<body>
<!--onsubmit="return validform()"-->
<form id="data_form" name="form1" method="post" enctype="multipart/form-data" action="">
<table align="center" border="2">
<tr>
<td>Name:</td>
<td><input id="tn" type="text" name="tname" <?php if($data['name']):?>value="<?php echo $data['name'];?>" <?php endif;?>></td>
<!--<td id="tne"></td>-->
</tr>
<tr>
<td>Address:</td>
<td><textarea id= "ta" rows="3" cols="16" name="address" >
<?php echo $data['address'];?>
</textarea> </td>
<!--<td id="tae"></td>-->
</tr>
<tr>
<td>Gender:</td>
<?php
$x=$data['gender'];
?>
<td> <input type="radio" id="gn" name="gender" value="male" <?php if($x=='male'):?> checked<?php endif;?> > Male
<input type="radio" id="gn" name="gender" value="female" <?php if($x=='female'):?> checked<?php endif;?> > Female
</td>
<td id="gne"></td>
</tr>
<tr>
<td>Hobby:</td>
<?php
$y=$data['hoby'];
?>
<td>
<input type="checkbox" name="hobby" value="hockey" <?php if($y=='hockey'):?> checked='checked';<?php endif;?>> Hockey
<input type="checkbox" name="hobby" value="reading" <?php if($y=='reading'):?> checked='checked';<?php endif;?>> Reading<br>
<input type="checkbox" name="hobby" value="traveling" <?php if($y=='traveling'):?> checked='checked';<?php endif;?>> Traveling
<br>
</td>
<td id="hbe"></td>
</tr>
<tr>
<td>Country: </td>
<?php
$z=$data['country'];
?>
<td>
<select name="helo" id="hl">
<option value="germany"<?php if($z=='germany'):?> selected<?php endif;?> >Germany </option>
<option value="india" <?php if($z=='india'):?> selected <?php endif;?> >India </option>
<option value="japan" <?php if($z=='japan'):?> selected<?php endif;?> >Japan </option>
</select>
</td>
<td id="hle"></td>
</tr>
<tr>
<td>Favourite Place:</td>
<?php
$w =$data['place'];
?>
<td>
<select id="fp" name="place" multiple="multiple">
<option value="ahmedabad" <?php if($w=='ahmedabad'):?> selected<?php endif;?> >Ahmedabad</option>
<option value="nadiad" <?php if($w=='nadiad'):?> selected<?php endif;?> >Nadiad</option>
<option value="anand" <?php if($w=='anand'):?> selected<?php endif;?> >Anand</option>
<option value="vadodara" <?php if($w=='vadodara'):?> selected<?php endif;?> >Vadodara</option>
<option value="surat" <?php if($w=='surat'):?> selected<?php endif;?> >Surat</option>
</select>
</td>
<td id="fp_error"></td>
</tr>
<tr>
<td>Photo:</td>
<td><input type="file" onchange="file_selected=true;" name="pic" ></td>
<td id="f_pic"></td>
</tr>
<tr>
<td>Resume:</td>
<td><input type="file" onchange="file_selected1=true;" name="doc" ></td>
<td id="f_doc"></td>
</tr>
<tr>
<td colspan="2"><center>
<input type="Submit" id="edit" value="edit" Name="Edit" onclick="editform();">
<input type="button" id="sbmt" value="Submit" Name="Submit" onclick="validform();">
<input type="submit" value="Logout" Name="Submit" onclick="Logout();">
<center></td>
</tr>
</table>
</form>
</body>
</html>
Thanks friend...

How to keep input in fields after form submitted for further update

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.

Categories