How to insert data in database using php - 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>

Related

MySQL table page not loading correct data

I'm creating a table that uses PHP to pull from a MySQL database that I have. I think I've got everything where I want it to be, however the only problem I'm having is that the results seem to be (for lack of a better word) "behind". What I mean by that is that my first page index.php is where I'm accepting user edits to the database. Once they click Update it sends them to my results.php file that is supposed to actually perform the SQL UPDATE and then display the updated table.
It updates the table just fine according to XAMPP's database editor. However, when I said "behind" I mean that the page loads, updates but doesn't display the updated data until either the user refreshes the page or returns to the first page THEN comes back. I'm not sure what could be causing it, so I'm hoping someone here can help me. I feel like the reason is something as simple as I'm just running the code in the wrong order, but I don't know for sure. My code is below:
index.php
<html>
<body>
<?php
include('dbconnect.php');
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
?>
<form name="form1" method="post" action="results.php">
<table width="auto" border="1" cellspacing="1" cellpadding="5">
<tr>
<td align="center"><strong>Event ID</strong></td>
<td align="center"><strong>Title</strong></td>
<td align="center"><strong>Topic</strong></td>
<td align="center"><strong>Description</strong></td>
<td align="center"><strong>Event Date</strong></td>
<td align="center"><strong>Speaker</strong></td>
<td align="center"><strong>Building</strong></td>
<td align="center"><strong>Room</strong></td>
</tr>
<?php
while($rows=mysqli_fetch_array($result)) {
?>
<tr>
<input name="event_id[]" type="hidden" id="event_id" value="<?php echo $rows['event_id']; ?>">
<td align="center">
<?php echo $rows['event_id'];?>
</td>
<td align="center">
<input name="title[]" type="text" id="title">
</td>
<td align="center">
<?php echo $rows['topic_name']; ?>
</td>
<td align="center">
<?php echo $rows['topic_description']; ?>
</td>
<td align="center">
<input name="date[]" type="date" id="date">
</td>
<td align="center">
<input title="Use reference tables below to enter speaker ID" name="speaker[]" type="text" id="speaker">
</td>
<td align="center">
<input title="Use reference tables below to enter building ID" name="building[]" type="text" id="building">
</td>
<td align="center">
<input title="Use reference tables below to enter Room ID" name="room[]" type="text" id="room">
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="8" align="center"><input type="submit" name="Update" value="UPDATE"></td>
</tr>
</table>
</form>
</body>
</html>
results.php
<html>
<body>
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors',1);
require_once('dbconnect.php');
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$id = $_POST['event_id'];
$title2 = $_POST['title'];
$date2 = $_POST['date'];
$speaker2 = $_POST['speaker'];
$building2 = $_POST['building'];
$room2 = $_POST['room'];
for($i=0;$i<$count;$i++) {
$sql="UPDATE events SET title='$title2[$i]', event_date='$date2[$i]', speaker='$speaker2[$i]', building='$building2[$i]', room='$room2[$i]' WHERE event_id='$id[$i]'";
$result1=mysqli_query($conn, $sql);
}
}
?>
<form name="form1" method="post" action="index.php">
<table width="auto" border="1" cellspacing="1" cellpadding="5">
<tr>
<td align="center"><strong>Event ID</strong></td>
<td align="center"><strong>Title</strong></td>
<td align="center"><strong>Topic</strong></td>
<td align="center"><strong>Description</strong></td>
<td align="center"><strong>Event Date</strong></td>
<td align="center"><strong>Speaker</strong></td>
<td align="center"><strong>Building</strong></td>
<td align="center"><strong>Room</strong></td>
</tr>
<?php
while($rows=mysqli_fetch_array($result)) {
?>
<tr>
<td align="center">
<?php echo $rows['event_id'];?>
</td>
<td align="center">
<?php echo $rows['title']; ?>
</td>
<td align="center">
<?php echo $rows['topic_name']; ?>
</td>
<td align="center">
<?php echo $rows['topic_description']; ?>
</td>
<td align="center">
<?php echo $rows['event_date']; ?>
</td>
<td align="center">
<?php echo $rows['speaker_name']; ?>
</td>
<td align="center">
<?php echo $rows['building_name']; ?>
</td>
<td align="center">
<?php echo $rows['room_name']; ?>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="8" align="center"><input type="submit" name="Return" value="Return"></td>
</tr>
</table>
</form>
</body>
</html>
Also if someone can give me some guidance as to how to run the htmlspecialchars function on my arrays within results.php I'd really appreciate it. I've already tried to create a for loop for literally each array but that didn't work. I've tried using ->
<?php
function htmlspecial_array(&$variable) {
foreach ($variable as &$value) {
if (!is_array($value)) { $value = htmlspecialchars($value); }
else { htmlspecial_array($value); }
}
}
but that also didn't work, and I've tried using the array_walk_recursive but to no avail. I want to try and do something like W3Schools' example here W3Schools Form Validation towards the bottom of the page where it says Validate Form Data With PHP and then gives an example.
The result you get from the UPDATE query is the number of affected rows in your database. To correctly display the updated data, you need to re-fetch from the database before you generate the HTML. You should rearrange your code in results.php like this:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors',1);
require_once('dbconnect.php');
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$id = $_POST['event_id'];
$title2 = $_POST['title'];
$date2 = $_POST['date'];
$speaker2 = $_POST['speaker'];
$building2 = $_POST['building'];
$room2 = $_POST['room'];
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
for($i=0;$i<$count;$i++) {
$sql="UPDATE events SET title='$title2[$i]', event_date='$date2[$i]', speaker='$speaker2[$i]', building='$building2[$i]', room='$room2[$i]' WHERE event_id='$id[$i]'";
$result1=mysqli_query($conn, $sql);
}
}
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
Side note: If your data is sensitive, you may want to read about mysqli prepared statement so hackers cannot tamper with your queries.
Regarding your question about htmlspecialchars, see Stackoverflow "Execute htmlspecialchars on a multi level array".

inserting values in to database only once

<?php if(isset($_POST['submit']))
{
$tadd=$_POST["tadd"]; //getting values
$pname=$_POST["pname"];
$date=$_POST["date"];
$result=mysql_query("insert into pannel(tadd,pname,date)values('$tadd','$pname','$date')");
echo "<script type='text/javascript'>
alert('Quotation Generated Successfully!')
</script>";
} ?>
<center>
<h1>Title</h1>
</center>
<form name="form" method="post" action="" onSubmit="submit;">
<center><table border="0" cellspacing="0" style="width:350px">
<tr> <td><b>To Address</td> <td><textarea name="tadd" rows="5"
cols="30"></textarea></td></tr>
<tr> <td><b>Project Name</td> <td><input type="text" name="pname" required></td></tr>
<tr> <td><b>Date</td> <td><input type="text" name="date"
id="datepicker" required></td></tr>
<tr> <td colspan="2" align="center"><input type="submit" name="submit"
value="submit"/></td> </tr></center> </table> </form>
I have one record in my database with
id tadd pname date
1 hello vvv 22/10/2014
if i insert values into database again it should data already inserted
please help me regarding this issue
You can achieve this using mysql_num_rows() which is one way to do this, which I believe the goal is to avoid duplicates.
Sidenote: You can also set your column(s) as UNIQUE to avoid duplicates.
N.B.: I used the pname column as an example. It's up to you to check which one will always be unique in regards to a username for instance.
$query = "SELECT * FROM pannel where pname = '".$pname."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
echo "Already exists.";
}
else{
mysql_query("insert into pannel (tadd, pname,date) values ('$tadd','$pname','$date')");
}
Do sanitize your data:
$tadd = mysql_real_escape_string($_POST["tadd"]);
and do the same for the others.
Even better, use mysqli with prepared statements, or PDO with prepared statements.
They're much safer, because your present code is open to SQL injection.
Footnotes:
You should get rid of onSubmit="submit;" in your form. As outlined in comments, it's not going to do anything.
Edit:
<?php
// assuming DB connection has been made.
if(isset($_POST['submit'])) {
$tadd= mysql_real_escape_string($_POST["tadd"]);
$pname= mysql_real_escape_string($_POST["pname"]);
$date= mysql_real_escape_string($_POST["date"]);
$query = "SELECT * FROM pannel where pname = '".$pname."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
echo "Already exists.";
exit;
}
else{
mysql_query("insert into pannel (tadd, pname,date) values ('$tadd','$pname','$date')");
echo "<script type='text/javascript'>alert('Quotation Generated Successfully!')</script>";
}
} // brace for if(isset($_POST['submit']))
?>
<!DOCTYPE html>
<head></head>
<body>
<center><h1>Title</h1></center>
<form method="post" action="">
<div align="center">
<center>
<table border="0" cellspacing="0" style="width:350px">
<tr> <td><b>To Address</td> <td><textarea name="tadd" rows="5" cols="30"></textarea></td></tr>
<tr> <td><b>Project Name</td> <td><input type="text" name="pname" required></td></tr>
<tr> <td><b>Date</td> <td><input type="text" name="date" id="datepicker" required></td></tr>
<tr> <td colspan="2" align="center">
<input type="submit" name="submit" value="submit"/>
</td> </tr>
</table>
</center>
</div>
</form>
</body>
</html>

php forum not detecting new line upon submission

I am trying to set up a feature very similar to a forum, where users can write chapters or stories (long sections of text). This text is then to be stored on mysql so that it can be recalled an read and commented on etc. This is all set up and works fine, however when a new line is typed by the user, it is not recognized. So the user may type -
This is para 1
This is para 2
But all that is displayed is -
This is para1This is para 2
I know that there are certain character is html and php such as or \n, but the people using the forum will not be savvy enough to do this. Is there a way that I can get this working automatically?
Below is the code for my add_topic.php
<?php
session_start();
$uname = $_SESSION['uname'];
$host="mysql.******************.co.uk"; // Host name
$username="**********"; // Mysql username
$password="************"; // Mysql password
$db_name="************_members"; // Database name
$tbl_name="forum_question"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get data that sent from form
$topic=$_POST['topic'];
$detail=$_POST['detail'];
$name=$_POST['username'];
$datetime=date("d/m/y h:i:s"); //create date time
$sql="INSERT INTO $tbl_name(topic, detail, name, datetime)VALUES('$topic', '$detail', '$name', '$datetime')";
$result=mysql_query($sql);
if($result){
echo "Successful<BR>";
echo "<a href=main_forum.php>View your topic</a>";
}
else {
echo "ERROR";
}
mysql_close();
?>
Currently the 'details' field on the database is set to MidText. I have also tried MidBlob but there is no change in the result.
The following is my create_topic.php code -
<?php
session_start();
$uname = $_SESSION['uname'];
?>
<table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form id="form1" name="form1" method="post" action="add_topic.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3" bgcolor="#E6E6E6"><strong>Create New Story</strong> </td>
</tr>
<tr>
<td width="14%"><strong>Title</strong></td>
<td width="2%">:</td>
<td width="84%"><input name="topic" type="text" id="topic" size="50" /></td>
</tr>
<tr>
<td valign="top"><strong>Story</strong></td>
<td valign="top">:</td>
<td><textarea maxlength="2000000" name="detail" cols="50" rows="30" id="detail"></textarea></td>
</tr>
<tr>
<td><strong>Username</strong></td>
<td>:</td>
<td><input name="username" value="<?php echo $uname; ?>" type="text" id="username" size="50" readonly></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Submit" /> <input type="reset" name="Submit2" value="Reset" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
I am an absolute beginner but I will try my best to make heads or tales of any advice that can be given. If you need anymore info please let me know.
Many thanks in advance.
Have you tried using nl2br before display? It will transform all the \n character to html <br/>.
See also the docs: http://php.net/manual/en/function.nl2br.php
Please try
$detail=htmlentities($_POST['detail']);
to get special HTML characters transformed in your database.
Hope that helps.
For further info go to http://php.net/manual/en/function.htmlentities.php

PHP doesn't insert into mysql

I'am trying to do very simple php page and have some kind of problem here. the page works and everything but there is nothing coming to mysql. When I press submit it prints insert into DrinkHistory(CustomerId,DrinkId,SellerId) values('1','3','2')Your Data Inserted. But when I login to phpmyadmin there is nothing in DrinkHistory table.
the code is below
<?php
// Create connection
$con=mysqli_connect("localhost","******","*******","test");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Mene kotii ku et mitää osaa: " . mysqli_connect_error();
}
// Insert Data
#$a=$_POST['CustomerId'];
#$b=$_POST['DrinkId'];
#$c=$_POST['SellerId'];
if(#$_POST['submit'])
{
echo $s="insert into DrinkHistory(CustomerId,DrinkId,SellerId) values('$a','$b','$c')";
echo "Your Data Inserted";
mysql_query($s);
}
?>
<center>
<form method="post">
<table width="100%" height="245" border="1" bgcolor="#00CCFF">
<tr><td width="112" height="26">Asiakas</td>
<td width="100"><input type="radio" name="CustomerId" value="1"/>Jokirinne Niko</td>
</tr>
<tr><td rowspan="2">Juoma</td>
<form method)="post">
<td height="28"><input type="radio" name="DrinkId" value="2"/>Kalja</td>
<td height="28"><input type="radio" name="DrinkId" value="3"/>Lonkero</td>
<td height="28"><input type="radio" name="DrinkId" value="4"/>Siideri</td>
<td height="28"><input type="radio" name="DrinkId" value="5"/>Fisu</td>
<td height="28"><input type="radio" name="DrinkId" value="6"/>Tequila</td>
<td height="26"><input type="radio" name="DrinkId" value="7"/>MustikkaShotti</td>
</tr>
<td height="33"></tr>
<tr><td rowspan="3">Myyjä</td>
<td><input type="radio" name="SellerId" value="1"/>Niko Jokirinne</td>
<tr>
<td><input type="radio" name="SellerId" value="2"/>Tanya Lickorish</td>
<tr>
<tr><td height="62"><input type="submit" name="submit" value="Juo"/></td></tr>
</table>
</form>
</center>
</body>
</html>
You seem to be omitting the connection string (using mysql_query instead of mysqli_query) and error verification. Try this:
<?php
// Create connection
$con=mysqli_connect("localhost","******","*******","test");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Mene kotii ku et mitää osaa: " . mysqli_connect_error();
}
// Insert Data
#$a=$_POST['CustomerId'];
#$b=$_POST['DrinkId'];
#$c=$_POST['SellerId'];
if(#$_POST['submit']) {
echo $s = "insert into DrinkHistory(CustomerId,DrinkId,SellerId) values('$a','$b','$c')";
if (mysqli_query($con, $s)) {
echo "Your Data Inserted";
} else {
echo "Error inserting data: ".mysqli_error();
}
}
?>
You have several database libraries to choose from but, once you decide, you need to stick to one. You cannot start a connection with the new mysqli extension:
$con=mysqli_connect("localhost","******","*******","test");
... and then try to query the database with the legacy deprecated functions:
mysql_query($s);
If you are not getting a blattant error message on screen you've probably failed to configure PHP to display error messages in your development box.That's something you need to fix before you go further; it's impossible to code without the aid of error messages. Here's a brief explanation.
Finally, you verify if your connection fails:
if (mysqli_connect_errno($con))
... but you don't test if your query fails.

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