Save runtime created textbox value in database table - php

I have create one form in that form contain one textbox and one add another button & save button,on click event of add another button new textbox is generated but when i click on save button newly generated textbox value can not be save into database please anyone can guide me
Here is my code:
<?php
global $Hostname;
global $Username;
global $Password;
global $Database_name;
function getConnection()
{
$Hostname = "localhost";
$Username ="root";
$Password ="";
$Database_name="labdata";
$oMysqli = new mysqli($Hostname,$Username,$Password,$Database_name); //create connection object.
return($oMysqli);
}
if(isset($_POST['submit']))
{
$TestParameters = $_POST['testparameters'];
$InsertQuery = "INSERT INTO test_table VALUES('$TestParameters')";
$oMysqli=getConnection();
$oMysqli->query($InsertQuery);
//print_r($InsertQuery);exit();
if(!$InsertQuery)
{
die('Could not enter data:' . mysql_error());
}
}
?>
<html>
<head>
<title>TestData</title>
<script type="text/javascript">
function create_row()
{
var newtr=document.createElement("tr");
var newtd=document.createElement("td");
var output="<input type=\"text\" name=\"testparameters\">";
newtd.innerHTML=output;
newtr.appendChild(newtd);
document.getElementById("table1body").appendChild(newtr);
}
</script>
</head>
<body>
<form name="testdetails" method="post" target="_self" action="<?php $_PHP_SELF ?>">
<label for="Testparameter">Testparameter</label>
<input type="text" name="testparameters"></input>
<table id="table1body">
<tr>
<td><input type="button" name="button" value="Add Test Parameter" onclick="create_row()">
</tr>
</table>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>

Try this
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());
}
}

<?php
$n=0;
if(isset($_GET['button1']))
{
$n++;
echo "hai";
echo "<br><input type='text' name='+i+'>";
}
if(isset($_POST['submit']))
{
$con=mysqli_connect("localhost","root","","ram123");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//print_r($_POST);
$count = count($_POST);
for($x=1;$x<$count;$x++){
$sql="INSERT INTO names (name)VALUES('$_POST[$x]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
/*
$sql="INSERT INTO names (name)VALUES('$_POST[1]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
*/
}
?>
<html>
<head>
<title>TestData</title>
<script type="text/javascript">
var i = 1;
function changeIt()
{
my_div.innerHTML = my_div.innerHTML +"<br><input type='text' name="+i+">";
i++;
}
</script>
</head>
<body>
<form name="testdetails" method="post" target="_self" action="<?php $_PHP_SELF ?>">
<input type="button" name="button1" value="Add Test Parameter" onclick="changeIt()">
<input type="submit" name="submit" value="submit">
<div id="my_div"></div>
</form>
</body>
</html>

you are using same name for all textbox
<input type="text" name="testparameters"></input>
use array for this,from this you will get value of all your textbox
<input type="text" name="testparameters[]"></input>
Code for iterating textbox value
$length = count($_POST['testparameters']);
for($i=0; $i< $length; $i++){
echo $_POST['testparameters'][$i];
}

Related

Data not inserting in database when submitted

I've set up a form to insert data into a database. It's connected to it fine and can display records with no issues. However, when I want to insert data I click the submit button it removes it from the form but doesn't insert it into the db. I've tried rewriting it about 3 times now using 2 different databases but just can't figure out where I'm going on.
<html>
<head>
</head>
<body>
<form action="input.php" meathod="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>
<?php
if( isset($_POST['submit'])){
//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);
if($conn){
echo 'connected';
}
else {
die('failed to connect');
}
$sql="INSERT INTO users(username,password) VALUES ('$_POST[username]','$_POST[password]')";
mysql_query($sql,$conn);
mysqli_close($conn);
};
?>
</body>
</html>
You have few typos "meathod=post" should be method="post",mysql_query($sql,$conn) should be mysqli_query($conn,$sql) and mysqli_select_db("test",$conn) should be mysqli_select_db($conn,"test")
<html>
<head>
</head>
<body>
<form action="input.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>
<?php
if( isset($_POST['submit'])){
//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db($conn,"test");
if($conn){
echo 'connected';
}
else {
die('failed to connect');
}
$sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";
mysqli_query($conn,$sql);
mysqli_close($conn);
};
?>
</body>
</html>
you have written "meathod=post" instead of "method=post"
also I have changed
$sql="INSERT INTO users(username,password) VALUES ('$_POST[username]','$_POST[password]')";
to
$sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";
this style much more better
<html>
<head>
</head>
<body>
<form action="lol.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>
<?php
if( isset($_POST['submit'])){
//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);
if($conn){
echo 'connected';
}
else {
die('failed to connect');
}
$sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";
mysql_query($sql,$conn);
mysqli_close($conn);
};
?>
</body>
</html>
I think problem is here
mysql_query($sql,$conn);
Replace with
mysqli_query($conn,$sql);
I hope this code will help you
<html>
<head>
</head>
<body>
<form action="input.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>
<?php
if( isset($_POST['submit'])){
//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);
if($conn){
echo 'connected';
}
else {
die('failed to connect');
}
$sql="INSERT INTO users(username,password) VALUES (".$_POST["username"].",".$_POST["password"].")";
mysqli_query($conn,$sql);
mysqli_close($conn);
?>
</body>
</html>

PHP GET not working

Im trying to get the taskid variable from the url:
Long story short the database never updated trying to echo $tasked is blank and im not sure why.
I have looked over all of the suggestions and many different websites I do not see what i'm missing
http://domain.com/ubxtask/addnote.php?taskid=163994
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add Note to Task</title>
</head>
<body>
<form action="" method="post">
<p>
<textarea name="notetoadd" rows="4" cols="50"></textarea>
</p>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
<?php
if ( isset( $_POST['submit'] ) ) {
$servername = "localhost";
$username = "dbusr";
$password = "dbpass";
$dbname = "db";
$notetoadd = $_POST['notetoadd'];
if (isset($_GET["taskid"])) {
//$taskid = $_GET['taskid'];
echo $_GET["taskid"];
//echo $taskid;
}
$sql = "INSERT INTO tasknotestbl (tasknum, tasknote)
VALUES ('$taskid', '$notetoadd')";
if ($conn->query($sql) === TRUE) {
header('Location: http://domain.com/task/tasklist.php');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
You should add the task id to your forms action, or it would be lost, if you submit the form
<form action="addnote.php?taskid=<?php echo $_GET['taskid']; ?>" method="post">
You can add hidden field to form with taskid and use post method:
<?php
if (empty($_GET['taskid'])) {
$taskid = '1';
}else{
$taskid = (int)$_GET['taskid'];
}
// your code submit code and
if (isset($_POST["taskid"])) {
echo $_POST["taskid"];
}
echo '<form action="" method="post">
<p><textarea name="notetoadd" rows="4" cols="50"></textarea></p>
<input type="hidden" name="taskid" value="'.$taskid.'" placeholder="taskID">
<input type="submit" value="Submit" name="submit">
</form>';
?>

WordPress - Select query on specific page

I want to select query in specific page. I created table in database:
First, I added phpexec on plugin for using PHP on page. Then, I tested Select query and it was ok. Finally, I want to create form for checking Serial Number. Here is my code:
<html>
<head>
<title></title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"><br><br>
Serial Number: <input type="Text" Name="Num1"><p>
<input type="Submit" value="Calculate">
</form>
<phpcode>
<?php
if (count($_POST) > 0 && isset($_POST["Num1"])
{
$servername = "localhost";
$username = "******";
$password = "*******";
$dbname = "******";
$serialNum = $_POST["Num1"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Install FROM SN WHERE serial = $serialNum";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["Install"];
}
} else {
echo "no result";
}
$conn->close();
}
?>
</phpcode>
</body>
</html>
Actual output is:
How to solve this issue?
Your form is broken... Try it this way
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>Serial Number: <input type="Text" Name="Num1" value=""></p>
<input type="Submit" value="Calculate">
</form>
hi maybe you can try with this
is a little example and check your values and id, names for values
and sintaxis for html and php
<html>
<head>
<title></title>
</head>
<body>
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<br><br>
Serial Number: <input type="text" name="Num1" id="Num1">
<br><br>
<input type="submit" name="submit" id="submit" value="Calculate">
<br><br>
</form>
<phpcode>
<?php
if(isset($_POST["submit"]))
{
function Conect()
{
if (!($link=mysql_connect("localhost","username","password")))
{
echo "error to conect to database.";
exit();
}
if (!mysql_select_db("databasename",$link))
{
echo "Error to select database.";
exit();
}
return $link;
}//end function Conect
$serialNum = mysql_real_escape_string($_POST["Num1"]);
$query="SELECT Install FROM SN WHERE serial = $serialNum";
$action=mysql_query($query,$link) or die("Error: ".mysql_error());
if(mysql_num_rows($action) > 0)
{
?>
<table border="1">
<tr COLSPAN=2 BGCOLOR="#6D8FFF">
<td>INSTALL</td>
</tr>
<?php
while($row=mysql_fetch_array($action))
{
echo "<tr>".
"<td>".$row["Install"]."</td>".
"</tr>";
}//end while
}
else
{
echo "don't exist recordsfor list ";
}//end if
mysql_close($link);
}//end if
?>
</phpcode>
</body>
</html>
good luck ..!!

How do i include ajax in PHP coding to display data in the same page

I want to display data retrieved from the table in the same page. I know if i use ajax, work becomes easier. But how do i do it? I don't know anything about ajax. My current program is combined with html and php. The program is below. All i want is, when i click the button, the requested action and the data must be displayed in the same page.
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error())
{
die("couldn't connect" . $conn->connect_error());
}
$id = $_POST['Id'];
$name = $_POST['Name'];
$blood = $_POST['BloodGroup'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['insert'])){
$insert = "Insert into ins(Id, name, BloodGroup) values ('$id','$name', '$blood')" ;
if($conn->query($insert) === TRUE) {
echo ("Input data entered successfully");
} else {
echo ("Input data failed to be entered" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['update'])) {
$update = "update ins set Name='".$name."', BloodGroup='".$blood."' where Id='".$id."'";
mysql_query($update);
if($conn->query($update) === TRUE) {
echo ("Data updated successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['delete'])) {
$id = $_POST['Id'];
$delete = "delete from ins where Id='".$id."'";
if($conn->query($delete) === TRUE) {
echo ("Data deleted successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
}
else {
$id = $_POST['Id'];
$retrieve = "SELECT * FROM ins WHERE Id = ".$id;
if ($result=mysqli_query($conn,$retrieve))
{
while ($row=mysqli_fetch_row($result))
{
echo '<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Blood Group</td>
</tr>
<tr>
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>
</tr>
</table>';
//$row[0],$row[1],$row[2]';
}
mysqli_free_result($result);
}}}
$conn->close();
?>
<h2>SELECT THE OPERATION YOU WANT TO PERFORM<h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Id: <input type="text" name="Id" />
Name: <Input type="text" name="Name" />
BloodGroup: <input type="text" name="BloodGroup" /><br /><br />
<input type="submit" name="insert" value="Insert" />
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />
<input type="submit" name="retrieve" value="retrieve" />
</form>
</body>
</html>
$.ajax({
method: "POST",
url: "{php file url}",
data: { name: "John", location: "Boston" } // data list need to sent
})
.done(function( msg ) {
$("#div1").html(result); //#div1 is container element where you want to show output of ajax
});
For more details refer
http://api.jquery.com/jquery.ajax/
Just start learning jquery and jquery ajax
http://api.jquery.com/jquery.ajax/
you will find something like this:
$.ajax({
type: "POST",
url: '', //write your php file url from where you want to get data
data:{}, //to post data like data:{customerName:'xyz'},
success: function(res){ //data returned from your php file
console.log(res); //use data as per your need
}
});

Form Submit Not Being Detected By isset

I am trying to detect a form click using if(isset($_POST['appSelecter'])){ however it seems to not be returning true. This might be to do with the fact that my button click returns to the same page which would loose the form data i had just populated. Can someone confirm if my assumption is correct and if so - how would i need to change this?
Thanks
tried to only paste a sample piece of code to not confuse matters - seems i have made things worse - here is the full flow
<?php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<!--META-->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Client Portal Login</title>
<!--STYLESHEETS-->
<link href="css/style.css" rel="stylesheet" type="text/css" />
<!--SCRIPTS-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<!--Slider-in icons-->
<script type="text/javascript">
$(document).ready(function() {
$(".username").focus(function() {
$(".user-icon").css("left","-48px");
});
$(".username").blur(function() {
$(".user-icon").css("left","0px");
});
$(".password").focus(function() {
$(".pass-icon").css("left","-48px");
});
$(".password").blur(function() {
$(".pass-icon").css("left","0px");
});
});
</script>
</head>
<body>
<!--WRAPPER-->
<div id="wrapper">
<!--SLIDE-IN ICONS-->
<div class="user-icon"></div>
<div class="pass-icon"></div>
<!--END SLIDE-IN ICONS-->
<!--LOGIN FORM-->
<form name="login-form" class="login-form" action="index.php" method="post">
<!--HEADER-->
<div class="header">
<!--TITLE--><h1>Client Portal Login</h1><!--END TITLE-->
<!--DESCRIPTION--><span>Please login to your client portal</span><!--END DESCRIPTION-->
</div>
<!--END HEADER-->
<!--CONTENT-->
<div class="content">
<!--USERNAME--><input name="username" type="text" class="input username" value="Username" onfocus="this.value=''" /><!--END USERNAME-->
<!--PASSWORD--><input name="password" type="password" class="input password" value="Password" onfocus="this.value=''" /><!--END PASSWORD-->
</div>
<!--END CONTENT-->
<!--FOOTER-->
<div class="footer">
<!--LOGIN BUTTON--><input type="submit" name="submit" value="Login" class="button" /><!--END LOGIN BUTTON-->
<!--REGISTER BUTTON--><input type="submit" name="submit" value="Register" class="register" /><!--END REGISTER BUTTON-->
</div>
<!--END FOOTER-->
</form>
<?php
include("application.php");
if(isset($_POST['submit'])){
$username=$_POST["username"];
$password=$_POST["password"];
$userid = logUserIn($username, $password);
if($userid > 0){
$applicationsForUser = getAppInformation($userid);
printUserApplicationSelectionForm($applicationsForUser);
if(isset($_POST['appSelecter'])) {
echo "this is a test message";
}
}
}
function printUserApplicationSelectionForm($applicationsForUser){
echo "<br/>";
echo "<br/>";
echo "<br/>";
echo "<br/>";
foreach ($applicationsForUser as $app) {
?>
<form action="index.php" method="post">
<input type="hidden" name="userid" value="<?php echo $app->getUserid(); ?>">
<input type="hidden" name="name" value="<?php echo $app->getName(); ?>">
<input type="hidden" name="created" value="<?php echo $app->getDateCreated(); ?>">
<input type="hidden" name="invoice" value="<?php echo $app->getInvoice(); ?>">
<input type="hidden" name="comment" value="<?php echo $app->getComment(); ?>">
<input type="submit" name="appSelecter" value="<?php echo $app->getName(); ?>">
</form>
<?php
}
}
function getAppInformation($userid){
$applicationsForUser = array();
$conn = new mysqli('localhost:3306', 'root', '', 'clientportal');
if ($conn->connect_errno > 0) {
die('Could not connect: ' . mysql_error());
}else{
//we have connected to the database
$sql = "SELECT * FROM application WHERE userid = '$userid'";
if(!$val = $conn->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}else{
$index = 0;
while($row = $val->fetch_assoc()){
$userid = $row['userid'];
$name = $row['name'];
$dateCreated = $row['date'];
$invoice = $row['invoiceid'];
$comment = $row['commentsid'];
$application = new Application($userid, $name, $dateCreated, $invoice, $comment);
$applicationsForUser[$index] = $application;
$index++;
}
}
}
$conn -> close();
return $applicationsForUser;
}
function logUserIn($username, $password) {
if(!isset($username) && !isset($password)){
return -1;
}
$result = -1;
//$conn = mysql_connect('localhost', 'web214-admin-ava', 'secondstory');
$conn = new mysqli('localhost:3306', 'root', '', 'clientportal');
if ($conn->connect_errno > 0) {
die('Could not connect: ' . mysql_error());
}else{
//we have connected to the database
$sql = "SELECT * FROM members WHERE username = '$username' AND password = '$password'";
if(!$val = $conn->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}else{
while($row = $val->fetch_assoc()){
$result = $row['id'];
break;
}
}
}
$conn -> close();
return $result;
}
?>
<!--END LOGIN FORM-->
</div>
<!--END WRAPPER-->
<!--GRADIENT--><div class="gradient"></div><!--END GRADIENT-->
</body>
</html>
You have used folowing in the form submit:
onClick="location.href='index.php'" // Making a GET request
This is not submitting the form using POST method. Remove this and it'll work.
Update: There is no submit button with name submit so this condion will not work:
if(isset($_POST['submit']))
Make it:
if(isset($_POST['appSelecter']))
You don't need if(isset($_POST['submit'])) instead use;
if(isset($_POST['appSelecter'])) {
$username=$_POST["username"];
$password=$_POST["password"];
$userid = logUserIn($username, $password);
if($userid > 0){
$applicationsForUser = getAppInformation($userid);
printUserApplicationSelectionForm($applicationsForUser);
}
}
You dont nee this
onClick="location.href='index.php'"
dont do anything , just apply value to button i, i think you have applied already ,
by location.href your request will be send by GET Method in thgis case no form elements sent to the server
if you allow native form submission then all form elements will be sent to server, in case of multiple forms , the only elements sent realted to that submit button form thats it

Categories