Saving runtime created table rows using PHP and MySQL - php

I am new to PHP. I am working on a form which has a table with thee columns that is two textboxes and and one combo box. I used JavaScript for generating the table rows and the same to delete it.
I also referred one of your blogs for generating the rows. Now I am stuck on how to save the values from the the generated textbox to the MySQL database. Can anyone help me out? It would be a huge favor.
Here is my code:
<?php
session_start();
if (!isset($_SESSION["username"])) {
header("Location: unauthorize_access.php");
}
if(isset($_POST['submit']))
{
$length = count($_POST['testparameters']);
for($i=0; $i< $length; $i++){
$TestParameters=$_POST['testparameters'][$i];
if(!empty($TestParameters)){
$InsertQuery = "INSERT INTO color(name) VALUES('$TestParameters')";
$result=mysql_query($InsertQuery) or die(mysql_error());
}
}
if(!$InsertQuery)
{
die('Could not enter data:' . mysql_error());
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Makhtab</title>
<link rel="stylesheet" type="text/css" href="form2/view.css" media="all">
<script type="text/javascript" src="form2/view.js"></script>
<script type="text/javascript" src="form2/calendar.js"></script>
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow()
{
console.log( 'hi');
var x=document.getElementById('POITable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
x.appendChild( new_row );
}
</script>
<script type="text/javascript">
function deletezimRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
document.getElementById('zimtable').deleteRow(i);
}
function inszimRow()
{
console.log( 'hi');
var x=document.getElementById('zimtable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
x.appendChild( new_row );
}
</script>
<!--<style type="text/css" title="currentStyle">
#import "tran/css/layout-styles.css";
#import "tran/css/themes/smoothness/jquery-ui-1.8.4.custom.css";
</style>-->
<script type="text/javascript" src="tran/js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="tran/js/jquery-ui-1.8.14.custom.min.js"></script>
<script type="text/javascript" src="tran/js/jq-ac-script.js"></script>
</head>
<body id="main_body" >
<img id="top" src="form2/top.png" alt="">
<div id="form_container">
<h1><a>Untitled Form</a></h1>
<form id="makhtab" class="appnitro" enctype="multipart/form-data" method="post" action="">
<div class="form_description">
<h2>Makhtab Details</h2>
<!--<p>This is your form description. Click here to edit.</p>-->
</div>
<table border="0px" width="100%">
<tr>
<td><label class="description" for="element_1">Code</label></td><td><input id="element_1" name="code" class="element text small" type="text" maxlength="6" value=""/></td>
</tr>
<tr>
<td><label class="description" for="element_1">Name</label></td><td><input id="element_1" name="name" class="element text large" type="text" maxlength="40" value=""/> </td>
</tr>
<tr>
<td><label class="description" for="element_1">Address</label></td><td><input id="element_4_1" name="add1" class="element text large" value="" type="text"></td>
</tr>
<tr>
<td></td><td><input id="element_4_1" name="add2" class="element text large" value="" type="text"></td>
</tr>
<tr>
<td></td><td><input id="element_4_1" name="add3" class="element text large" value="" type="text"></td>
</tr>
<tr>
<td><label class="description" for="element_1">City</label></td><td><select name="cmbcity" class="element text medium" style="font-size:18px;"/>
<option value=""></option>
<?php
mysql_connect("localhost", "root", '') or die(mysql_error());
mysql_select_db("webapp") or die(mysql_error());
$result = mysql_query("SELECT `name` from city ") or die(mysql_error());
while ($year = mysql_fetch_array($result)) {
echo "<option value='$year[name]'>$year[name]</option>";
}
?>
</select>
</tr>
<tr>
<td><label class="description" for="element_1">State</label></td><td><select name="cmbstate" class="element text medium" style="font-size:18px;"/>
<option value=""></option>
<?php
mysql_connect("localhost", "root", '') or die(mysql_error());
mysql_select_db("webapp") or die(mysql_error());
$result = mysql_query("SELECT `name` from state ") or die(mysql_error());
while ($year = mysql_fetch_array($result)) {
echo "<option value='$year[name]'>$year[name]</option>";
}
?>
</select>
</tr>
</tr>
<tr>
<td><label class="description" for="element_1">Country</label></td><td><select name="cmbcountry" class="element text medium" style="font-size:18px;"/>
<option value=""></option>
<?php
mysql_connect("localhost", "root", '') or die(mysql_error());
mysql_select_db("webapp") or die(mysql_error());
$result = mysql_query("SELECT `name` from country ") or die(mysql_error());
while ($year = mysql_fetch_array($result)) {
echo "<option value='$year[name]'>$year[name]</option>";
}
?>
</select>
<tr>
<td><label class="description" for="element_1">Telephone</label></td><td><input id="element_1" name="country" class="element text medium" type="text" maxlength="255" value=""/></td>
</tr>
<tr>
<td><label class="description" for="element_1">Mobile</label></td><td><input id="element_1" name="country" class="element text medium" type="text" maxlength="10" value=""/></td>
</tr>
<tr>
<br />
</tr>
</table>
<tr>
<br /><p style="border-bottom: 1px dotted #ccc;"></p><br />
<div class="form_description">
<h2>Zimmedar Details</h2>
<!--<p>This is your form description. Click here to edit.</p>-->
</div>
</tr>
<input type="button" id="addmorezimbutton" value="Add zimmedar" onclick="insRow()"/><br/><br/>
<table id="zimtable" border="0px" size="100px" cellspacing="0" cellpadding="2">
<tr>
<td width="10" align="center"><label class="description">Srno. </label></td>
<td width="118"><label class="description">Zimmedar Name</label></td>
<td width="118"><label class="description">Mobile</label></td>
<td width="10"></td>
<td width="10" align="center"></td>
</tr>
<tr>
<td>1</td>
<td width="210"><input size="40" maxlenght="40" type="text" id="zimame[]"/></td>
<td width="80"><input size="10" maxlenght="10" type="text" id="zimmob[]"/></td>
<!--<td><input size="45" maxlenght="10" type="text" id="momob"/> </td>-->
<td><input type="button" id="addzimmore" value="+" onclick="inszimRow()"/></td>
<td align="center"><input type="button" id="delzimbutton" value="-" onclick="deletezimRow(this)"/></td>
</tr>
</table>
<tr>
<br /><p style="border-bottom: 1px dotted #ccc;"></p><br />
<div class="form_description">
<h2>Muallim Details</h2>
<!--<p>This is your form description. Click here to edit.</p>-->
</div>
</tr>
<input type="button" id="addmorePOIbutton" value="Add Muallims" onclick="insRow()"/><br/><br/>
<table id="POITable" border="0px" size="100px" cellspacing="0" cellpadding="2">
<tr>
<td width="10" align="center"><label class="description">Srno. </label></td>
<td width="118"><label class="description">Moallim Name</label></td>
<td width="118"><label class="description">Mobile</label></td>
<td width="118"><label class="description">Qabiliyat</label></td>
<td width="10"></td>
<td width="10" align="center"></td>
</tr>
<tr>
<td>1</td>
<td width="210"><input size="40" maxlenght="40" type="text" id="moname[]"/></td>
<td width="80"><input size="10" maxlenght="10" type="text" id="momob[]"/></td>
<td><select name="cmbmuallim[]" class="element text large" style="font-size:18px;"/>
<option value=""></option>
<?php
mysql_connect("localhost", "root", '') or die(mysql_error());
mysql_select_db("webapp") or die(mysql_error());
$result = mysql_query("SELECT `name` from qabiliyat ") or die(mysql_error());
while ($year = mysql_fetch_array($result)) {
echo "<option value='$year[name]'>$year[name]</option>";
}
?>
</select></td>
<!--<td><input size="45" maxlenght="10" type="text" id="momob"/> </td>-->
<td><input type="button" id="addmore" value="+" onclick="insRow()"/></td>
<td align="center"><input type="button" id="delPOIbutton" value="-" onclick="deleteRow(this)"/></td>
</tr>
</table>
<br /><p style="border-bottom: 1px dotted #ccc;"></p><br />
<table border="0px" width="85%">
<tbody><tr>
<td width="105"><label class="description">No. of Students</label></td>
<td width="65"><input type="text" name=stu" size="5" maxlength="5"></input></td>
<td width="105"><label class="description">No. of Batches</label></td><td width="14"><input type="text" name="batch" size="5" maxlength="3"></input></td>
</tr>
<tr>
</tr>
</tbody>
</table>
</div>
</div>
</form>
</table>
</form>
</body>
</html>

Correct me if am wrong.
I didnt see any code to open a mysql database connection.
See this example.
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
} else {
echo "Error creating database: " . mysql_error();
}
?>
Before inserting records using mysql_query, make sure that you opened a mysql db connection like above.

Related

How to use nl2br to fetch data of textarea using php?

I am new in php. I have a web form. In which i use textarea. I have another PHP page where I display data from db and applying CRUD operation. Now here is the problem when I click on Edit button my all form data has been fetched from db but the formatting of textarea Text has been changed. It shows \r\r\r\n I use nl2br but its not working. I want to display my data in same formating.
<textarea rows="20" cols="100" id="text" name="text" style="font-size:14px;" > <?php echo !empty(nl2br($text))?(nl2br($text)):'';?> </textarea><td>
My Full Page Code is
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
if ( !empty($_POST)) {
// keep track post values
$file_name = $_POST['file_name'];
$ref_no = $_POST['ref_no'];
$to_name = $_POST['to_name'];
$confidential = $_POST['confidential'];
$designation = $_POST['designation'];
$date = $_POST['date'];
$solutation = $_POST['solutation'];
$entity = $_POST['entity'];
$add_1 = $_POST['add_1'];
$thank_you = $_POST['thank_you'];
$add_2 = $_POST['add_2'];
$yours_truly = $_POST['yours_truly'];
$add_3 = $_POST['add_3'];
$sign_name = $_POST['sign_name'];
$city = $_POST['city'];
$s_designation = $_POST['s_designation'];
$heading_line_1 = $_POST['heading_line_1'];
$encl_line_1 = $_POST['encl_line_1'];
$heading_line_2 = $_POST['heading_line_2'];
$encl_line_2 = $_POST['encl_line_2'];
$heading_line_3 = $_POST['heading_line_3'];
$encl_line_3 = $_POST['encl_line_3'];
$text = mysql_real_escape_string( $_POST['text'] );
// update data
$valid = true;
if ($valid) {
$pdo = Database::connect();
// $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE test set file_name ='$file_name', ref_no ='$ref_no', to_name ='$to_name',
confidential ='$confidential', designation = '$designation', date ='$date',
solutation ='$solutation', entity ='$entity', add_1 ='$add_1',
thank_you ='$thank_you', add_2 ='$add_2', yours_truly ='$yours_truly',
add_3 ='$add_3', sign_name ='$sign_name', city ='$city',
s_designation ='$s_designation', heading_line_1 ='$heading_line_1', encl_line_1 ='$encl_line_1',
heading_line_2 ='$heading_line_2', encl_line_2 ='$encl_line_2', heading_line_3 ='$heading_line_3',
encl_line_3 ='$encl_line_3', text ='$text' WHERE id ='$id'";
$q = $pdo->prepare($sql);
$q->execute(array($file_name,$ref_no,$to_name,$confidential,$designation,$date,$solutation,$entity,$add_1,
$thank_you,$add_2,$yours_truly,$add_3,$sign_name,$city,$s_designation,$heading_line_1,$encl_line_1,$heading_line_2,
$encl_line_2,$heading_line_3,$encl_line_3,$id));
Database::disconnect();
header("Location: index.php");
}
else {
}
}
$con=mysqli_connect("localhost","MY_LOGIN","MY_PASSWORD","MY_DATABASE");
$id2 = $_GET['id'];
$sql = "SELECT * FROM test where id='$id2'";
$result=mysqli_query($con,$sql);
$row= (mysqli_fetch_array($result,MYSQLI_ASSOC));
$file_name = $row['file_name'];
$ref_no = $row['ref_no'];
$to_name = $row['to_name'];
$confidential = $row['confidential'];
$designation = $row['designation'];
$date = $row['date'];
$solutation = $row['solutation'];
$entity = $row['entity'];
$add_1 = $row['add_1'];
$thank_you = $row['thank_you'];
$add_2 = $row['add_2'];
$yours_truly = $row['yours_truly'];
$add_3 = $row['add_3'];
$sign_name = $row['sign_name'];
$city = $row['city'];
$s_designation = $row['s_designation'];
$heading_line_1 = $row['heading_line_1'];
$encl_line_1 = $row['encl_line_1'];
$heading_line_2 = $row['heading_line_2'];
$encl_line_2 = $row['encl_line_2'];
$heading_line_3 = $row['heading_line_3'];
$encl_line_3 = $row['encl_line_3'];
$text = mysql_real_escape_string( $row['text'] );
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="newstyles.css">
<script src="js/bootstrap.min.js"></script>
<script>
function show_confirm(){
return confirm("Copy is being created....");
window.location.href='index.php';
}
</script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$("#date").datepicker({
dateFormat: "yy-mm-dd"
}).datepicker();
});
</script>
</head>
<body>
<form action="edit4.php?id=<?php echo $id; ?>" method="POST" >
<table border="0" class="DivTableBorder" width="840px">
<tr>
<td class="DivSubHeaderCellTop" colspan="6">Letters</td>
</tr> <tr> </td> </tr>
<tr>
<td class="DivCellText" width="80px">File Name </td>
<td class="DivCellText" width="480px" colspan="3"><input name="file_name" type="text" id="file_name"
value="<?php echo !empty($file_name)?$file_name:'';?>" class="inputRemarks" />
</td>
<td class="DivCellText" width="80px">Referance #</td>
<td class="DivCellText" width="200px"><input name="ref_no" type="text" id="ref_no"
value="<?php echo !empty($ref_no)?$ref_no:'';?>" class="inputRemarks" />
</td> </tr>
<tr ><td bgcolor="#999999" colspan="4"></td>
<td class="DivCellText" width="80px"></td>
<td class="DivCellText" width="200px"></td>
</tr>
<tr>
<td class="DivCellText" width="80px">To - Name</td>
<td class="DivCellText" colspan="3"><input name="to_name" type="text" id="to_name"
value="<?php echo !empty($to_name)?$to_name:'';?>" class="inputRemarks" />
</td>
<td class="DivCellText" width="80px">Confidential</td>
<td class="DivCellText" width="200px">
<?php if($confidential == "on"){ ?>
<input name="confidential" type="checkbox" checked="checked" id="confidential" value="on" />
<?php }else{ ?>
<input name="confidential" type="checkbox" id="confidential" value="on" />
<?php } ?>
</td> </tr>
<tr>
<td class="DivCellText" width="80px"> Designation</td>
<td class="DivCellText" colspan="3"><input name="designation" type="text" id="designation"
value="<?php echo !empty($designation)?$designation:'';?>" class="inputRemarks" />
</td>
<td class="DivCellText" width="80px">Date :</td>
<td class="DivCellText" width="200px">
<input name="date" type="text" id="date" value="<?php echo $date; ?>" />
</td> </tr>
<tr>
<td class="DivCellText" > </td>
<td class="DivCellText" colspan="3"> </td>
<td class="DivCellText" width="80px">Solutation</td>
<td class="DivCellText" width="200px" >
<select name='solutation' id='solutation' size='1' STYLE='width: 95%' value="<?php echo !empty($solutation)?$solutation:'';?>" >
<option value='Others' >[--Others--]</option>
<option value='Dear Sir' >Dear Sir</option>
<option value='Madam' >Madam</option>
</select>
</td> </tr>
<tr>
<td class="DivCellText" width="80px"> Entity</td>
<td class="DivCellText" colspan="3"><input name="entity" type="text" id="entity"
value="<?php echo !empty($entity)?$entity:'';?>" class="inputRemarks" />
</td>
<td class="DivCellText" width="80px"> </td>
<td class="DivCellText" width="200px" >
<input name="txtSolutation" type="text" id="txtSolutation"
value="" class="inputRemarks" />
</td> </tr>
<tr>
<td class="DivCellText" width="80px"> Add-1</td>
<td class="DivCellText" colspan="3"><input name="add_1" type="text" id="add_1"
value="<?php echo !empty($add_1)?$add_1:'';?>" class="inputRemarks" />
</td>
<td class="DivCellText" width="80px">Thank You.</td>
<td class="DivCellText" width="200px" ><input name="thank_you" type="text" id="thank_you"
value="<?php echo !empty($thank_you)?$thank_you:'';?>" class="inputRemarks" />
</td>
</tr>
<tr>
<td class="DivCellText" width="80px"> Add-2</td>
<td class="DivCellText" colspan="3"><input name="add_2" type="text" id="add_2"
value="<?php echo !empty($add_2)?$add_2:'';?>" class="inputRemarks" />
</td>
<td class="DivCellText" width="80px">Yours truly</td>
<td class="DivCellText" width="200px" >
<select name='yours_truly' id='yours_truly' size='1' STYLE='width: 95%' value="<?php echo !empty($yours_truly)?$yours_truly:'';?>" >
<option value='1' >Yours truly</option>
<option value='2' >Regards</option>
</select>
</td> </tr>
<tr>
<td class="DivCellText" width="80px"> Add-3</td>
<td class="DivCellText" colspan="3"><input name="add_3" type="text" id="add_3"
value="<?php echo !empty($add_3)?$add_3:'';?>" class="inputRemarks" />
</td>
<td class="DivCellText" width="80px">Signature-Name</td>
<td class="DivCellText" width="200px" >
<select name='sign_name' id='sign_name' size='1' style='width:95%' value="<?php echo !empty($sign_name)?$sign_name:'';?>">
<option value='1' >Adnan Afaq</option>
<option value='2' >Muhammad Shahzad Saleem</option>
<option value='3' >Adnan Dilawar</option>
<option value='4' >Rana Muhammad Nadeem</option>
<option value='5' >Jhangeer Hanif</option>
</select>
</td> </tr>
<tr>
<td class="DivCellText" width="80px"> City</td>
<td class="DivCellText" colspan="3"><input name="city" type="text" id="city"
value="<?php echo !empty($city)?$city:'';?>" class="inputRemarks" />
</td>
<td class="DivCellText" width="80px">S-Designation</td>
<td class="DivCellText" width="200px">
<select name='s_designation' id='s_designation' size='1' STYLE='width: 95%' value="<?php echo !empty($s_designation)?$s_designation:'';?>" >
<option value='1' >Managing Director</option>
<option value='2' >Chief Operating Officer</option>
<option value='3' >Manager Ratings</option>
<option value='4' >Unit Head Ratings</option>
</select>
</td>
</tr>
<tr>
<td class="DivCellText" width="80px">Heading Line-1</td>
<td class="DivCellText" width="480px" colspan="3"><input name="heading_line_1" type="text" id="heading_line_1"
value="<?php echo !empty($heading_line_1)?$heading_line_1:'';?>" class="inputRemarks" maxlength="55"/>
</td>
<td class="DivCellText" width="80px">Encl: Line-1</td>
<td class="DivCellText" width="200px" >
<input name="encl_line_1" type="text" id="encl_line_1" value="<?php echo !empty($encl_line_1)?$encl_line_1:'';?>" class="inputRemarks" />
</td>
</tr>
<tr>
<td class="DivCellText" width="80px">Heading Line-2</td>
<td class="DivCellText" width="480px" colspan="3"><input name="heading_line_2" type="text" id="heading_line_2"
value="<?php echo !empty($heading_line_2)?$heading_line_2:'';?>" class="inputRemarks" maxlength="55" />
</td>
<td class="DivCellText" width="80px"> Line-2</td>
<td class="DivCellText" width="200px" >
<input name="encl_line_2" type="text" id="encl_line_2" value="<?php echo !empty($encl_line_2)?$encl_line_2:'';?>" class="inputRemarks" />
</tr>
<tr>
<td class="DivCellText" width="80px">Heading Line-3</td>
<td class="DivCellText" width="480px" colspan="3"><input name="heading_line_3" type="text" id="heading_line_3"
value="<?php echo !empty($heading_line_3)?$heading_line_3:'';?>" class="inputRemarks" maxlength="55" />
</td>
<td class="DivCellText" width="80px"> Line-3</td>
<td class="DivCellText" width="200px">
<input name="encl_line_3" type="text" id="encl_line_3" value="<?php echo !empty($encl_line_3)?$encl_line_3:'';?>" class="inputRemarks" />
</td>
</tr>
<tr ><td bgcolor="#999999" colspan="6"></td></tr>
<tr ><td colspan="6">
<table border="0" class="DivTableBorder" width="840px">
<tr>
<td class="DivCellText" colspan="4">
<textarea rows="20" cols="100" id="text" name="text" style="font-size:14px;" > <?php echo !empty(nl2br($text))?(nl2br($text)):'';?> </textarea><td>
</tr>
<tr>
<td width="100"><input type="submit" name="submit" value="Create Copy" onclick="return show_confirm();" class="blueButton"></input></td>
<td width="100"><input type="reset" name="reset" value="Cancel" class="blueButton" /> </td>
<td width="100">
<input type="submit" name="submit" value="Save" class="blueButton"></input>
</td>
<td width="303"> <input type="submit" name="submit" value="Update" class="blueButton"> </input> </td>
<td width="209">
<a class="btn" href="index.php">Back</a> </td>
</tr>
</table>
</form>
<?php
$_POST['submit']="";
if($_POST['submit'] == "Create Copy"){
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server
$db = mysql_select_db("pacra1", $connection); // Selecting Database from Server
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$file_name = $_POST['file_name'];
$ref_no = $_POST['ref_no'];
$to_name = $_POST['to_name'];
$confidential = $_POST['confidential'];
$designation = $_POST['designation'];
$date = $_POST['date'];
$solutation = $_POST['solutation'];
$entity = $_POST['entity'];
$add_1 = $_POST['add_1'];
$thank_you = $_POST['thank_you'];
$add_2 = $_POST['add_2'];
$yours_truly = $_POST['yours_truly'];
$add_3 = $_POST['add_3'];
$sign_name = $_POST['sign_name'];
$city = $_POST['city'];
$s_designation = $_POST['s_designation'];
$heading_line_1 = $_POST['heading_line_1'];
$encl_line_1 = $_POST['encl_line_1'];
$heading_line_2 = $_POST['heading_line_2'];
$encl_line_2 = $_POST['encl_line_2'];
$heading_line_3 = $_POST['heading_line_3'];
$encl_line_3 = $_POST['encl_line_3'];
$text = mysql_real_escape_string( $_POST['text'] );
//$txtTitle = mysql_real_escape_string( $_POST['txtTitle'] );
//$txtRational = $_POST['txtRational'];
//Insert Query of SQL
$query = mysql_query("INSERT INTO test(file_name, ref_no, to_name, confidential, designation, date, solutation, entity, add_1, thank_you, add_2, yours_truly, add_3, sign_name, city, s_designation, heading_line_1, encl_line_1, heading_line_2, encl_line_2, heading_line_3, encl_line_3, text)
values
('$file_name', '$ref_no', '$to_name', '$confidential', '$designation', '$date', '$solutation', '$entity', '$add_1', '$thank_you', '$add_2', '$yours_truly', '$add_3', '$sign_name', '$city', '$s_designation', '$heading_line_1', '$encl_line_1', '$heading_line_2', '$encl_line_2', '$heading_line_3', '$encl_line_3', '$text')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
//mysql_close($connection); // Closing Connection with Server
}
?>
</body>
</html>
You should change your php echo code as you dont need to include the !empty verification. If you do then you will have to create that before you echo the textbox. I suggest you change your code to this:
<textarea rows="20" cols="100" id="text" name="text" style="font-size:14px;" > <?php echo nl2br($text);?> </textarea><td>
You can also find some documentation of the nl2br here :
http://php.net/manual/en/function.nl2br.php
Upon inserting to the database, apply the nl2br - as you are likely to be presenting that data as text on a page more often than an textarea.
$mysql->real_escape_string(trim(nl2br($_POST['text'])))
Where $mysql is the mysqli database connection
Disclaimer As Bartdude mentioned, this is not especially good practice, since the information in the database should be as free from tags as possible - however, if this data is to be used in HTML pages only, then this solution should work.
Then when returning the data to a textarea, simply remove the <br> tags, the newline characters will be there anyway and should be interpreted by the browser correctly.
str_replace("<br>", " ", $row['text'])

dropdownlist not passing selected values in form via POST

I have a registration form which includes 2 dropdown lists, one of which changes depending on which option in the first dropdown list is selected.Upon clicking the button submit, all the values in the form are passed successfully, EXCEPT for the values in the dropdown list.
My Code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8" />
<title>Sign Up</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript">
function configureDropDownLists(ddl1,ddl2) {
var retail = new Array('Books','Computer Accessories','Electronics', 'Fashion','Others');
var dining = new Array('Asian','Chinese','French','Italian','Japanese','Korean','Western','Others');
switch (ddl1.value) {
case 'Retail':
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < retail.length; i++) {
createOption(document.getElementById(ddl2), retail[i], retail[i]);
}
break;
case 'Dining':
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < dining.length; i++) {
createOption(document.getElementById(ddl2), dining[i], dining[i]);
}
break;
default:
document.getElementById(ddl2).options.length = 0;
break;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
</script>
</head>
<body style="background-color:#FFF">
<div id="container_register">
<div id="header_register"></div>
<div id="welcome_register">Register</div>
<div id="box_register">
<form id="RegForm" name="RegForm" method="POST" action="Register.php">
<table width="460" border="0" cellpadding="5" cellspacing="5">
<tr>
<td>Username*</td><td><input type="text" name="username" maxlength="30" size="30" required="required" /></td>
</tr>
<tr>
<td>Email*</td><td><input type="text" name="email" maxlength="30" size="30" required="required" /></td>
</tr>
<tr>
<td>Verify Email*</td><td><input type="text" name="vemail" maxlength="50" size="30" required="required" /></td>
</tr>
<tr>
<td>Password*</td><td><input type="password" name="password" maxlength="50" size="30" required="required" /></td>
</tr>
<tr>
<td>Verify Password*</td><td><input type="password" name="vpassword" maxlength="50" size="30" required="required" /></td>
</tr>
<tr>
<td>Business Name*</td><td><input type="text" name="bizname" maxlength="30" size="30" required="required" /></td>
</tr>
<tr>
<td>Verify Business Name*</td><td><input type="text" name="vbizname" maxlength="30" size="30" required="required" /></td>
</tr>
<tr>
<td>Business Type*</td>
<td>:
<select name="type" id="ddl" onchange="configureDropDownLists(this,'ddl2')">
<option value=""></option>
<option value="Retail">Retail</option>
<option value="Dining">Dining</option>
</select>
</tr>
<tr>
<td>Business SubType*</td>
<td>:
<select id="ddl2" name="subtype">
</select>
</td>
</tr>
<tr>
<td>Info</td><td><textarea name="info" rows="5" cols="24" maxlength="300"></textarea>
</tr>
<tr>
<td colspan="2"><input type="SUBMIT" name="Button" value="Register"></td>
</tr>
<tr>
<td colspan="2"><?PHP if(isset($errormsg)){echo"$errormsg";}?></td>
</tr>
<tr>
<td colspan="3"><font color="#FF0000"></font></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
Upon submitting the form, i am directed to the processing page where i echo print_r($POST), and i get
Array ( [username] => uname [email] => email [vemail] => vemail [password] => pw [vpassword] => vpw [bizname] => name [vbizname] => vname [Button] => Register )
Question:
How do i pass the values of the selected values in the dropdown list AND the textarea?

Get the database content posted on a selected option into a form with single fields

I have a form with a select. The options are coming from a database and displayed into the select.
The columns on the database are:
id, date, title, body.
On the select I display only date and title. In the same page I have a form with:
date -> input text
title -> input text
body -> text area
I want that when an option from the select is clicked by the user the fields below will be update with the content kept from the selected option which contain the database data.
Now I have no idea how to get the data on the fields below.
My idea was to get the index of the option of the drop down. Is this possible?
EDIT COMPLETE CODE:
<html>
<body>
<div class="normal">
<table style="width:100%;height:100%;" border="1">
<tr>
<td width="174"><strong>geste n</strong></td>
<td width="505" valign="middle" height="24">
<input type="radio" name="n" id="new" value="nuova" onchange="shown(this.id);" <?php if($_POST['n'] == "nuova"){echo "CHECKED";} ?> />Nuova n
<input type="radio" name="n" id="mod" value="modifica" onchange="shown(this.id);" <?php if($_POST['n'] == "modifica"){echo "CHECKED";} ?> />Modifica n
<select id="sceltannascosta" style="display:none">
<?php
include("/login/flock/sql.php");
$conn = mysqli_connect($host, $user, $pw, $db) or die("Impossibile connettersi");
$a = "SELECT * FROM n ORDER BY id DESC";
$b = mysqli_query($conn, $a);
print '<option></option>';
while ($c = $b->fetch_object()) {
print '<option>'.$c->id.$c->data.$c->title.$c->body.'</option>';
}
$b->close();
$conn->close;
?>
</select>
<select id="sceltan" style="display:none" onChange="showEntry(this,this.value);setndamod(this);">
<?php
include("/login/flock/sql.php");
$conn = mysqli_connect($host, $user, $pw, $db) or die("Impossibile connettersi");
$a = "SELECT * FROM n ORDER BY id DESC";
$b = mysqli_query($conn, $a);
print '<option></option>';
while ($c = $b->fetch_object()) {
print '<option>'.$c->data.' - '.$c->title.'</option>';
}
$b->close();
$conn->close;
?>
</select>
<input type="submit" id="botenascostogeste" class="button">
</form>
</td>
</tr>
</table>
</div>
<p> </p>
<div class="normal" id="c" style="display:none">
<table style="width:100%;height:100%;">
<tr>
<td colspan="3" border="0">
<strong class="confirm">c nuova n</strong>
</td>
</tr>
<tr>
<td width="107" align="right">
<strong>Data</strong>
</td>
<td colspan="2">
<form name="nuovan" method="post" action="cht.php?c=yes">
<input name="datan" type="text" maxlength="10" size="8" value="<?php echo date(d.".".m.".".Y) ?>"> gg.mm.aaaa
</td>
</tr>
<tr>
<td align="right">
<strong>Titolo</strong>
<td width="360">
<input name="titolon" type="text" maxlength="50" size="50" value="<? echo htmlspecialchars("titolo n - lunghezza massima 50 caratteri") ?>" onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')">
</td>
<td width="522">
<b><span id=myCounter>6</span></b> caratteri rimanenti per il titolo</font>
</td>
</tr>
<tr>
<td colspan="3">
<textarea name="teston"><?php if(isset($_POST['teston'])){echo $_POST['teston'];}else{echo 'Testo n con stile personalizzato';} ?></textarea>
<script>
CKEDITOR.replace('teston');
</script>
</td>
</tr>
<tr>
<td align="right">
<input type="submit" name="c" class="button" onClick="document.getElementById('botenascostogeste').click();">
</form>
</td>
<td colspan="2">
<?php
$c = $_GET['c'];
$titolon = $_POST['titolon'];
$teston = $_POST['teston'];
$datascritta = $_POST['datan'];
if($c == 'yes'){
if($_POST['titolon'] == NULL || $_POST['teston'] == NULL || $_POST['datan'] == NULL){
echo '<img src="'.$imagen.'" style=width:"' . $width . 'px;height:' . $height . 'px;">';
} else {
function verificadata($datascritta) {
list($dd,$mm,$yyyy)=explode(".",$datascritta);
if (is_numeric($dd) && is_numeric($mm) && is_numeric($yyyy))
{
return checkdate($mm,$dd,$yyyy);
}
return false;
}
if(verificadata($datascritta)){
$connessione = mysql_connect ($host, $user, $pw) or //connect to the database
die('<img src="'.$imagen.'" style=width:"' . $width . 'px;height:' . $height . 'px;">');
mysql_select_db ($db); //select the database
mysql_query("INSERT INTO n(data, title, body) VALUES ('$datascritta', '$titolon', '$teston')");
mysql_close($connessione);
echo ('<img src="'.$imagey.'" style=width:"' . $width . 'px;height:' . $height . 'px;"> Ok'); // It worked.
} else { die('<img src="'.$imagen.'" style=width:"' . $width . 'px;height:' . $height . 'px;">');
}
}
}
?>
</td>
</table>
</div>
<div class="normal" id="modifica" style="display:none">
<table style="width:100%;height:100%;">
<tr>
<td colspan="3" border="0">
<strong class="confirm">Modifica n</strong>
</td>
</tr>
<tr>
<td width="107" align="right">
<strong>Data</strong>
</td>
<td colspan="2">
<form name="modifican" method="post" action="cht.php?modifica=yes">
<input name="idmodifican" type="text" style="display:none" value="INSERIRE ID DI MODIFICA DEL DATABASE QUI">
<input name="datanmodificata" type="text" maxlength="10" size="8" value="POST DATE FROM THE n TO MODIFY SELECTED"> gg.mm.aaaa
</td>
</tr>
<tr>
<td align="right">
<strong>Titolo</strong>
</td>
<td width="360">
<input name="modificatitolo" type="text" maxlength="50" size="50" value="POST TITLE FROM THE n TO MODIFY SELECTED" onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')">
</td>
<td width="522">
<b><span id=myCounter>50</span></b> caratteri rimanenti per il titolo</font>
</td>
</tr>
<tr>
<td colspan="3">
<textarea name="modificatesto">POST BODY FROM THE n TO MODIFY SELECTED</textarea>
<script>
CKEDITOR.replace('modificatesto');
</script>
</td>
</tr>
<tr>
<td align="right">
<input type="submit" name="modifica" class="button">
</form>
</td>
<td colspan="2">
PHP I HAVE TO DO TO UPDATE THE n ON THE DATABASE (I'm able to do this part).
</td>
</table>
</div>
</body>
for this you need to make ajax call.
then use jquery to get the field set up depending upon the value selected in the select field you can set the value of the other fields try this modify it according to your need
<body>
<form>
<select id="sel_opt">
<?php
$i = 1;
foreach($valueformdb as $value)
{
echo "<option class=\"option\" id=\"opt_$i\">";
echo $value;
echo '</option>';
$i++;
}
?>
</select>
<input type="text" id="txt_date" value="" />
<input type="text" id="txt_title" value="" />
<textarea id="ta_body"></textarea>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('.sel_opt').on('change', function(){
var id = $(this).attr('id');
$.ajax({
type:'POST',
dataType: 'json',
url:" ",// path of file to handle ajax request
data:'option='+id, // this will be posted on the page which handle the ajax and give back the data from db
success:function(data){
$('#txt_date').val(data[date]);// ajax respond the array containg the value its advised to use json
$('#txt_title').val(data[title]);
}
});
});
});
</script>
</body>
this is not the exact code you need to modify a bit, cause i don't know the exact thing you are trying to achieve

Date picker & combo box values are not going to mysql

I am making a registration form in PHP and when submitting the form Date(Check In, for which I have used Date Picker), Combo boxes(Sex & Room No) & check box(taxi) is not getting inserted.
I have looked enough in to the code but not getting what is wrong..though other combo box and check box working just fine.
PHP Code -
<?php
$passport = $_POST['passport'];
$name = $_POST['name'];
$sex = $_POST['sex'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$city = $_POST['city'];
$country = $_POST['country'];
$contact = $_POST['contact'];
$email = $_POST['email'];
$roomNo = $_POST['roomNo'];
if(isset($_POST['food']) && $_POST['food'] == 'food')
{
$food = 'yes';
}
else
{
$food = 'no';
}
if(isset($_POST['car']) && $_POST['car'] == 'car')
{
$car = 'yes';
}
else
{
$car = 'no';
}
if(isset($_POST['others']) && $_POST['others'] == 'others')
{
$others = 'yes';
}
else
{
$others = 'no';
}
$checkIn = $_POST['checkIn'];
mysql_connect("localhost","root","");
mysql_select_db("guesthouse");
$personal_query = "INSERT INTO personal_details VALUES(
'',
'$name',
'$sex',
'$address1',
'$address2',
'$city',
'$country',
'$contact',
'$email')";
mysql_query($personal_query);
$result = mysql_affected_rows();
if($result == 1)
{
echo "Personal Details Submitted";
}
$booking_query = "INSERT INTO booking VALUES(
'',
'$name',
'$roomno',
'$food',
'$taxi',
'$others',
'$checkIn')";
mysql_query($booking_query);
$result = mysql_affected_rows();
if($result == 1) {
echo "<br/>Booking Details Submitted";
}
?>
HTML -
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" media="all" href="jsDatePick_ltr.min.css" />
<script type="text/javascript" src="jsDatePick.min.1.3.js"></script>
<script type="text/javascript">
window.onload = function(){
new JsDatePick({
useMode:2,
target:"checkIn",
dateFormat:"%d-%M-%Y"
/*selectedDate:{
day:5,
month:9,
year:2006
},
yearsRange:[1978,2020],
limitToToday:false,
cellColorScheme:"beige",
dateFormat:"%m-%d-%Y",
imgPath:"img/",
weekStartDay:1*/
});
};
</script>
</head>
<form name="form1" method="post" action="registration_handle.php">
<table width="60%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2" align="center" bgcolor="#0099FF">Room Reservation Details :</td>
</tr>
<tr>
<td width="33%" align="center" bgcolor="#66FFCC">Passport No </td>
<td width="67%"><label for="textfield"></label>
<input type="text" name="passport" id="passport"></td>
</tr>
<tr>
<td align="center" bgcolor="#66FFCC">Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td align="center" bgcolor="#66FFCC">Sex</td>
<td><label for="select3"></label>
<select name="sex" id="sex">
<option value="" selected>Male</option>
<option value="" >Female</option>
</select></td>
</tr>
<tr>
<td align="center" bgcolor="#66FFCC">Address 1</td>
<td><input type="text" name="address1" id="address1"></td>
</tr>
<tr>
<td align="center" bgcolor="#66FFCC">Address2</td>
<td><input type="text" name="address2" id="address2"></td>
</tr>
<tr>
<td align="center" bgcolor="#66FFCC">City</td>
<td><input type="text" name="city" id="city" /></td>
</tr>
<tr>
<td align="center" bgcolor="#66FFCC">Country</td>
<td><label for="select2"></label>
<select name="country" id="country">
<?php
mysql_connect("localhost","root","");
mysql_select_db("guesthouse");
$query = "SELECT name FROM country";
$query_result = mysql_query($query);
while($result = mysql_fetch_assoc($query_result))
{
?>
<option value = "<?php echo $result['name'] ?>"><?php echo $result['name'] ?></option>
<?php
}
?>
</select></td>
</tr>
<tr>
<td align="center" bgcolor="#66FFCC">Contact No</td>
<td><input type="text" name="contact" id="contact"></td>
</tr>
<tr>
<td align="center" bgcolor="#66FFCC">E-Mail </td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="center" bgcolor="#66FFCC">Room No</td>
<td><label for="select4"></label>
<select name="roomNo" id="roomNo">
<?php
mysql_connect("localhost","root","");
mysql_select_db("guesthouse");
$query = "SELECT name FROM roomno";
$query_result = mysql_query($query);
while($result = mysql_fetch_assoc($query_result))
{
?>
<option value = "<?php echo $result['name'] ?>"><?php echo $result['name'] ?></option>
<?php
}
?>
</select></td>
</tr>
<tr>
<td align="center" bgcolor="#66FFCC">Extra Service</td>
<td><p>
<label> </label>
<input type="checkbox" name="food" value="food" />Food
<input type="checkbox" name="car" value="car" />Car
<input type="checkbox" name="others" value="others" />Others<br>
</p></td>
</tr>
<tr>
<td align="center" bgcolor="#66FFCC">Check In </td>
<td><label for="textfield3"></label>
<input type="text" size="16" name="checkIn" id="checkIn"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="button" id="button" value="Submit">
<input type="reset" name="Reset" id="Reset" value="Reset" />
<input type="submit" name="cancel" id="cancel" value="Cancel" /></td>
</tr>
</table>
</form>
</html>
value of sex is "" (if you want default, don't type value="")
-Tested-
<html>
<body>
<select onchange="alert(this.value);">
<option>Volvo</option>
<option>Saab</option>
<option value=''>Mercedes</option>
<option>Audi</option>
</select>
</body>
</html>
you never give any value to $taxi (wich is called car in your form)
You initialte $roomNo and store $roomno
--- found these errors because I tend to do same things. here's a tip, always verify your variables name first, 99% of your probs will be fixed --- (works for me :) )

Mysql Problem with html and php

I have a table called Stafflist which is called and lists all of the members on the page.
I then want to have some text boxes for each person which are editable.
When the submit button is clicked I want it to insert the staff name and the relevant info from the page into a separate table called Services
The code I've got is just pulling at the moment and no inserting is done.
I would be grateful for an example of how to achieve this.
Security isn't an issue right now as I'm going to go through and look at the security part at a later date
<?php
include 'dbc.php';
page_protect();
company();
$stafflist = mysql_query("SELECT * FROM StaffList
WHERE full_name != 'Adam Carter' AND full_name != 'Jakata'
AND branch = '$_SESSION[branch]' ");
if (checkAdmin()) {
?>
<html><head><title>Book Off Holiday</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src="php_calendar/scripts.js" type="text/javascript"></script>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<form name="form" action="Newkpi.php" method="post">
<table width="100%" border="0" cellspacing="0" cellpadding="5" class="main">
<tr>
<td colspan="3"> </td>
</tr>
<td width="160" valign="top">
<?php
if (isset($_SESSION['user_id'])) {
}
?>
Admin CP
</td>
<td width="732" valign="top">
<p>
<h3 class="titlehdr">New KPI</h3>
<table width="300px" border="0" align="Centre" cellpadding="2" cellspacing="0">
<tr bgcolor="#000050">
<td width="20px"><h3 class="Text2">Staff Member</h3></td>
<td width="20px"><h3 class="Text2">Service Amount</h3></td>
<td width="20px"><h3 class="Text2">Service Date</h3></td>
<td width="20px"><h3 class="Text2">Forecast For Next Month</h3></td>
<td width="20px"><h3 class="Text2">Product Sales</h3></td>
<td width="20px"><h3 class="Text2">Clients This Month</h3></td>
<td width="20px"><h3 class="Text2">Personel Retension</h3></td>
<td width="20px"><h3 class="Text2">Total Retension</h3></td>
<td width="20px"><h3 class="Text2">Colours</h3></td>
<td width="20px"><h3 class="Text2">Cuts</h3></td>
<td width="20px"><h3 class="Text2">Pre-Booking</h3></td>
<td width="20px"><h3 class="Text2">Time Used</h3></td>
</tr>
<?php
while ($rrows = mysql_fetch_array($stafflist)) {
?>
<tr>
<td name="user_name"><h3 class="Text3"><?php echo $rrows['full_name'];?></h3></td>
<td><h3 class="Text3"><input name="Serviceamount" type="text" size="4" id="Serviceamount"></h3></td>
<td><h3 class="Text3"><input name="servicedate" type="text" size="4" id="servicedate"></h3></td>
<td><h3 class="Text3"><input name="forecast" type="text" size="4" id="forecast"></h3></td>
<td><h3 class="Text3"><input name="productsales" type="text" size="4" id="productsales"></h3></td>
<td><h3 class="Text3"><input name="Clientsthismonth" type="text" size="4" id="Clientsthismonth"></h3></td>
<td><h3 class="Text3"><input name="Personelret" type="text" size="4" id="Personelret"></h3></td>
<td><h3 class="Text3"><input name="Totalret" type="text" size="4" id="Totalret"></h3></td>
<td><h3 class="Text3"><input name="colours" type="text" size="4" id="colours"></h3></td>
<td><h3 class="Text3"><input name="cuts" type="text" size="4" id="cuts"></h3></td>
<td><h3 class="Text3"><input name="prebooking" type="text" size="4" id="prebooking"></h3></td>
<td><h3 class="Text3"><input name="timeused" type="text" size="4" id="timeused"></h3></td>
</tr>
<?php
}
?>
</table>
<input name="doSubmit" type="submit" id="doSubmit" value="Create">
</td></table></form></body></html>
<?php
}
?>
Thank you in advance for any help
$value1 = mysql_real_escape_string(....
$value2 = mysql_real_escape_string(....
$updateServices = mysql_query('INSERT INTO `Services` (`column1`, `column2`)
VALUES (' . $value1 . ', ' . $value2 . ')');
or, using PHP Data Objects (basic security included, like escaping, type casting)
/**
* #var PDO $database
*/
$stmt = $database->prepare('INSERT INTO `Services` (`column1`, `column2`)
VALUES (:value1, :value2)');
$stmt->bindValue(':value1', $value1);
$stmt->bindValue(':value2', $value2);
if($stmt->execute() == true && $stmt->rowCount() > 0)
{
// whatever to do on success
return true;
}

Categories