Drop Down populated by mysql selection not posting - php

I'm new to PHP here and struggling with an issue. I've created a form to submit information to a powershell script on the back end. I have one drop down field (telephone) that is pulling from mysql and populating. That part is working great. The issue that I am having is that when i go to post the data and pass it to the powershell script that field (telephone) is being passed as blank. I'm not sure where I may have caused the issue and looking for some help here.
Here is what I have. I'd like to keep it in PHP if possible.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<?php
// If there was no submit variable passed to the script (i.e. user has visited the page without clicking submit), display the form:
if(!isset($_POST["submit"]))
{
?>
<form name="testForm" id="testForm" action="BTAM2.php" method="post" /> <br />
First Name: <input type="text" name="SAMname" id="SAMname" maxlength="20" /><br /> <br/>
Telephone Number:
<?php
$con=mysqli_connect("localhost","root","","it");
//============== check connection
if(mysqli_errno($con))
{
echo "Can't Connect to mySQL:".mysqli_connect_error();
}
//This creates the drop down box
echo "<select name='phonenum' id='phonenum'>";
echo '<option value="0">'.' '.'</option>';
$query = mysqli_query($con,"Select `btphonenumber` from `btphone` where `btuser` = ' '");
$query_display = mysqli_query($con,"SELECT * FROM btphone");
while($row=mysqli_fetch_array($query))
{
echo "<option value='". $row['id']."'>".$row['btphonenumber']
.'';
}
echo '</select>';
?><br /> <br />
<input type="submit" name="submit" id="submit" value="Create User" />
</form>
<?php
}
// Else if submit was pressed, check if all of the required variables have a value:
elseif((isset($_POST["submit"])) && (!empty($_POST["SAMname"])))
{
// Get the variables submitted by POST in order to pass them to the PowerShell script:
$firstname = $_POST["SAMname"];
$telenumber = $_POST["phonenum"];
var_dump($_REQUEST);
}
// Else the user hit submit without all required fields being filled out:
else
{
echo "Sorry, you did not complete all required fields. Please go back and try again.";
}
?>

I've resolved my own issue. in the line
echo "<option value='". $row['id']."'>".$row['btphonenumber']
I should have had
echo "<option value='". $row['btphonenumber']."'>".$row['btphonenumber']

Related

variable replace in form in php and html

I am trying to make a php program where user will input $name but it will replace with its variable. The code is given bellow
<form method="post" >
<textarea type="text" name="preview"></textarea>
<input type="submit" value="preview"></input>
<form>
<?php
$name="Nahid";
echo $_POST['preview'];
?>
I am expecting an output like: My name is Nahid.
when user will input: My name is $name.
I modified the code to help achieve the stated objective of the program.
I also added some comments to help you understand the code.
I replaced <textarea> with an input field, and I changed the name from 'preview' to 'name' to avoid confusion.
<!DOCTYPE html>
<html>
<head>
<title>Name Preview</title>
</head>
<body>
<form action= "" method="post">
<label>Name: </label>
<input type="text" name="name">
<input type="submit" name="submit" value="PREVIEW"></input>
<form>
</body>
</html>
<?php
// Ensure that form is submitted
if(isset($_POST['submit']))
{
// Ensure that a name is entered
if (isset($_POST['name']) && !empty($_POST['name']))
{
// Store user's input in a variable
$name = htmlentities($_POST['name']);
// Display name
echo "<p>";
echo "My name is " . $name;
echo "</p>";
}
else
{
// Display notification if no name is entered.
echo "Please enter your name";
}
}
?>
Hope that is helpful.
if you enter your name in text area and submit form so you will see entered text
if you enter same value 'Nahid' in text area so you think $name is showing instead of $_POST['preview']
you can concat $name with $_POST['preview'] using dot
test folooowing code:
echo $name . ' <br> ' . $_POST['preview'];
please enter another name in textarea to test it

Adding records to MySQL using PHP and page security

This is an effort to create a PHP page to add data to a table. I am getting a parsing error on line 79 so I have been fiddling with it for a while:
Parse error: syntax error, unexpected T_STRING in /home/sharah19/dev.rahmaninet.org/new.php on line 79
Also I have another question: Whats the easiest way to make this page secure? So only users who are authenticated through the login page can add a record?
The contents of new.php:
<?php
/*
NEW.PHP
Allows user to create a new entry in the database
*/
// creates the new record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($first, $last,$email, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Add a New Record</title>
<link href="rahmani.css" rel="stylesheet">
</head>
<body>
<div id="main">
<h1>RahmaniNET CRM System</h1>
<?php include("header.php"); ?>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>First Name: *</strong> <input type="text" name="first_name" value="<?php echo $first_name; ?>" /><br/>
<strong>Last Name: *</strong> <input type="text" name="last_name" value="<?php echo $last_name; ?>" /><br/>
<strong>email: *</strong> <input type="text" name="email" value="<?php echo $email; ?>" /><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$first_name = mysql_real_escape_string(htmlspecialchars($_POST['first_name']));
$last_name = mysql_real_escape_string(htmlspecialchars($_POST['last_name']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
// check to make sure both fields are entered
if ($first_name == '' || $last_name == ''|| $email == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($first_name, $last_name, $email, $error);
}
else
{
// save the data to the database
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email' )
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('$first', '$last','$email', $error);
}
?>
The error comes from the lack of a closing quote on your MySQL query:
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email') or die(mysql_error());
It should be:
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email'") or die(mysql_error());
Also you ask:
Also I have another question: Whats the easiest way to make this page
secure? So only users who are authenticated through the login page can
add a record?
If you are using Apache then you should you use Apache AuthType Basic. More details are here. Details under “Getting it working.”
You are missing a double quote in your sql string:
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email' )

PHP form - on submit stay on same page

I have a PHP form that is located on file contact.html.
The form is processed from file processForm.php.
When a user fills out the form and clicks on submit,
processForm.php sends the email and direct the user to - processForm.php
with a message on that page "Success! Your message has been sent."
I do not know much about PHP, but I know that the action that is calling for this is:
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
How can I keep the message inside the form div without redirecting to the
processForm.php page?
I can post the entire processForm.php if needed, but it is long.
In order to stay on the same page on submit you can leave action empty (action="") into the form tag, or leave it out altogether.
For the message, create a variable ($message = "Success! You entered: ".$input;") and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>.
Like this:
<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
There are two ways of doing it:
Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action to the current page URL.)
if(isset($_POST['submit'])) {
// Enter the code you want to execute after the form has been submitted
// Display Success or Failure message (if any)
} else {
// Display the Form and the Submit Button
}
Using AJAX Form Submission which is a little more difficult for a beginner than method #1.
You can use the # action in a form action:
<?php
if(isset($_POST['SubmitButton'])){ // Check if form was submitted
$input = $_POST['inputText']; // Get input text
$message = "Success! You entered: " . $input;
}
?>
<html>
<body>
<form action="#" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
You have to use code similar to this:
echo "<div id='divwithform'>";
if(isset($_POST['submit'])) // if form was submitted (if you came here with form data)
{
echo "Success";
}
else // if form was not submitted (if you came here without form data)
{
echo "<form> ... </form>";
}
echo "</div>";
Code with if like this is typical for many pages, however this is very simplified.
Normally, you have to validate some data in first "if" (check if form fields were not empty etc).
Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.
You can see the following example for the Form action on the same page
<form action="" method="post">
<table border="1px">
<tr><td>Name: <input type="text" name="user_name" ></td></tr>
<tr><td align="right"> <input type="submit" value="submit" name="btn">
</td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$name=$_POST['user_name'];
echo 'Welcome '. $name;
}
?>
simple just ignore the action attribute and use !empty (not empty) in php.
<form method="post">
<input type="name" name="name">
<input type="submit">
</form>
<?PHP
if(!empty($_POST['name']))
{
echo $_POST['name'];
}
?>
Try this... worked for me
<form action="submit.php" method="post">
<input type="text" name="input">
<input type="submit">
</form>
------ submit.php ------
<?php header("Location: ../index.php"); ?>
I know this is an old question but since it came up as the top answer on Google, it is worth an update.
You do not need to use jQuery or JavaScript to stay on the same page after form submission.
All you need to do is get PHP to return just a status code of 204 (No Content).
That tells the page to stay where it is. Of course, you will probably then want some JavaScript to empty the selected filename.
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)

Stay on current page after POST data

i have form which genrate from a specific search button.the newly generated form has several form wich can update it's own data
how to doing such a update without any affect to current page.
because of search result and search parameter should not be change.
eventually question in sort, give me an idea to "update each record based on query search while displaying it'.
ex:
<pre>
**name:[** k% **] branch:[** acc **] SEARCH** >>>>search form
EMPID | NAME | BRANCH | EDIT |
1 | kamal | acc | edit | >>>>>>dynamicaly generated form based query serch
2 | kapila | acc | edit | >>>>>>dynamicaly generated form based query serch
</pre>
thank you..
here my try
<?php
session_start();
include("../../config/config.inc.php");
?>
<!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=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="../../css/tbl.css"/>
<script type="text/javascript" src="../../jquery/formControll.js"></script>
<script type="text/javascript">
function autoSubmit(){
document.forms['searchForm'].action=SCRIPT_NAME;
document.forms['searchForm'].submit();
alert("done");
return true;
}
</script>
<title>OT Detail</title>
</head>
<body>
<?php
$errors = array();
$htmlcode="";
$me = $_SERVER['PHP_SELF'];
if(isset($_GET["invalid"])) //that means this is a redirected session
{
//form data default value initialization goes here
$Year=$_GET["Year"];
$Month=$_GET["Month"];
echo "<br><br><strong>ERROR: ";
foreach($_GET["errors"] as $k=>$v)
echo "<font color=red >".$v."</font>";
echo "</strong>";
}
else//if $_GET["invalid"] is not define then this is not redirecting session
{
//form data default value initialization goes here
$Year=date("Y");
$Month=date("m");
}
//for sequrity reasons we check weather 'REQUEST_METHOD'== 'POST'
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//server side manual form validation goes here
if (!$_POST['Year'])
$errors[0] = "Year ?";
if (!$_POST['Month'])
$errors[1] = "Month?";
if (count($errors)>0){
header("Location:setOtPermit.php?invalid=1&Year=".$_POST["Year"]."&Month=".$_POST["Month"]."&errors=".$errors);
exit;
}
else //no error
{
//get post array
foreach($_POST as $key=>$value){
if ($key!="Search"){
$value=htmlentities(stripslashes(strip_tags($value)));
${$key}=$value;
}//if $key
}//4e
//******* building sql for search
$sql="SELECT branch FROM ".$tbl_name2." WHERE empNo=".$_SESSION['resideFigure'];
$result=mysql_query($sql,$con)or die("cannot query");
$row=mysql_fetch_array($result,MYSQL_NUM);
$myBranch="Finance";//$row[0];
//echo $myBranch;
$sql="select * from ".$tbl_name4." e
where e.empNo in(
select d.empNo
from ".$tbl_name2." d
where d.branch='".$myBranch."') and e.empNo=000123 and e.permitMonth=1";
//echo $sql;
$result=mysql_query($sql,$con)or die("cannot query");
//*** search result feching into table goes here
if(mysql_num_rows($result)>0)
{
$htmlcode.="<center><table id='myDisplay'>";
$htmlcode.="<tr>";
for($i = 0; $i < mysql_num_fields($result); $i++) {
$htmlcode.="<th>".mysql_field_name($result,$i)."</th>";
}//for mysql_num_fields
$htmlcode.="</tr>";
$rowAlter=true;
while($row = mysql_fetch_assoc($result))
{
$htmlcode.="<form name='myform[]' method='POST' action='".$me."' onSubmit='return validateForm()'>";
if($rowAlter)
{$htmlcode.="<tr>";
$rowAlter=false;
}
else
{
$htmlcode.="<tr class='alt'>";
$rowAlter=true;
}
foreach($row as $k=>$v)
{
$htmlcode.="<td><input type='text' name='mydata[]' value='".$v."'></td>";
}//4e
$htmlcode.="<td><input type='submit' name='Update' onclick='autoSubmit()' value='Update'></td></tr>";
}//while
$htmlcode.="</form></table></center>";
}
else//when data not fetched
{
echo "<br><br><font color=blue >It seems to be you have not done any OT Permission!</font>";
}
}//else error count
}//if $_SERVER
?>
<center><form name="searchForm" method="POST" action="<?php echo strip_tags($me);?>" onSubmit="return validateForm()">
<table border="0" cellspacing="0" cellpadding="2">
<tr>
<td>Year</td><td><input type="text" name="Year" value="<?php echo $Year;?>"></td>
<td>Month</td><td><input type="text" name="Month" value="<?php echo $Month;?>"></td>
<td><input type="submit" name="Search" value="Search"></td>
<td><input type="reset" name="Reset" value="Reset"></td>
</tr>
</table>
</form></center>
<script type="text/javascript">SetHandlers()</script>
<?php
//display result as table
if (count($errors)==0)
echo $htmlcode;
//for sequrity reasons & confirm to dynamic form are submited we check weather 'REQUEST_METHOD'== 'POST'
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['Update'])){}
echo "if success i can do this its not difficult,but things is result desapper";
?>
</body>
</html>
I like to post the information back to the same page. You can use php to handle the post at the start of the script and then you already have all the data you submitted so you can populate the search field and everything using that data.
Alternatively don't submit the form but perform an ajax query. That way your current page remains unchanged.

Problem with PHP 'PHP_SELF'

I am having a bit of trouble. It does not seem to be a big deal, but I have created a page that the user can edit a MySQL database. Once they click submit it should process the php within the if statement and echo 1 record updated. The problem is that it does not wait to echo the statement. It just seems to ignore the way I wrote my if and display the whole page. Can anyone see where I went wrong.
<!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></title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php require("serverInfo.php"); ?>
<?php
$res = mysql_query("SELECT * FROM cardLists order by cardID") or die(mysql_error());
echo "<select name = 'Cards'>";
while($row=mysql_fetch_assoc($res)) {
echo "<option value=\"$row[cardID]\">$row[cardID]</option>";
}
echo "</select>";
?>
Amount to Add: <input type="text" name="Add" />
<input type="submit" />
</form>
<?php
if(isset($_POST['submit']));
{
require("serverInfo.php");
mysql_query("UPDATE `cardLists` SET `AmountLeft` = `AmountLeft` + ".mysql_real_escape_string($_POST['Add'])." WHERE `cardID` = '".mysql_real_escape_string($_POST['Cards'])."'");
mysql_close($link);
echo "1 record Updated";
}
?>
<br />
<input type="submit" name="main" id="main" value="Return To Main" />
</body>
</html>
if(isset($_POST['submit']));
1) Should not have a semicolon after it.
2) $_POST['submit'] is not set. You have to set a name on your submit button and give it a value. Just setting the type to 'submit' does not return a value for $_POST['submit'] in PHP.
You've got a ; after your if statement.
I noticed that you have two submit buttons and I assume that you are using the first one.
Try giving it a name="submit" and a value too.
Of course it doesnt. PHP runs in the server side, not in browser!
Open your page source. There is no PHP. Nothing to wait.
You need another page to send your form to.
And it is a big deal. It's a cornestone of understanding how the web does work.

Categories