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...
Related
I have three Table their structure is added down there. i want to show all role on one screen. and when click on one any role it will take you to next screen where (all the permission shown in check boxes) permission that is given to that role checked and other unchecked. and i want to that dynamically, as it can be given and taken by using check boxes. there check boxes should contain role_id and perm_id so it can b use for crud operations.table has many to many relation.
i have the role_id bu using the isset($_GET['role_id']) metthod and perm_id by calling a function that will give me the perm_id
<?php if (isset($_GET['role_id'])) {
$role_id = $_GET['role_id'];
} ?>
user_permission.php page
<?php $row = $role->allPermission($role_id); if(!empty($row)){
?>
<table class="table table-bordered table-striped" id="datatable-editable">
<thead>
<tr>
<th><center>Add</center></th>
<th><center>Update</center></th>
<th><center>Delete</center></th>
<th><center>View</center></th>
</tr>
</thead>
<tbody>
<tr>
<?php $all_permissions = $permission->allPermissions();
while ($row=mysqli_fetch_assoc($all_permissions)) {
$perm_id = $row['perm_id'];
$check_permission = $permission->checkPermission($role_id,$perm_id);
while ($row=mysqli_fetch_assoc($check_permission)){
?>
<td><center><input type="checkbox" perm_id="<?php echo $row['perm_id']?>" value="<?php echo $row['permission']?>"> <?php echo $row['permission']?>
</center>
</td>
<?php
}} ?>
</tr>
<tr>
<?php foreach ($row as $val) {?>
<td>
<?php if ($val['permission'] == 'add' || $val['permission'] == 'update' || $val['permission'] == 'delete' || $val['permission'] == 'view'){ ?>
<input type="checkbox" checked="checked" value="<?php echo $val['id']?>">
<?php } else { ?> <input type="checkbox" value="<?php echo $val['id']?>" > <?php }?>
</td>
<?php } ?>
<!-- foreach ($value as $key => $val) {
// echo $key . ' => ' . $val." / ";
echo $key['prem'];
} -->
<!-- <td>
<?php if (in_array('add', $row)){ ?>
<input type="checkbox" checked="checked" value="<?php echo $id?>">
<?php } else { ?> <input type="checkbox" > <?php }?>
</td>
<td>
<?php if (in_array('update', $row)){ ?>
<input type="checkbox" checked="checked">
<?php } else { ?> <input type="checkbox" > <?php }?>
</td>
<td>
<?php if (in_array('delete', $row)){ ?>
<input type="checkbox" checked="checked">
<?php } else { ?> <input type="checkbox" > <?php }?>
</td>
<td>
<?php if (in_array('view', $row)){ ?>
<input type="checkbox" checked="checked">
<?php } else { ?> <input type="checkbox" > <?php }?>
</td> -->
</tr>
</tbody>
</table>
allPermissions()
public function allPermissions()
{
$query="SELECT * from permission where status = 1";
$conn=$this->Connection();
$result = mysqli_query($conn,$query);
$num_rows = mysqli_num_rows($result);
if ($num_rows>0) {
return $result;
}
}
chechkPermission()
public function checkPermission($role_id,$perm_id)
{
$query = "select * from role_perm rp where role_id = '$role_id' and perm_id = '$perm_id' ";
$conn=$this->Connection();
$result = mysqli_query($conn,$query);
$num_rows = mysqli_num_rows($result);
if ($num_rows>0) {
return $result;
}
}
its been three(now) days i'm stuck here, please help. and sorry for my bad english
Table Structure
This is how i want it
you mean something like this? <input type="checkbox" <?= ($permission >= 3 ? "checked" : "") ?>
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');
?>
in this code,error message shows error by alert box,but i want to see error message below particular text box. mean when i click on submit button which field not fill, below that field it should display message below that field.
and also there is one problem if i not fill radio button or checkbox and other all are filled and when i click on submit button it store in database other all detail except that radio or checkbox.
so how can i solve it
Thanks.....
<!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 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
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;
}
}//Favourite place
if (x==null || x=="")
{
alert("Please Enter Name:");
//flag = 0;
}
if (y==null || y==" ")
{
alert("Please Enter Address");
}
if ((form1.gender[0].checked == false) && (form1.gender[1].checked == false))
{
alert("Pleae Select Gender");
}
if (form1.hobby.checked == false && form1.hobby.checked == false && form1.hobby.checked == false)
{
alert ('Please!!!, Select any hobby!');
}
if(valid==false)
{
alert("Please! Select Any Favourite Place ");
}
if(!file_selected)
{
alert('Please Select any Picture');
}
if(!file_selected1)
{
alert('Please Select any Document');
return false;
}
{
document.getElementById('data_form').action = "Data_con.php";
return false;
}
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 type="text" name="tname"></td>
</tr>
<tr>
<td>Address:</td>
<td><textarea rows="3" cols="16" name="address"> </textarea> </td>
</tr>
<tr>
<td>Gender:</td>
<td> <input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
</td>
</tr>
<tr>
<td>Hobby:</td>
<td>
<input type="checkbox" name="hobby" value="hockey"> Hockey
<input type="checkbox" name="hobby" value="reading"> Reading<br>
<input type="checkbox" name="hobby" value="traveling"> Traveling
<br>
</td>
</tr>
<tr>
<td>Country: </td>
<td>
<select name="helo">
<option value="germany">Germany </option>
<option value="india" selected>India </option>
<option value="japan">Japan </option>
</select>
</td>
</tr>
<tr>
<td>Favourite Place:</td>
<td>
<select id="fp" name="place" multiple="multiple">
<option value="ahmedabad">Ahmedabad</option>
<option value="nadiad">Nadiad</option>
<option value="anand">Anand</option>
<option value="vadodara">Vadodara</option>
<option value="surat">Surat</option>
</select>
</td>
</tr>
<tr>
<td>Photo:</td>
<td><input type="file" onchange="file_selected=true;" name="pic" ></td>
</tr>
<tr>
<td>Resume:</td>
<td><input type="file" onchange="file_selected1=true;" name="doc" ></td>
</tr>
<tr>
<td colspan="2"><center>
<input type="submit" value="Submit" Name="Submit" onclick="validform();">
<input type="submit" value="Logout" Name="Submit" onclick="Logout();">
<center></td>
</tr>
</table>
</form>
</body>
</html>
you first create tds with different id's for each and every input field
instead of alert
document.getElementById('td id').innerHTML="your message";
return false;
like this
<tr>
<td>Favourite Place:</td>
<td>
<select id="fp" name="place" multiple="multiple">
<option value="ahmedabad">Ahmedabad</option>
<option value="nadiad">Nadiad</option>
<option value="anand">Anand</option>
<option value="vadodara">Vadodara</option>
<option value="surat">Surat</option>
</select>
</td>
<td id="fp_error"></td>
</tr>
and in javascript
document.getElementById('fp_error').innerHTML="your message";
return false;
download jquery.js and jquery.validate.js and validate form elements using below demo code.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"> </script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.validate.js"> </script>
<script>
$('document').ready(function() {
$('#data_form').validate({
rules: {
'tname': {
required: true
},
'address': {
required: true
}
},
messages:{
'tname': {
required: 'Please Enter Name'
},
'address': {
required: 'Please Enter address'
}
}
});
});
</script>
It is better way. Easy of implementation and also saves time.
I have a script below which the user logs a php form.
There is a section with 2 drop down menus next to each other, 'npc_battery_n_code' and 'npc_battery_other_code'.
What I am trying to do is to make it so one of these drop down menus has to have an option selected for the form to be submitted, but not both or none.
So for example, if an option gets selected in 'npc_battery_n_code' and then the user selects another option in 'npc_battery_other_code', then the value of the 'npc_battery_n_code' will revert to the 'None' option.
Any suggestions welcome
<?php //logsale.php
require_once ('./includes/config.inc.php');
$page_title = 'Log a sale';
include ('./includes/header.html');
if (!isset($_SESSION['sp_user_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
$users = $_SESSION['sp_user_id'];
?>
<h1>Heading</h1>
<?php
if (isset($_POST['submitted'])) {// Handle the form.
require_once ('mydatabase.php');
if (!empty($_POST['npc_quantity'])) {
$quantity = escape_data($_POST ['npc_quantity']);
} else {
$quantity = FALSE;
echo '<p><font color="red">You forgot to enter the Quantity</font></p>';
}
if (!empty($_POST['npc_customer_name'])) {
$customer = escape_data($_POST ['npc_customer_name']);
} else {
$customer = FALSE;
echo '<p><font color="red">You forgot to enter the Customer Name</font></p>';
}
if (!empty($_POST['npc_registration_no'])) {
$rego = escape_data($_POST ['npc_registration_no']);
} else {
$rego = FALSE;
echo '<p><font color="red">You forgot to enter the Customer Rego Number</font></p>';
}
if (!empty($_POST['npc_suo_no'])) {
$suo = escape_data($_POST ['npc_suo_no']);
} else {
$suo = FALSE;
echo '<p><font color="red">You forgot to enter the SUO Number</font></p>';
}
if (!empty($_POST['npc_amb_club_no'])) {
$repair_order = escape_data($_POST ['npc_amb_club_no']);
} else {
$repair_order = FALSE;
echo '<p><font color="red">You forgot to enter the A-Club number</font></p>';
}
if (!empty($_POST['npc_repair_order'])) {
$amb_club = escape_data($_POST ['npc_repair_order']);
} else {
$amb_club = FALSE;
echo '<p><font color="red">You forgot to enter the Repair Order</font></p>';
}
if (!empty($_POST['npc_invoice_no'])) {
$inv = escape_data($_POST ['npc_invoice_no']);
} else {
$inv = FALSE;
echo '<p><font color="red">You forgot to enter the Invoice Number </font></p>';
}
if (!empty($_POST['npc_entry_userdate'])) {
$inv_date = escape_data($_POST ['npc_entry_userdate']);
} else {
$inv_date = FALSE;
echo '<p><font color="red">You forgot to enter the Invoice Date</font></p>';
}
if ($quantity && $customer && $rego && $suo && $repair_order && $amb_club && $inv && $inv_date) {
$uid = #mysql_insert_id(); //Get the url ID.
$query = "INSERT INTO npc_sales_list
(npc_item_id , sp_user_id, npc_battery_n_code, npc_battery_other_code, npc_quantity,
npc_customer_name, npc_registration_no, npc_suo_no, npc_amb_club_no, npc_repair_order,
npc_entry_userdate, npc_usertype, npc_points, npc_bonus_points, npc_entry_date)
VALUES
('$uid', '$users', '$_POST[npc_battery_n_code]', '$_POST[npc_battery_other_code]', '$quantity',
$customer , $rego, $suo, $amb_club , $repair_order,
$inv , 'NPC', '5' , '0' , NOW())";
$result = mysql_query ($query) or trigger_error
("Query: $query\n<br />MySQL Error: " .mysql_error());
if ($result = #mysql_query($query)) {
//Finish the page.
echo '<p>The sale with invoice number: <strong>' . $inv . '</strong> <br />
is now registered into the system.</p>
<p>If you would like to log in further sales, please click here</p>
<p>If you would like to view your sales log, please click here</p>
';
include ('./includes/footer.html'); // Include the HTML footer.
exit();
} else { // If it did not run OK.
echo '<p><font color="red" size="+1">You could not be
registered due to a system error. We apologize for any
inconvenience.</font></p>';
}
}
} else { // If one of the data tests failed.
echo '<p><font color="red" size="+1">Please check all manatory fields are complete and try again.
</font></p>';
}
mysql_close(); // Close the database connection.
?>
<form enctype="multipart/form-data" action="logsale.php" method="post">
<table width="520" border="0" cellspacing="3" cellpadding="2">
<tr>
<td width="184"><div align="right">NPC Vehicle<span class="style2">*</span></div></td>
<td width="323"><select name="npc_battery_n_code" id="npc_battery_n_code">
<option value="None"
<?php if (isset($_POST['npc_battery_n_code']) && $_POST['npc_battery_n_code'] == 'None')
{echo 'selected="selected"';} ?>>None
</option>
<option value="55D23L"
<?php if (isset($_POST['npc_battery_n_code']) && $_POST['npc_battery_n_code'] == '55D23L')
{echo 'selected="selected"';} ?>>55D23L
</option>
<option value="55D23R"
<?php if (isset($_POST['npc_battery_n_code']) && $_POST['npc_battery_n_code'] == '55D23R')
{echo 'selected="selected"';} ?>>55D23R
</option>
<option value="75D23R"
<?php if (isset($_POST['npc_battery_n_code']) && $_POST['npc_battery_n_code'] == '75D23R')
{echo 'selected="selected"';} ?>>75D23R
</option>
</select></td>
</tr>
<tr>
<td width="184"><div align="right">Other <span class="style2">*</span></div></td>
<td width="323">
<select name="npc_battery_other_code" id="npc_battery_other_code">
<option value="50D20L"
<?php if (isset($_POST['npc_battery_other_code']) && $_POST['npc_battery_other_code'] == '50D20L')
{echo 'selected="selected"';} ?>>50D20L
</option>
<option value="50D20R"
<?php if (isset($_POST['npc_battery_other_code']) && $_POST['npc_battery_other_code'] == '50D20R')
{echo 'selected="selected"';} ?>>50D20R
</option>
<option value="55D23LMF"
<?php if (isset($_POST['npc_battery_other_code']) && $_POST['npc_battery_other_code'] == '55D23LMF')
{echo 'selected="selected"';} ?>>55D23LMF
</option>
<option value="55D23RMF"
<?php if (isset($_POST['npc_battery_other_code']) && $_POST['npc_battery_other_code'] == '55D23RMF')
{echo 'selected="selected"';} ?>>55D23RMF
</option>
</select></td>
</tr>
<tr>
<td><div align="right">Quantity <span class="style2">*</span></div></td>
<td><input type="text" name="npc_quantity" size="10" maxlength="10"
value="<?php if (isset($_POST['npc_quantity'])) echo $_POST['npc_quantity']; ?>" /></td>
</tr>
<tr>
<td><div align="right">Customer name<span class="style2">*</span></div></td>
<td><input type="text" name="npc_customer_name" size="30" maxlength="30"
value="<?php if (isset($_POST['npc_customer_name'])) echo $_POST['npc_customer_name']; ?>" /></td>
</tr>
<tr>
<td><div align="right">Rego number <span class="style2">*</span></div></td>
<td><input type="text" name="npc_registration_no" size="10" maxlength="7"
value="<?php if (isset($_POST['npc_registration_no'])) echo $_POST['npc_registration_no']; ?>" /></td>
</tr>
<tr>
<td><div align="right">SUO No.<span class="style2">*</span></div></td>
<td><input type="text" name="npc_suo_no" size="10" maxlength="7"
value="<?php if (isset($_POST['npc_suo_no'])) echo $_POST['npc_suo_no']; ?>"/></td>
</tr>
<tr>
<td><div align="right">A-Club ID<span class="style2">*</span></div></td>
<td><input type="text" name="npc_amb_club_no" size="15" maxlength="7"
value="<?php if (isset($_POST['npc_amb_club_no'])) echo $_POST['npc_amb_club_no']; ?>"/></td>
</tr>
<tr>
<td><div align="right">Repair Order <span class="style2">*</span></div></td>
<td><input type="text" name="npc_repair_order" size="15" maxlength="12"
value="<?php if (isset($_POST['npc_repair_order'])) echo $_POST['npc_repair_order']; ?>" /></td>
</tr>
<tr>
<td><div align="right">Invoice No. <span class="style2">*</span></div></td>
<td><input size="10" name="npc_invoice_no"
value="<?php if (isset($_POST['npc_invoice_no'])) echo $_POST['npc_invoice_no']; ?>" /></td>
</tr>
<tr>
<td><div align="right">Invoice Date <span class="style2">*</span></div></td>
<td><input size="12" name="npc_entry_userdate" maxlength="10"
value="<?php if (isset($_POST['npc_entry_userdate'])) echo $_POST['npc_entry_userdate']; ?>"/> </td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Submit" /></p><input type="hidden" name="submitted" value="TRUE" />
</td>
</tr>
</table>
</form>
<p>Footer</p>
<?php
include ('./includes/footer.html');
?>
jquery: select and unselect items of listbox is what you are looking for.
How you want your script to work cannot be achieved with PHP or Mysql. You can only work with the data when the website is loaded. If you want to edit the data without refreshing the page you need to use JavaScript, or more advanced jQuery.
I have 2 dropdowns on my HTML page : The first drop down contains the database column names based on which the the second dropdown would be populated i.e.
I have a single table with fields: <Student Name, Degree, City> and following would be the entries;
1. "A", "BS", "New York"
2. "B", "BS", "Chicago"
3. "C", "MS", "Boston"
4. "D", "MS", "New York"
So my first dropdown would contain the column names i.e. "Degree" and "City".
If I select "Degree", the 2nd dropdown should populate "BS" and "MS" and if I select "City", the 2nd dropdown should select "New York", "Boston" and "Chicago".
How can I go about with the implementation?
[Adding my code]:
the changeSecond(first) method remains exactly the same as you suggested
<body>
<form method="POST" action="" name="mainForm">
<table>
<tr>
<td> Filter by: </td>
<td>
<div id="first">
<select onChange="changeSecond(this.value)">
<option value="1">All</option>
<option value="2">Degree</option>
<option value="3">City</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td>
<div id="second">
<select name="val">
<option value=""></option>
</select>
</div>
</td>
</tr>
</table>
</form>
</body>
And this is the second_script.php as you suggested:
<?
$link = mysql_connect("localhost", "root", "");
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_select_db("myDatabase", $link))
{
$first=mysql_real_escape_string($_REQUEST["first"]);
$query="SELECT ".$first." FROM myTable GROUP BY ".$first;
$data=mysql_query($query);
echo "<select id=\"second\">";
while($row=mysql_fetch_row($data))
{
echo "<option value=\"".$row[0]."\">".$row[0]."</option>";
}
echo "</select>";
}
echo mysql_error();
?>
code for the main file in which you want to populate drop down based on other
in below example i show localities in child dropdown for that city that is selected in parent drop down
<script type="text/javascript">
function city_locality(val)
{
// alert (val);
url="<?php echo $this->baseurl ?>/components/com_ezportal/includes/query.php";
data="stid="+val;
$.post(url,data,function(data){
$("#locid").html(data);
});
}
</script>
<select name="filter_1state" id="filter_1state" onChange="city_locality(this.value)">
<option value="0">-- Select City --</option>
<option value="1">Lahore</option>
<option value="2">Karachi</option>
<option value="3">Islamabad</option>
<option value="4">Quetta</option>
<option value="5">Multan</option>
</select>
code for the file query.php
<?php
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('mydatabase');
if (isset($_POST['stid']))
{
$stid = $_POST['stid'];
$query= mysql_query("SELECT id,ezcity FROM tbl_locality WHERE stateid = '".$stid."' GROUP BY ezcity");
?>
<option value="0">-- Select Locality --</option>
<?php
while($row = mysql_fetch_array($query))
{
?>
<option value="<?php echo $row['id']?>"><?php echo $row['ezcity']?> </option>
<?php
}
}
?>
If you want a more dynamic solution (that will accommodate changes to the background DB) you can do something like this on your page:
<script>
function changeSecond(first){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var res=xmlhttp.responseText;
document.getElementById("second").innerHTML=res;
}
}
xmlhttp.open("GET","second_script.php?first="+first,true);
xmlhttp.send();
}
</script>
...
<select onChange="changeSecond(this.value)">
<option value="Degree">Degree</option>
<option value="City">City</option>
</select>
<div id="second"><select><option value=""></option></select></div>
and then a script similar to:
<?php
//database connection
$first=mysql_real_escape_string($_REQUEST["first"]);
$query="SELECT ".$first." FROM tablename GROUP BY ".$first;
$data=mysql_query($query);
echo "<select>";
while($row=mysql_fetch_row($data)){
echo "<option value=\"".$row[0]."\">".$row[0]."</option>";
}
echo "</select>";
?>
I guess for real flexibility you'd also want to dynamically populate that first one using mysql_field_name in another script similar to above
You could either have all the dropdown needed preloaded and hidden, and show them when the 'change' event is triggered in the first dropdown, or have two dropdowns and empty it on that same 'change' event.
If you choose the second approach you should buffer the data to insert in the dropdown list, partially or totally
You can use ajax for this purpose
eg1.html
<html>
<head><title></title>
</head>
<body>
<form method="POST" action="" name="mainForm">
<table>
<tr>
<td> Filter by: </td>
<td>
<div id="first">
<select id="first_dropdown">
<option value="All">All</option>
<option value="Degree">Degree</option>
<option value="City">City</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td>
<div id="second">
<select id="second_dropdown">
</select>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
<script src = "https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#first_dropdown').change(function(){
$.ajax({
'type' : 'post',
'url' : 'getDropdownOptions.php',
'data': 'first=' + $(this).val(),
'success' : function(data) {
$('#second_dropdown').html(data);
}
});
});
});
</script>
getDropdownOptions.php
<?php
$link = mysql_connect("localhost", "root", "");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if (mysql_select_db("myDatabase", $link)) {
$first = mysql_real_escape_string($_REQUEST["first"]);
$query = "SELECT " . $first . " FROM myTable GROUP BY " . $first;
$data = mysql_query($query);
$rtn_data = '';
while ($row = mysql_fetch_row($data)) {
$rtn_data .= "<option value=\"" . $row[0] . "\">" . $row[0] . " </option>";
}
echo $rtn_data;
exit;
}
echo mysql_error();
?>
Divyesh here, your answer is
==============================
edit.php
==============================
<!-- edit.php -->
<?php
include("config.php");
$id=$_REQUEST['id'];
echo $id;
$query=mysqli_query($con,"SELECT * FROM register r
INNER JOIN country c ON r.cuid = c.cuid
INNER JOIN state s ON r.sid = s.sid
INNER JOIN city ct ON r.cid = ct.cid where id='$id'");
while($r=mysqli_fetch_array($query))
{
$fn=$r['firstname'];
$add=$r['address'];
$gn=$r['gender'];
$hobby=$r['hobby'];
$h=explode(',',$hobby);
$q=array('reading','traveling','cricket','drawing');
$country=$r['cuid'];
$state=$r['sid'];
$city=$r['cid'];
echo $gn;
$edu= $r['education'];
$email=$r['email'];
$pass=$r['password'];
$conpass=$r['conpassword'];
$phno=$r['phoneno'];
}
?>
<html>
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'cuid='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html(html);
}
});
}else{
$('#state').html(html);
$('#city').html(html);
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'sid='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html(html);
}
});
});
</script>
</head>
<body>
<form method="post" action="update.php">
<table border="1" align="center">
<caption>Edit user data</caption>
<tr>
<td>First name</td>
<td><input type="text" name="fn" value="<?php echo $fn;?>"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="add" value="<?php echo $add;?>"></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gn" value="male" <?php echo ($gn=='male')?'checked':'' ; ?> size="17">Male
<input type="radio" name="gn" value="female" <?php echo ($gn=='female')?'checked':'' ; ?> size="17">Female
</td>
</tr>
<tr>
<td>Hobby</td>
<td><input type="checkbox" name="hobby[]" value="reading" <?php if(in_array('reading',$h)){echo ("checked:'checked'");}?> >reading
<input type="checkbox" name="hobby[]" value="traveling" <?php if(in_array('traveling',$h)){echo ("checked:'checked'");}?> >traveling
<input type="checkbox" name="hobby[]" value="cricket" <?php if(in_array('cricket',$h)){echo ("checked:'checked'");}?> >cricket
<input type="checkbox" name="hobby[]" value="drawing" <?php if(in_array('drawing',$h)){echo ("checked:'checked'");}?> >drawing</td>
</tr>
<?php
$query = mysqli_query($con,"SELECT * FROM country");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
?>
<td>Country</td>
<td><select name="country" id="country">
<option value="<?php echo $country;?>"><?php echo $country;?></option>
<?php
if($rowCount > 0)
{
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['cuid'].'">'.$row['country'].'</option>';
}
}
else
{
echo '<option value="">Country not available</option>';
}
?>
</select>
</td></tr>
<tr>
<td>State</td>
<td>
<select name="state" id="state">
<option value="<?php echo $state;?>"><?php echo $state;?></option>
</select>
</td></tr>
<tr>
<td>City</td>
<td>
<select name="city" id="city">
<option value="<?php echo $city;?>"><?php echo $city;?></option>
</select>
</td>
</tr>
<tr>
<td>Education</td>
<td><input type="text" name="edu" value="<?php echo $edu;?>"></td>
</tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email;?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="pass" value="<?php echo $pass;?>"></td>
</tr>
<tr>
<td>Confirm password</td>
<td><input type="text" name="conpass" value="<?php echo $conpass;?>"></td>
</tr>
<tr>
<td>Phone no</td>
<td><input type="text" name="phno" value="<?php echo $phno;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value="<?php echo $id;?>">
<input type="submit" name="update" value="update"></td>
</tr>
</table>
</form>
</body>
</html>
================
<h3>ajaxData.php</h3>
================
<!--ajaxData.php-->
<?php
//Include database configuration file
include("config.php");
if(isset($_POST["cuid"]) && !empty($_POST["cuid"]))
{
//Get all state data
$query = mysqli_query($con,"SELECT * FROM state WHERE cuid = ".$_POST['cuid']."");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
//Display states list
if($rowCount > 0)
{
echo '<option value="">Select state</option>';
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['sid'].'">'.$row['state'].'</option>';
}
}
else
{
echo '<option value="">State not available</option>';
}
}
if(isset($_POST["sid"]) && !empty($_POST["sid"]))
{
//Get all city data
$query = mysqli_query($con,"SELECT * FROM city WHERE sid =".$_POST['sid']."");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
//Display cities list
if($rowCount > 0)
{
echo '<option value="">Select city</option>';
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['cid'].'">'.$row['city'].'</option>';
}
}
else
{
echo '<option value="">City not available</option>';
}
}
?>