Storing data in mysql using two dimensional array - php

Here is the form that collects employer's history and stores that data into 2d array, then I am trying to store that info into mysql database in a table employment. It gives me no error but it can't store data into mysql ..
form1.php
<form action="result.php" method="post">
<table width="676" border="0" cellspacing="0" cellpadding="7" align="center">
<tr><td colspan="6" bgcolor="#C0C0C0">EMPLOYMENT HISTORY</td></tr>
<?php
for ($x=0; $x<2; $x++)
{
?>
<tr>
<td colspan="3" align="left">NAME OF EMPLOYER<br>
<input type="text" name="emp[emp_name][]" size="38"></td>
<td align="left">JOB TITLE <br>
<input type="text" name="emp[emp_title][]" size="32"></td>
</tr>
<tr>
<td colspan="5" valign="top">ADDRESS<br>
<input type="text" name="emp[emp_addr][]" size="58"></td>
</tr>
<tr>
<td colspan="2" valign="top">REASON FOR LEAVING<br>
<textarea name="emp[emp_reason][]" cols="25" rows="3"></textarea></td>
</tr>
<tr>
<td align="left">DATE STARTED<br>
<input type="text" name="emp[emp_start][]" size="8"></td>
<td align="left">DATE ENDED<br>
<input type="text" name="emp[emp_end][]" size="8"></td>
<td colspan="2" align="left">TYPE OF BUSINESS<br>
<input type="text" name="emp[emp_btype][]" size="15"></td>
</tr>
<tr><td colspan="6" bgcolor="#C0C0C0"> </td></tr>
<?php } ?>
</table>
<input type="submit" name="submit" value="SUBMIT"> <input type="reset" value="RESET">
</form>
here is the result.php
<?php
// open connection to the database
mysql_connect('localhost', 'user', 'pass');
mysql_select_db('userdb');
// get all the values
$app_id = 5;
$app_emp = array($emp => array(
$emp_name => $_POST["emp_name"],
$emp_title => $_POST["emp_title"],
$emp_addr => $_POST["emp_addr"],
$emp_reason => $_POST["emp_reason"],
$emp_start => $_POST["emp_start"],
$emp_end => $_POST["emp_end"],
$emp_btype => $_POST["emp_btype"]
));
// set up error list array
$errorList = array();
$count = 0;
// validate
// making sure that they are filling in all the required fields for the employer for each of the 3 "boxes"
for ($x=0; $x<sizeof($app_emp); $x++)
{
if(!empty($emp_name[$x]) || !empty($emp_start[$x]) || !empty($emp_end[$x]))
{
if(empty($emp_start[$x]) || empty($emp_end[$x]))
{
$errorList[$count] = "Invalid entry: Employment History, item " . ($x+1);
$count++;
}
}
}
// if no errors
if (sizeof($errorList) == 0)
{
// insert employment history
for($i=0; $i<sizeof($emp_name); $i++)
{
$x = 0;
if (!empty($emp_name[$i][$x]) && !empty($emp_start[$i][$x]) && !empty($emp_end[$i][$x]))
{
$query = "INSERT INTO `employment` (`app_id`,`name`,`title`,`addr`,`reason`,`start`,`end`,`bustype`) VALUES ('$app_id', '$emp_name[$x]', '$emp_title[$x]', '$emp_addr[$x]','$emp_reason[$x]', '$emp_start[$x]', '$emp_end[$x]', '$emp_btype[$x]')" or die(mysql_error());
$result = mysql_query($query, $conn) or die ("Error in query: $query. " . mysql_error());
}
}
// If it gets processed, print success code
echo "Your information has been accepted.";
}
else
{
?>
<table width="676" border="0" cellspacing="0" cellpadding="8" align="center">
<tr><td>
<?php
// or list errors
listErrors();
?>
</span></td>
</tr>
</table>
<?
}
?>
<?php
// print out the array
echo '<pre>';
print_r($_POST);
echo '</pre>';
?>

I know you have found a solution. Just incase someone found this and get curious :)
There are couple of issues with the logic
For start under this line:
// get all the values
$emp will be empty '' all the time as it is not initialised and if you initialise the entire logic will shatter.
Also the $_POST you have mentioned will always be empty. You need to address it from them Master (Level1) Just var_dump($_POST) and you see what I mean :)
So do something like this: (I must stress this is not a good approach but just to shed some light on this question)
var_dump($_POST['emp']); // This is master array that holds everything
$app_emp = array();
foreach ($_POST['emp'] as $key => $val) {
$app_emp[0][$key] = mysql_real_escape_string($val[0]);
$app_emp[1][$key] = mysql_real_escape_string($val[1]);
}
// set up error list array
$errorList = array();
$count = 0;
var_dump($app_emp);
Now in the $app_emp you have got 2 separate arrays that you can go through, validate and add them to DB. Of-course the current SQL is not going to work as you need to wiggle it to fit the new array. Rest should be easy.
Couple Of handy note:
I am sure you are cleaning up your form submit mysql_real_escape for
all the vars.
Also try to use redirection after successful submit,
as users will intend to refresh the page. Otherwise user is going to
get ugly do you want to resubmit the data.
Make sure you pass a token to the result page, and check it there. I would use a random DB number so stop the Cross Browser hacks.
Hope this help. H.

Related

How to process data in a form using php without submitting it

When I enter a video ID and the length of loan and then hit button FindDetails my form will show the name of the video, it's price to hire and the total cost of hire.
This causes two problems:
Submitting the form wipes video ID and the length of loan. Rats!
I cant adjust how many days I want to borrow a video and watch
the cost of the loan automatically adjust.
NB I include all php script as I will actually need to submit the form to write details of the reservation in a csv file. I'm not sure if this will stop a work around solution.
PHP:
<?php
if (isset($_POST['FindDetails'])) {
$ID = $_POST['videoID'];
$Days = $_POST['days'];
//Open the CSV file
$file_handle = fopen("video.csv", "r");
//loop until hit the last line feof)
while (!feof($file_handle))
{
//put data in each line [0],[1] etc into a variable.
$info = fgetcsv($file_handle);
// Check its the one we want.
if($info[0]==$_POST["videoID"])
{
$videoName = "$info[2]";
$videoCost ="$info[4]";
$costOfHire= $videoCost*$Days;
}
}
fclose($file_handle);
}
if (isset($_POST['submit'])) {
$ID = $_POST['videoID'];
$VideoName = $_POST['videoName'];
$VideoCost = $_POST['videoCost'];
$Days = $_POST['days'];
$Total = $_POST['total'];
$DateFrom = $_POST['date_from'];
$DateTo = $_POST['date_to'];
$StudentName = $_POST['studentName'];
//Saving loan details
$csv_file = 'loans.csv';
if (is_writable($csv_file)) {
if (!$csv_handle = fopen($csv_file,'a')) {
// this line is for troubleshooting
echo "<p>Cannot open file $csv_file</p>";
exit;
}
$csv_item = "\"$ID\",\"$VideoName\",\"$VideoCost\",\"$Days\",\"$Total\",\"$DateFrom\",\"$DateTo\",\"$StudentName\"\n";
if (is_writable($csv_file)) {
if (fwrite($csv_handle, $csv_item) === FALSE) {
//for testing
//echo "Cannot write to file";
exit; }
}
fclose($csv_handle);
}
}
if (isset($_POST['submit'])) {
echo "<p style='padding: .5em; border: 2px solid red;'>Thanks for booking the Video. Please collect from E24 on the date ordered.</p>";
}
?>
HTML:
Loans
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Enter the Video ID below
<table id="tables" class="form" style="width:100%;">
<tr>
<td>Video ID</td>
<td><input type="text" value="" name="videoID" id="videoID" placeholder= "Enter A Number between 1 and 8"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="FindDetails" id="FindDetails" value="Search Video" /></td>
</tr>
<tr>
<td>Video Name</td>
<td><input type="text" value="<?php echo (isset($videoName))?$videoName:'';?>" name="videoName" id="videoName"/></td>
</tr>
<tr>
<td>Video Rental Cost (per day)</td>
<td><input type="text" value="<?php echo (isset($videoCost))?$videoCost:'';?>" name="videoCost" id="videoCost"/></td>
</tr>
<tr><td></td><td></td></tr>
<tr>
<td>Number of days</td>
<td><input type="text" value="" name="days" id="days" placeholder= "Enter the number of days you wish to borrow the video for" /></td>
</tr>
<tr>
<td>Total cost</td>
<td><input type="text" value="<?php echo (isset($costOfHire))?$costOfHire:'';?>" name="total" id="total"/></td>
</tr>
Part 1
I assume the HTML and PHP portions presented are in the same file.
You use <?php echo (isset($costOfHire))?$costOfHire:'';?> for example to access variables set in the PHP code.
Why not use <?php echo (isset($ID))?$ID:'';?> to simply recycle the submitted video ID? Then do the same for the length of loan variable.
Part 2
Here is one way live loan cost calculation could work. The javascript will go between <script></script> tags in the <head> of the document.
function updateLoanCost(loanPeriod) {
var costDisplayEl = document.getElementById("loanCostDisplay");
var dollarsPerDay = 3;
costDisplayEl.innerText = "$" + loanPeriod * dollarsPerDay;
}
Enter a number of days <br />
<input type = "number" id = "test" onchange = "updateLoanCost(this.value);"/>
<div id = "loanCostDisplay"></div>

PHP login script isnt working, passes variables back to page then does nothing

I'm learning PHP and am having issues getting the following code to work properly. Basically the login page displays correctly, and without errors and the variables appear to be assigned correctly, but upon page reload I just get the same login form, it appears the data has either not been passed and is therefore not being acted upon.
I've looked at the code over and over again and even tried a different method (produced same result!) so it'd be lovely if someone helpful could spend a minute and point me in the right direction.
One thing that might be an issue is my server is running 5.3.9 and the book I'm working from is PHP5 so maybe some of the function I'm calling have been deprecated. Which would be a pain...
<?php
include_once "common_db.inc";
$register_script = "register.php";
if (!isset ($userid)) {
login_form();
exit;
} else {
session_start();
session_register ("userid", "userpassword");
$username = auth_user ($_POST['userid'], $_POST['userpassword']);
if (!$username) {
$PHP_SELF = $_SERVER['PHP_SELF'];
session_unregister ("userid");
session_unregister ("userpassword");
echo "Failed to authorize. " .
"Enter a valid DX number and password." .
"Click the link below to try again.<br>\n";
echo "login<br>";
echo "Click the following link to register<br>\n";
echo "Register";
exit;
} else {
echo "Welcome, $username!";
}
}
function login_form()
{
global $PHP_SELF;
?>
<form method="post" action="<?php echo "$PHP_SELF"; ?>">
<div align="center"><center>
<h3>Please login to use the page you requested</h3>
<table width="200" cellpadding="5">
<tr>
<th width="18%" align="right" nowrap>id</th>
<td width="82%" nowrap>
<input type="text" name="userid" />
</td>
</tr>
<tr>
<th width="18%" align="right" nowrap>password</th>
<td width="82%" nowrap>
<input type="password" name="userpassword" />
</td>
</tr>
<tr>
<td colspan="2" width="100%" nowrap>
<input type="submit" value="login" name="Submit" />
</td>
</tr>
</table>
</center>
</div>
</form>
<?php
}
function auth_user($userid, $userpassword)
{
global $dbname, $user_tablename;
$link_id = db_connect($dbname);
$query = "SELECT DXNumber FROM $user_tablename WHERE DXNumber = '$userid'
AND userpassword = password ('$userpassword')";
$result = mysql_query ($query);
if (!mysql_num_rows($result)){
return 0;
}else{
$query_data = mysql_fetch_row($results);
return $query_data[0];
}
}
?>
You're not defining $userid or checking if the form has been submitted. Try:
if (!isset($_POST['userid'])) {
Your query in your auth_user function needs to look like this:
$query = "SELECT DXNumber FROM $user_tablename WHERE DXNumber = '$userid' AND userpassword ='" . $userpassword."'";
Also, you're open to sql injection. You should look into using PDO and prevent it.
try
if (!isset $_POST['userid']) {
and see if that helps. It looks like $userid is not being set before you branch.
(edited because of stupid spelling checker.)

How to insert data in database using php

I have just started to work with php. I write a simple code in php to insert data in a table customer. I am using mssql database.
<?php
function InsertData()
{
$link = mssql_connect('db','123','test');
if (!$link || !mssql_select_db('php', $link))
{
die('Unable to connect or select database!');
}
$sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
$result = mysql_query($sql, $link);
if(!$result)
{
echo mysql_error();
exit;
}
// close the connection
mysql_free_result($result);
mysql_close();
echo "Data successfully inserted";
}
?>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td colspan="3" height="10" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%"> Name:</td>
<td width="60%"><INPUT type="text" name="txtName" id="txtName" Width="200px" MaxLength="30" /> </td>
</tr>
<tr>
<td colspan="3" height="12" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%"> Company Website:</td>
<td width="60%"><INPUT type="text" name="txtWebsite" id="txtWebsite" width="200px" MaxLength="200" /> </td>
</tr>
<tr>
<td > </td>
<td > <input type="button" value="submit" id="imgBtnSubmit" click="InsertData()"/> </td>
</tr>
</table>
I have written above code to insert data into the table and I am calling InsertData function on onClick event of submit button but on clicking button data is not getting inserted into the table. Please anyone tell me where is the problem in this code.
There are a few problems with your code.
You're missing the <form> as pointed out by Tudor Constantin.
The other problem is that you can't use the onclick event of an element to trigger PHP code as you're done above. The onclick event is for JavaScript (or other client side scripting languages like VBScript).
Additionally, make sure that you use the functions that start with mssql and not mysql if you use Microsoft SQL Server. The functions are not interchangeable.
Here's a short example:
<?php
// The request method is POST.
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
// Connect to the database
$link = mssql_connect('db','123','test');
// Do more stuff with the database.
}
?>
<form method="POST" action="/path/to/this/file.php">
<input type="text" name="example" />
<input type="submit" value="Send" />
</form>
When you click the "Send" button, the form will be POSTed to /path/to/this/file.php. By checking that the request method is "POST", you can then connect to the database and insert records accordingly.
Checking for $_SERVER['REQUEST_METHOD'] is one of many ways you can do this. You could also check that a value for an particular input was set using if ( ! empty($_REQUEST['input_name']) ) { ... }.
As the previous answer states, you don't actually have submission logic. What's at least equally important is that you, by your own admission, do not have a MySQL server. MySQL and MS-SQL are different and not at all equivalent. You can't use PHP MySQL commands or the MySQL extension to talk to MS-SQL.
You're using MS-SQL functions here:
$link = mssql_connect('db','123','test');
if (!$link || !mssql_select_db('php', $link))
{
die('Unable to connect or select database!');
}
and then MySQL here:
$sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
$result = mysql_query($sql, $link);
if(!$result)
{
echo mysql_error();
exit;
}
// close the connection
mysql_free_result($result);
mysql_close();
echo "Data successfully inserted";
...and, as yet another answer states, you're trying to use Javascript to call a PHP function.
You therefore have two three problems - well, technically one problem. I suggest you read a FAQ on MS-SQL in PHP at the very least, and ideally complete Javascript and PHP tutorials. There is no way that we can provide an answer that you can use short of writing your program for you, as you - and I swear I'm not being unpleasant here, I know you're doing your best - just don't have the knowhow to put it together yet. Google is your friend here. Good luck.
As many have already mentioned there are a few errors in your code. My solution to your question offers a different approach.
Rather than calling the InsertData() method you can do something else in the one php document.
This is done by using an if/else statement, assigning 'submit' to the name value of the submit button as well as the special PHP variable $_SERVER['PHP_SELF'].
First, the server checks if the form has been submitted.
When the page is first loaded this will return false and the form is displayed for them to fill out
When the user clicks the submit button the form reloads the page and runs the PHP script again. This time the if statement returns true as the form HAS been submitted so it executes the part of the script that inserts the data in MSSQL and displays the successful message.
Check out the code below:
<?php
if (isset($_POST['submit'])){
//connect to the database
$link = mssql_connect('db','123','test');
//display error if database cannot be accessed
if (!$link || !mssql_select_db('php', $link))
{
die('Unable to connect or select database!');
}
//assign form input to variables
$txtName = $_POST['txtName'];
$txtWebsite = $_POST['txtWebsite'];
//SQL query to insert variables above into table
$sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
$result = mssql_query($sql, $link);
//if the query cant be executed
if(!$result)
{
echo mssql_error();
exit;
}
// close the connection
mssql_free_result($result);
mssql_close();
echo "Data successfully inserted";
}
else { ?>
<form name="input" action="$_SERVER['PHP_SELF']" method="POST">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td colspan="3" height="10" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%">Name:</td>
<td width="60%"><INPUT type="text" name="txtName" id="txtName" Width="200px" MaxLength="30" /> </td>
</tr>
<tr>
<td>Company Website:</td>
<td><INPUT type="text" name="txtWebsite" id="txtWebsite" width="200px" MaxLength="200" /></td>
</tr>
<tr>
<td><input type="button" name="submit" value="submit" /></td>
</tr>
</table>
</form>
<?php } ?>
Give that a try. There's some great PHP tutorials that go over the fundamentals here:
http://devzone.zend.com/article/627
Hope that all helped.
It looks like you don't have a <form> in your page - the data is not getting to your server.
Also, you are not reading the input anywhere - how do you fill your $txtName and $txtWebsite with meaningful values?
Also, InsertData is a PHP function, which is executed on the server side - your HTML part is interpreted on the client side (in the browser). You can't call that function there.
Try with this:
<?php
function InsertData()
{
$link = mssql_connect('db','123','test');
if (!$link || !mssql_select_db('php', $link))
{
die('Unable to connect or select database!');
}
$txtName = $_REQUEST['txtName'];
$txtWebsite = $_REQUEST['txtWebsite'];
$sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
$result = mssql_query($sql, $link);
if(!$result)
{
echo mssql_error();
exit;
}
// close the connection
mssql_free_result($result);
mssql_close();
echo "Data successfully inserted";
}
if ($_REQUEST['txtName'] > ''){
InsertData();
}
?>
<form name="input" action="this_file_name.php" method="get">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td colspan="3" height="10" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%"> Name:</td>
<td width="60%"><INPUT type="text" name="txtName" id="txtName" Width="200px" MaxLength="30" /> </td>
</tr>
<tr>
<td colspan="3" height="12" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%"> Company Website:</td>
<td width="60%"><INPUT type="text" name="txtWebsite" id="txtWebsite" width="200px" MaxLength="200" /> </td>
</tr>
<tr>
<td > </td>
<td > <input type="button" value="submit" id="imgBtnSubmit" /> </td>
</tr>
</table>
</form>

get data from dynamically created html table for certain columns

my current problem is :
I have a HTML table created "dynamically" according to how many rows brings back a mysql_query. The first column gets tha data from the query and the second column have a text field (see below):
<?php
$selApart = "SELECT idAPARTMENT FROM BUILDING, APARTMENT WHERE APARTMENT.BUILDING_ID = BUILDING.idBUILDING AND idBUILDING = '$building'";
$res = mysql_query($selApart) or die("Could not execute query.");
?>
<table width="244" border="0" cellspacing="0" id="hours_table">
<tr>
<td width="121">APARTMENT</td>
<td width="119">HOURS</td>
</tr>
<?php
$rcnt = 0;
while($r = mysql_fetch_array($res)){
$a = $r['idAPARTMENT'];
$rcnt++;
$rid = 'row'.$rcnt;
?>
<tr>
<td>'<?php echo $a?>'</td>
<td id='<?php echo $rid?>'><input type="text" name="hours" id="hours" value="0"/></td>
</tr>
<?php } ?>
<input type="submit" name="complete" id="complete" align="middle" value="INSERT"/>
After my table is "ready", I want to fill in my text fields and insert these values in an sql table. What I don't know is how I can get the value of each column through the id I set, sth like
if(isset($_POST['complete'])){
for($i=0; $i<$rcnt; $i++){
//INSERT INTO APARTMENT (idAPARTMENT, HOURS) VALUES ($a, **table.row.id**)
}
}
Can someone help? Is this possible to be done?
Thanks in advance!
He, thing you have to do is add $rid as name to text box, then just submit form and you will have them in $_POST["row"+$rid];
You can loop through every $_POST and if variable starts with row + num save it in db
foreach($_POST as $key => $value)
//if $key starts with row execute your db save
I hope this helps
Put that table into a form with method=POST and when submitting you'll find all input's in the $_POST array by name.
<?php
print_r($_POST);//this will just show you the contents of the array, you play with it later on
$selApart = "SELECT idAPARTMENT FROM BUILDING, APARTMENT WHERE APARTMENT.BUILDING_ID = BUILDING.idBUILDING AND idBUILDING = '$building'";
$res = mysql_query($selApart) or die("Could not execute query.");
?>
<form action="" method="POST"><!-- table must be included in a form with action pointing the script location, "" means itself -->
<table width="244" border="0" cellspacing="0" id="hours_table">
<tr>
<td width="121">APARTMENT</td>
<td width="119">HOURS</td>
</tr>
<?php
$rcnt = 0;
while($r = mysql_fetch_array($res)){
$a = $r['idAPARTMENT'];
$rcnt++;
$rid = 'row'.$rcnt;
?>
<tr>
<td>'<?php echo $a?>'</td>
<td id='<?php echo $rid?>'><input type="text" name="hours<?= $a ?>" id="hours" value="0"/></td><!-- name="hourse<?= $a ?>" each name must be unique, that's why you include the ID from your table. It's not a good idea to put a counter, use actual data from the table. -->
</tr>
<?php } ?>
</table>
<input type="submit" name="complete" id="complete" align="middle" value="INSERT"/>
</form>
The post "get data from dynamically created html table for certain columns" was very useful. It helped me a lot, but needs a little change:
<?php
//database connectivity
mysql_connect ("localhost","root","","sis")or die("cannot connect");
mysql_select_db("sis")or die("cannot select DB");
//query to fetch data
$sql1="select * from student";
$result1= mysql_query($sql1);
// forming table to view data
if($result1){
echo "<table cellspacing='1' cellpadding='5'>
<th width='30%'>Roll_No </th>
<th width='40%'>Name </th>
<th width='30%'>Sem & Sec </th>";
while($row=mysql_fetch_array($result1)){
$Roll_No=$row['Roll_No'];
$Name=$row['Name'];
$Sem_Sec=$row['Sem_Sec'];
echo"<tr>
<td>$Roll_No</td>
<td>$Name</td>
<td>$Sem_Sec</td>
</tr>";
}
?>

MySQL, PHP - Forms Help

Greetings,
I have the following code
<?
include("conn.php");
$sn=$_GET["sn"];
$sql="select * from kpi where no='$sn'";
$result=mysql_query($sql,$connection) or die(mysql_error());
while($row=mysql_fetch_array($result)) {
$sn=$row['id'];
$no=$row['no'];
$pdetails=$row['pdetails'];
$kpistatus=$row['kpistatus'];
$status=$row['status'];
$cols=$row['cols'];
$rows=$row['rows'];
}
?>
<form name="form1" method="post" action="formsubmit.php?mode=addtable">
<table width="100%" border="1" align="center" cellpadding="2" cellspacing="2">
<tr>
<td colspan="2"><strong>Add Table</strong></td>
</td>
</tr>
<tr>
<td>NO</td>
<td><input name="no" type="text" id="no" value="<? echo $no; ?>"></td>
</tr>
<tr>
<td>PROJECT DETAILS</td>
<td><textarea name="pdetails" rows="10" cols="100"><? echo $pdetails; ?></textarea></td>
</tr>
<tr>
<td>KPISTATUS</td>
<td>
<?
echo "<table border=\"1\" align=\"left\">\n";
$j=0;
while ($j < $rows)
{
echo "<tr>\n";
$i=0;
while ($i < $cols)
{
?>
<td><input type="text" name="kpistatus" id="kpistatus"></td>
<?
$i++;
}
echo "</tr>\n";
$j++;
}
echo "</table>\n";
?>
</td>
</tr>
<tr>
<td>STATUS</td>
<td><textarea name="status" rows="10" cols="100"><? echo $status; ?></textarea></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="Submit" value="ADD TABLE"></td>
</tr>
</table>
</form>
elseif($mode=="addtable") {
$no=$_POST["no"];
$pdetails=$_POST["pdetails"];
$kpistatus=$_POST["kpistatus"];
$status=$_POST["status"];
$sn=$_POST["id"];
$sql="update kpi set pdetails='$pdetails',kpistatus='$kpistatus',status='$status' where no='$no'";
//echo $sql;
$result=mysql_query($sql,$connection) or die(mysql_error());
//header("location: index.php");
}
?>
Screenshot of the form :
http://img395.imageshack.us/my.php?image=1226818203913yi6.png
Users can input how many rows and column they need to insert data. In screenshot my rows is 10 whereas column is 5.
Now the part where i stuck is, how can i make sure, all inputted data in
< input type="text" name="kpistatus" id="kpistatus"> get saved in kpistatus mysql table..
Please help me.
Thanks.
If you put square brackets in an input name, php will automatically turn them into an array for you in the post array. Then you can just iterate through that and save them as needed. In your form, you would put
<input type="text" name="kpistatus[]" id="kpistatus">
(Note the addition of the two brackets).
Then, in your form handling code, you would have $_POST['kpistatus'] as an array. You could use PHP's implode function to turn this into a comma-seperated list by doing something like implode(',', $_POST['kpistatus'].
A quick note:
In your code, you need to use mysql_real_escape_string on all of your variables before you insert them. Otherwise, a user could enter SQL code into one of the inputs and be able to do whatever they wanted (this is called SQL injection).
Imagine what would happen if someone had a single-quote in their status string. At best it would cause an error, at worst they could overwrite or erase your data.
Sorry if this is obvious to you, but I just want to make sure to cover it.

Categories