Once I check one checkbox of multiple students, only one student is stored inside my database. I want to get the value of the checkbox of each student added every input of the admin. One more thing is that I want to copy the data of the first name and section inside the table //see comment to "attendance" database. The database of the value inside the table is "student". Thanks in advance.
<html>
<body>
<form method = "POST"><strong>
Set the date:
</strong>
<input type = "date" name = "set_date"></br></br>
<table width="800" border="3" cellpadding="1" cellspacing="1">
<tr>
<th><center>First name</center></th>
<th><center>Section</center></th>
<th><center>Status</center></th>
</tr>
<?php
$con = mysql_connect("localhost", "root", "avtt123");
mysql_select_db("arvintarrega",$con);
$query = mysql_query("SELECT * FROM student");
echo "<form action = attendance.php method = POST>";
while($student=mysql_fetch_array($query))
{
echo "<tr>";
echo "<td><center>".$student['fname']."</center></td>"; // the 'fname' and the 'section'
echo "<td><center>".$student['section']."</center></td>";
echo '<td><center><input type = "checkbox" name = "status" value = "Present">Present </input>';
echo '<input type = "checkbox" name = "status" value = "Absent">Absent </input>';
}
echo "</form>";
echo "</table>";
if(isset($_POST['save']))
{
if(filter_input(INPUT_POST, 'set_date') && filter_input(INPUT_POST, 'status'))
{
if(isset($_POST['set_date']) && ($_REQUEST['status']=="Present"))
{
$sql = "INSERT INTO attendance(date, status) VALUES('$_POST[set_date]', '$_REQUEST[status]')";
echo '<span style="color:green;"><strong></br>Attendance Complete!<strong></span>';
}
else if(isset($_POST['set_date']) && ($_REQUEST['status']=="Absent"))
{
$sql = "INSERT INTO attendance(date, status) VALUES('$_POST[set_date]', '$_REQUEST[status]')";
echo '<span style="color:green;"><strong></br>Attendance Complete!<strong></span>';
}
mysql_query($sql, $con);
}
else
echo '<span style="color:red;"><strong></br>All fields are required</strong></span>';
}
?>
</br></br>
<input type = "submit" name = "save" value = "Submit>
</form>
</body>
</html>
Related
I've been trying to get this code to work for a long time now but i keep getting this error:
Notice: Undefined index: id in C:\xampp\htdocs\Project\modify.php on line 4
Here's the code:
<?php
include 'includes/phpConnection.php';
if(!isset($_POST["submit"])) {
$q = "SELECT * FROM members WHERE ID =".$_GET['id'];
$result = mysql_query($q);
$person = mysql_fetch_array($result);
}
?>
<h1>Edit A Member</h1>
<form method='post' action= '<?php echo $_SERVER['PHP_SELF']; ?>'>
First Name<input type = 'text' name= 'inputFName' value = '<?php echo $person['FIRST_NAME']?>'/>
First Last Name<input type = 'text' name= 'inputLname' value = '<?php echo $person['LAST_NAME']?>'/>
Second Last Name<input type = 'text' name= 'inputLname2' value = '<?php echo $person['LAST_NAME2']?>'/>
Date of Birth<input type = 'date' name= 'inputDoB' value = '<?php echo $person['DATE_OF_BIRTH']?>'/>
relation<input type = 'text' name= 'inputRelation' value = '<?php echo $person['relation_to_me']?>'/>
age<input type = 'text' name = 'age' />
<input type="hidden" name = "id" value="<?php echo $_GET['id'];?>"/>
<br />
<input type="submit" name="submit"/>
</form>
<?php
if(isset($_POST['submit'])){
$u = "UPDATE members SET `FIRST_NAME`='$_POST[inputFName]',`LAST_NAME`='$_POST[inputLname]',`LAST_NAME2`='$_POST[inputLname2]',`DATE_OF_BIRTH`='$_POST[inputDoB]',`AGE`= '$_POST[age]',`relation_to_me`='$_POST[inputRelation]' WHERE ID =".$_POST['id'];
mysql_query($u) or die(mysql_error());
}
?>
please help
It looks like you're posting id, not sending it as a query parameter.
if($_POST["id"] === "") echo "id is an empty string\n";
if($_POST["id"] === null) echo "id is null\n";
if(isset($_POST["id"])) echo "id is set\n";
if(!empty($_POST["id"])) echo "id is not empty";
Correct this in your code:
<?php
include 'includes/phpConnection.php';
if(!isset($_POST["submit"]) && isset($_GET["id"])) { // <--- declare id here
$id = intval($_GET["id"]); // <--- declare id here and admit only integer values
$q = "SELECT * FROM members WHERE ID =".$id;
$result = mysql_query($q);
$person = mysql_fetch_array($result);
}
?>
Remember to sanitize data input to prevent SQL Injection.
<?php for ($i=0; $i <$num_results; $i++){?>
<tr height="25px">
<td align="center "><?php $row = $result->fetch_assoc();
echo "<strong>". ($i+1)?><td >
<td align="center "><?php echo stripslashes($row['I'd]); ?><td>
What i want- i want to insert data into database if no existing data, and update if the data already exist in database.
Problem - If i click submit button without enter new data, the data still insert into database.
This is my code so far:
<script type="text/javascript" src="js/jquery-1.7.1.js"></script>
<?php
mysql_connect("localhost","root","");
mysql_select_db("cuba");
if(isset($_POST['hantar']))
{
for($a=1; $a<=count($_POST['name']); $a++)
{
/*$sqlQuery = "REPLACE INTO a (id,name,ic) VALUES ('".$_POST['id'][$a]."','".$_POST['name'][$a]."', '".$_POST['ic'][$a]."')"; */
$sqlQuery = "INSERT INTO a (id,name,ic) VALUES ('".$_POST['id'][$a]."','".$_POST['name'][$a]."', '".$_POST['ic'][$a]."' ) on DUPLICATE KEY UPDATE name='".$_POST['name'][$a]."', ic ='".$_POST['ic'][$a]."'";
mysql_query($sqlQuery)or die(mysql_error());
}
}
?>
<form action="" method="post">
<div class="b">
<?php
$a = 1;
$share = mysql_query("select *from a")or die(mysql_error());
while($share_papar = mysql_fetch_array($share))
{
?>
<table class="bb" style="border:1px solid #003;">
<tr>
<td width="200">Name</td>
<td> : <input type="text" class="input_teks" name="name[]" value="<? php echo $share_papar['name'];?>" />
</td>
</tr>
<tr>
<td>ic</td>
<td> : <input type="text" class="input_teks" name="ic[]" value="<?php echo $share_papar['ic'];?>" /></td>
</tr>
<tr>
<td>id</td>
<td> : <input type="text" class="input_teks" name="id[]" value="<?php echo $share_papar['id'];?>" id="akhir"/></td>
</tr>
<tr>
<td colspan="2" align="right" class="b_buang">Remove</td>
</tr>
</table>
<?php
}?>
</div>
<input type="submit" value="ss" name="hantar">
</form>
<span class="b_tambah">Add new group</span>
<script type="text/javascript">
$(function()
{
//nk clone
$('.b_tambah').on('click',function(e)
{
$(".b").find(".bb").last().clone(true).appendTo(".b");
alert( $(".bb:last").find("input[id=akhir]").last().val());
var m = $(".bb:last").find("input[id=akhir]").last();
m.val("");
});
//nk buang
$(".b_buang").click(function () {
if($('.bb').length < 2)
{
alert("Remove operation can be done if GROUP more than one");
}
else
{
$(this).parents(".bb").remove();
}
});
});
</script>
<!-- close clone Shareholders -->
</td>
I'm using jquery to clone form same with update form, then reset value to blank for input type name (id), so i can have non match id with existing data. But if i submit form without cloning those form, the data will insert into database. What i want is, no need to insert data into database if i dont cloning the new data and just update the existing. How i can achieve that..
Use this code
if(isset($_POST['hantar']))
{
for($a=1; $a<=count($_POST['name']); $a++)
{
$name = $_POST['name'][$a];
$ic = $_POST['ic'][$a];
$name = $_POST['name'][$a];
$sel = mysql_query("select * from a where name = '$name' and ic = '$ic' ");
if(mysql_num_rows($sel) > 0){
//write update query
$fet =mysql_fetch_array($sel);
$auto_increment_id = $fet['id'];
$sqlQuery = " update a set name = '$name' , ic = '$ic' where id = '$auto_increment_id' ";
}
else {
// write insert query
$sqlQuery = "INSERT INTO a (id,name,ic) VALUES ('".$_POST['id'][$a]."','".$_POST['name'][$a]."', '".$_POST['ic'][$a]."' ) ";
}
mysql_query($sqlQuery)or die(mysql_error());
}
}
first check the $_POST['name'] in SELECT query if it is exsits update in the query if not then insert into database
try replacing
for($a=1; $a<=count($_POST['name']); $a++)
to
for($a=0; $a < count($_POST['name']); $a++)
And also check validation
e.g.
if(isset($_POST['name'][$a]) && trim($_POST['name'][$a]) != "")
Finally.. This code save me..
if(isset($_POST['hantar']))
{
for($a=0; $a < count($_POST['name']); $a++)
{
if($_POST['name'][$a]=="")
{
}else
{
if($_POST['id'][$a]=="")
{
$sqlQuery = "INSERT INTO a (name,ic) VALUES ('".$_POST['name'][$a]."', '".$_POST['ic'][$a]."' )";
mysql_query($sqlQuery)or die(mysql_error());
}
else
{
$sqlQuery = " update a set name = '{$_POST['name'][$a]}' , ic = '{$_POST['ic'][$a]}' where id = '{$_POST['id'][$a]}' ";
mysql_query($sqlQuery)or die(mysql_error());
}
}
}
}
<?php
$user_name = "root";
$password = "";
$database = "my_db";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if(isset ($_POST['name']))
{
$name = $_POST['name'];
if(mysql_query("INSERT INTO persons VALUES(' ' , '$name') "))
echo "Successful Insertion!";
else
echo "Please try again!";
}
$result = mysql_query("SELECT * FROM persons");
?>
<html>
<head>
<style type = "text/css">
li { list-style-type: none; display: inline; padding: 10px; text-align: center;}
</style>
</head>
<body>
<form action = " . " method = "POST">
Name: <input type = "text" name = "name"><br>
<input type = "submit" value = "Enter">
</form>
<form name = "delete_form" method = "POST" action = "delete.php" >
<input type = "submit" name = "deleteRecord" value = "Delete Record" />
</form>
<h1>List of Names</h1>
<table border = "1" width = "100%" cellpadding = "5" cellspacing = "2">
<tr>
<td><strong></strong></td>
<td><strong>ID</strong></td>
<td><strong>Company</strong></td>
<td><strong>Edit</strong></td>
<td><strong>Delete</strong></td>
</tr>
<?php while ($row = mysql_fetch_array($result)) { ?>
<tr>
<td><input type="radio" Name="id" value="<?php echo $row['id']; ?>" ></td>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo "<a href = 'edit.php?id=$row[id]'>edit</a>" ?></td>
<td><?php echo "<a href = 'delete.php?id=$row[id]'>delete</a>" ?></td>
</tr>
<?php } ?>
<form name = "edit_form" method = "POST" action = " edit.php?edit= "<?php echo $row['id'] ?> >
<input type = "submit" name = "editRecord" value = "Edit Record" />
</form>
</table>
<?php
while($row = mysql_fetch_array($result))
echo "<li>$row[id]</li> . <li>$row[name]</li> <li> <a href = 'edit.php?edit=$row[id]'>edit</a> </li> <li> <a href = 'delete.php?del=$row[id]'>delete</a></li> <br>";
?>
</body>
</html>
edit.php
<?php
$user_name = "root";
$password = "";
$database = "my_db";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$row = " ";
if (isset($_POST['id']))
{
// if there is an id sent through POST and it isn't null/empty, use that
$id = $_POST['id'];
$SQL = "SELECT * FROM persons WHERE id = '$id' ";
$result = mysql_query($SQL);
$row = mysql_fetch_array($result);
}
else
{
// otherwise use id sent through GET links
$id = $_GET['id'];
$SQL = "SELECT * FROM persons WHERE id = '$id' ";
$result = mysql_query($SQL);
$row = mysql_fetch_array($result);
}
if(isset($_POST['newName']))
{
$id = $_POST['id'];
$newName = $_POST['newName'];
$SQL = "UPDATE persons SET name = '$newName' WHERE id = '$id' ";
$result = mysql_query($SQL) or die("Could not update database" . mysql_error());
echo "<meta http-equiv = 'refresh' content = '0 ; url = index.php'>";
}
?>
<form action = " edit.php" method = "POST">
ID: <input type = "text" name = "id" value = "<?php echo $row[0] ?>"<br><br>
Name: <input type = "text" name = "newName" value = "<?php echo $row[1] ?>"<br><br>
<input type = "submit" value = "Update">
</form>
Hello,
The code above shows how to edit and delete records in a database. Originally, the edit and delete options were in the form of links to a php script which performed the required action. The ID number of the selected row gets passed to the edit or delete php file which then does the action that the user selects (refer to the comments in the code above) I am now trying to modify this code so that I can use a radio button to select a record and then edit or delete the record using radio buttons. I know this sounds trivial but I am having some difficulty with it. Any assistance would be greatly appreciated. Thank you.
Hello Tom. I have made the changes that you suggested but I it still giving the same problem. I have included the edit.php file in case you want to have a look.
The value of your radio buttons needs to contain the ID of the record to be edited.
<td><INPUT TYPE="Radio" Name="radio" value="<?php echo $row['id']; ?>"></td>
Then when you submit the form, you will know the record you are editing has id of value $_POST['radio'].
Though you are already using GET method to pass IDs (through your edit and delete links). I would recommend having consistency, and passing all IDs with parameter id. So
Use this
<td><?php echo "<a href = 'edit.php?id=$row[id]'>edit</a>"; ?></td>
<td><?php echo "<a href = 'delete.php?id=$row[id]'>delete</a>"; ?></td>
And this
<td><input type="radio" name="id" value="<?php echo $row[id]; ?>"></td>
Then in edit.php and delete.php, check to see if an ID was passed through POST (if someone submitted the form) or through GET (they clicked a link), then use whichever has a value.
<?php
if (!empty($_POST['id']))
{
// if there is an id sent through POST and it isn't null/empty, use that
$id = $_POST['id'];
}
else
{
// otherwise use id sent through GET
$id = $_GET['id'];
}
I should also mention that mysql_fetch_array is deprecated and you should be using PDO or MySQLi. Read more here: http://www.php.net/mysql_fetch_array
I have a dynamic HTML table that allows users to enter receipt items in, and they can add as many rows as necessary.
If they forget to fill out a field upon form POST, I want all those rows with the data to stay shown, instead what happens, is they dynamic rows disappear and no values are saved in the one row that shows on default.
How can I achieve having those dynamic table rows shown with the values they've entered to avoid them having to enter all the data again?
<?php
if(isset($saveAdd))
{
$expenseType = safeDataMySQL($_POST['expenseType']);
//Save page, redirect to same page but increment receipt number.
if(empty($_POST['expenseNumber']))
{
//New expense so no records have been created as of yet. Otherwise, this would be stored in hidden field.
$getRef = mysql_query("SELECT CAST(SUBSTRING(refNumber,4) AS UNSIGNED INTEGER) AS referenceNumber FROM expense_main ORDER BY referenceNumber DESC LIMIT 1") or die("Ref No: " . mysql_error());
if(mysql_num_rows($getRef) > 0)
{
while($refData = mysql_fetch_array($getRef))
{
//Expense Number!
$refNumber = $refData['referenceNumber'];
$refNumber = ($refNumber + 1);
}
$ins = mysql_query("INSERT INTO `expense_main` (`respid`, `refNumber`, `dateCreated`, `draftMode`, `expenseType`) VALUES ('".$respid."', 'USA".$refNumber."', NOW(), '1', '".$expenseType."')") or die("Expense Insert: " . mysql_error());
$expClaimNumber = 'USA'.$refNumber;
}
}
else
{
$expClaimNumber = safeDataMySQL($_POST['expenseNumber']);
}
//Get the next receipt in line as well
$getRec = mysql_query("SELECT receiptNumber FROM expense_details ORDER BY receiptNumber DESC LIMIT 1") or die("Get Receipt: " . mysql_error());
if(mysql_num_rows($getRec) > 0)
{
while($recData = mysql_fetch_array($getRec))
{
$receiptNumber = $recData['receiptNumber'];
$receiptNumber = ($receiptNumber + 1);
}
}
$fields = array('recLineDate_', 'recLineCategory_', 'recLineDescr_', 'recLineAmount_');
foreach ($fields as $field)
{
foreach ($_POST[$field] as $key=>$line)
{
$returnArray[$key][$field] = $line;
}
}
foreach ($returnArray as $lineItem)
{
if(empty($lineItem['recLineDate_']))
{
$Errors[] = 'You forgot to enter the receipt date.';
}
else
{
$recDate = safeDataMySQL($lineItem['recLineDate_']);
}
if(empty($lineItem['recLineCategory_']))
{
$Errors[] = 'You forgot to enter a category.';
}
else
{
$recCategory = safeDataMySQL($lineItem['recLineCategory_']);
}
if(empty($lineItem['recLineDescr_']))
{
$Errors[] = 'You forgot to enter a description.';
}
else
{
$recDescr = safeDataMySQL($lineItem['recLineDescr_']);
}
if(empty($lineItem['recLineAmount_']))
{
$Errors[] = 'You forgot to enter your receipt amount.';
}
else
{
$recAmount = safeDataMySQL($lineItem['recLineAmount_']);
}
if(empty($_POST['alternateBranch']))
{
$alternateBranch = '0';
}
else
{
$alternateBrach = $_POST['alternateBranch'];
}
if(!isset($Errors))
{
$recDate = date("Y-m-d", strtotime($recDate));
$ins = mysql_query("INSERT INTO `expense_details` (`receiptNumber`, `claimId`, `alternateBranch`, `dateAdded`, `expenseDate`, `expenseDescription`, `expenseAmount`, `categoryId`)
VALUES ('".$receiptNumber."', '".$expClaimNumber."', '".$alternateBranch."', NOW(), '".$recDate."', '".$recDescr."', '".$recAmount."', '".$recCategory."')") or die("Could not insert receipt: " . mysql_error());
$nextReceipt = ($receiptNumber + 1);
//Redirect to same page, incrementing the receipt number by 1.
header('Location: createExpense.php?expenseNumber='.$expClaimNumber.'&receiptNum='.$nextReceipt);
}
}
}
$expenseNumber = safeData($_GET['expenseNumber']);
$receiptNumber = safeData($_GET['receiptNum']);
if (isset($Errors))
{
echo "<div align='center'><span class='errormessagered'><ul class='errors'>";
foreach ($Errors as $Error)
{
echo "<li>".$Error."</li>";
echo '<br />';
}
echo "</ul></span></div>";
}
?>
<form name="createNew" method="POST" action="">
<div id="row">
<div id="left">
<strong>Receipt Items:</strong>
</div>
<div id="right">
<i>Only add another line to the receipt below IF you have multiple items on one receipt.</i>
<br /><br />
<table border="0" width="825px" cellspacing="0" cellpadding="5" name="receipts" id = "receipts">
<thead>
<tr>
<th class="colheader" width="120px">Date</th>
<th class="colheader" width="120px">Category</th>
<th class="colheader" width="120px">Description</th>
<th class="colheader" width="120px">Amount</th>
<th class="colheader" width="145px"><span class="boldblacklinks">[Add +]</span></th>
</tr>
</thead>
<tbody class="lineBdy">
<tr id="line_1" class="spacer">
<td><input type="text" class="date fieldclasssm" id="recLineDate[]" name="recLineDate_[]" size="10" value = "<?=date("m/d/Y", strtotime($today))?>"/></td>
<td><select name="recLineCategory_[]" class="fieldclasssm">
<option value = "">Select a Category...</option>
<?php //Get Categories
$getCats = mysql_query("SELECT id, nominalName FROM expense_nominalCodes ORDER BY id") or die("Get Cats: " . mysql_error());
if(mysql_num_rows($getCats) > 0)
{
while($catData = mysql_fetch_array($getCats))
{
echo '<option value = "'.$catData['id'].'"'; if($catData['id'] == $_POST['recLineCategory_']) { echo "Selected = 'SELECTED'"; } echo '>'.$catData['nominalName'] . '</option>';
}
}
?>
</select>
</td>
<td><input type="text" class="lineDescr fieldclasssm" name="recLineDescr_[]" id="recLineDescr[]" value = "<?=$_POST['recLineDescr']?>" size="40" /></td>
<td colspan = "2"><input type="text" class="sum lineAmount fieldclasssm" name="recLineAmount_[]" id="recLineAmount[]" value = "<?=$_POST['recLineAmount']?>" size="12" /></td>
</tr>
</tbody>
</table>
</div>
" />
" />
<script type="text/javascript">
$(document).ready(function () {
$('.date').change(function () {
$('.date').val($('.date:nth-of-type(1)').val());
});
});
//Add new table row & clone date field
$('#add').on('click', function(){
addReceiptItem();
$('.date').focus(function() {
$(this).select();
});
$('.receipt').focus(function() {
$(this).select();
});
});
function addReceiptItem(){
var lastID = $('tr[id*="line_"]').length,
newTds = $('tr[id="line_' + lastID + '"] td').clone(),
newRow = document.createElement('tr');
// add new id and class to row, append cloned tds
$(newRow)
.attr('id', 'line_' + (lastID + 1 ))
.attr('class', 'spacer')
.append(newTds);
$(newRow).find('input').not(':eq(0)').val('');
// $(newRow).find('class').not(':eq(0)').not(':eq(0)').val('');
//add the new row to the table body
$('tbody.lineBdy').append(newRow);
$('.receipt').attr('readonly', true);
$('.date').attr('readonly', true);
};
</script>
Just to get you started. You can add the rows from $_POST["rows"]
foreach ($_POST["rows"] as $rowstring) {
list($date, $cat, $desc, $amt) = explode(",", $rowstring)
?>
<td><?php echo $date; ?></td>
<td><?php echo $cat; ?></td>
<td><?php echo $desc; ?></td>
<td><?php echo $amt; ?></td>
<td> </td>
<?php
}
Assuming you add a hidden input with a comma delimited string each time a dynamic row is added.
FWIW, I would also recommend doing all of the database queries (ie $getCats = ...) prior to rendering anything to the screen so that in case the 'or die()' happens, you wont get a half rendered page.
I create inputs using the information in the columns for example if a field is called about_content it outputs a label of About Content with an input field. This works fine for inserting however I want to use this code similarly to UPDATE and I want to display to users the current value of a field as entered in the database. For example if about_content = Hello World! I want the input value to reflect that. Is there a way of doing this dynamically?
<?php
require('dbc.php');
mysql_select_db($db);
$resultInput = mysql_query("SHOW COLUMNS FROM about WHERE Field NOT IN
('id', 'created', 'date_modified', 'last_modified', 'update', 'type', 'bodytext')
AND Field NOT REGEXP '_image'"); // selects only the columns I want
$result = mysql_query("SELECT * FROM about WHERE id=".$_GET['id']); // values I want to put into the values for <input>
while ($row = mysql_fetch_assoc ($result) && $column = mysql_num_rows ($resultInput)) {
foreach($row as $column => $value){
echo '<label>'.$column.'<input name="'.$column.'" type="input" value="'.$value.'"></label><br>';
}
}
?>
See the spot you've marked with an arrow? Instead of the string (1), set value to the appropriate database value you read in $result (not in $resultInput).
Here's how: use mysql_fetch_assoc for your SELECT query, not mysql_fetch_row. There will be only one row, so fetch it before you start generating the form. You'll then have a named array with the row values, and you can grab each field by name and put it in the form.
If you don't understand how to do that, check the php documentation for mysql_fetch_assoc.
And escape your $_GET['id'] like you were told in your last question. You're begging to be pwned!
See mysql_fetch_field.
if (mysql_num_rows($result) > 0) {
//loop creates inputs
//make $resultInput object to array.
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$meta = mysql_fetch_field($result, $i);
if(in_array($meta->name, $resultInput )){
echo '<div class="wrapper"><label>' . ucfirst(str_replace('_', ' ',$meta->name)) .
'<br><input name="' . $meta->name .
'" type="text" class="input" value="$row[$meta->name]"><br></label></div>';
}
$i++;
}
}
<?php
include('db.php');
if (isset($_POST['btn'])) {
$dcolumn = $_POST['dyncolumns'];
$dvalue = $_POST['dynfields'];
$name = $_POST['name'];
$mobile = $_POST['mobile'];
$address = $_POST['address'];
$query = "INSERT into addtable(name,mobile,address)VALUES('" . $name . "','" . $mobile . "','" . $address . "')";
$result = mysql_query($query)or die(mysql_error());
$id = mysql_insert_id();
if ($dcolumn) {
foreach ($dcolumn as $key => $value) {
$result1 = "show COLUMNS from addtable like '.$value.'";
$exists = mysql_query($result1)or die(mysql_error());
$data = mysql_fetch_assoc($exists);
if ($data==TRUE) {
$query = "update addtable set $value = '" . $dvalue[$key] . "' where id=$id";
} else {
$query1 = "ALTER TABLE addtable ADD $value varchar(45)";
$result2 = mysql_query($query1)or die(mysql_error());
$query = "update addtable set $value = '" . $dvalue[$key] . "' where id=$id";
$result = mysql_query($query)or die(mysql_error());
}
}
}
}
?>
<script>
function myFunction() {
var table = document.getElementById("insert");
var row = table.insertRow(3);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "<input type='text' name='dyncolumns[]'>";
cell2.innerHTML = "<input type='text' name='dynfields[]' >";
}
</script>
<html>
<body>
<form name="insert" method="post">
<table border="2" align="center" id="insert">
<tr>
<td>Name</td><td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Mobile</td><td><input type="text" name="mobile" maxlength="10"/></td>
</tr>
<tr>
<td>Address</td><td><input type="text" name="address" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="btn" value="submit"></td>
</tr>
</table>
<input type="button" onclick="myFunction()" name="add" value="Add">
Logout
</form>
</body>
</html>