PHP code inside HTML value attribute - php

there!
I want to do a database search and display the result back to the user in a pre-populated HTML form.
I located the exact part in the code that is not working but I can't understand why PHP is not picked by the server. I'm using UwAMP.
To illustrate the problem here is my short snippet of code that I need help with:
<form id="st_reg" action="" method="POST">
Student Number:
<input type="number" name="s_num" min="1000000" max="3000000" > </br>
<input type="Submit" value="Search">
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['s_num'])){
$errors[] = "You forgot to enter the Student No!";
}
else{
$st_no = trim($_POST['s_num']);
}
if(empty($errors)){
//Open database connection
require('../../connect_to_database/mysql_connect.php');
//Check if the student is already in the database
$query = "SELECT * FROM student WHERE student_no = $st_no";
//Run the query
$result = mysqli_query($db_connection,$query);
if(!$result){
echo "The student does not exist!";
echo"Please <a href='index.html'>go back</a> and choose another action!";
}
elseif($result){
echo "<h2>Student Details:</h2>";
while($row = mysqli_fetch_array($result)){
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> ">
AND the PHP code inside VALUE ATTRIBUTE is not executing when it should in reality. Don't bother about GLOBAL php tags not being closed 'cause they are in the file (I'm not that dump).
Please note all this code is inside a .php file with HTML code. This is a just the processing part after the form is submitted. I saved my time by using single-quotes for echo and escaped the sigle-quotes along the way where DB access was required. I tried curly brackets around variables, echo with double-quotes escaping double-qoutes within it but none of these attempts were successful. This is strange because I can perfectly echo $row['student_no'] outside of this context and is running fine.
I also looked at similar questions on this website. They were close but none of them had nearly to this context. I am open to any suggestions and better than that solutions.

echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> ">
should look like this:
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="' . (isset($row['student_no']) ? $row['student_no'] : '') . '">
CONTINUATION OF STRING...

The following will do what you want.
value="<?= (isset($row["student_no"]) ? $row["student_no"] : "") ?>"
You don't need to worry about all of the escaping when you're inside the PHP chunk already.

Related

Populate textbox with table entry plus one?

I am trying to increment project number based on the last entry. The the primary key PROJECTNOID auto-increments but is not the same format as the project number (Ex: PROJECTNOID = 1 and Project Number = 19000). I don't want this to be a dropdown box even though some of my code shows the opposite.
<?php
connect = mysqli_connect("**", "**", "**", "**");
$query4 = "SELECT PROJECTNOID, ProjectNumber FROM tblProjects ORDER BY
PROJECTNOID";
$result4 = mysqli_query($connect,$query4);
$options4 = "";
while($row4 = mysqli_fetch_row($result4);){
$options4 = $options4."<input value=$row4[0]$row4[1]</input>";
}
?>
Here is the html textbox:
<label for="txtfield">Project Number</label>
<!--<input type="text" id="reqtxtfield" name="projectnumber"
value="<?php ?>" readonly/>-->
<?php echo $options4;?>
But it would look like how you had it but instead of '1' inside the
box it would display '19000' and there would be nothing outside of the
box other than the label "Project Number". As far as i'm aware you can
assign a value to the text box, regardless of whatever the input is. I
would like it to display the value from one field name but actually
contain the value from a different field name. Both are in the same
table of course.
OK - gotcha. Unfortunately, you cannot do that. A textbox can only have one value and the user is always free to change that value, even if you make it read-only. You can test that out by using the developer toolbar in your browser. Probably a good time to mention that all user input should be considered dangerous and you should never trust it. Once they have submitted the form you need to verify it.
What I would recommend in your case is to use a hidden <input> which contains the value you actually want to submit; projectnoid. You can then display the Project Number in any manner you choose.
<form>
<h1>Project Number: 19000</h1>
<input type="hidden" name="projectnoid" value="1">
<input type="submit" name="submit">
</form>
To generate this, you would:
<?php
while($row4 = mysqli_fetch_row($result4)){
$projectnoid = $row[0];
$projectNumber = $row[1];
echo '<h1>' . $projectNumber . '</h1>';
echo '<input type="hidden" name="projectnoid" value="'. $projectnoid .'">
}
PHP:
<?php
$query_5 = "SELECT MAX(ProjectNumber) FROM tblProjects;";
$result_5 = mysqli_query($conn, $query_5);
$row_5 = mysqli_fetch_array($result_5);
$nextproject=$row_5['MAX(ProjectNumber)']+1;
?>
HTML:
<html>
<form class="myform" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>" method="post">
<label for="txtfield">Project Number</label>
<input type="text" id="reqtxtfield" name="projectnumber" value="<?php echo $nextproject ?>" readonly/><br>
After running successful insert query:
echo "<meta http-equiv='refresh' content='0'>"; //REFRESH PAGE TO UPDATE PROJECT NUMBER

Displaying the form if the post is empty or result if it has already been submitted

This is my first post and I'm complete beginner so please be gentle :)
I'm trying to create a form that after submitting an account name would check and return a CNAME of the host (account+domain.com)
The problem is that I want to do it all on the same website so it will either display the form if nothing has been posted or display the result otherwise.
This is what I've created, it seems that I'm not calling the POST correctly, but I can't really get what am I doing wrong.
Please help
<?php
if(isset($_POST[DomainSubmit])){
$AccountName = $_POST[ClientDomain];
$CName = dns_get_record($AccountName."domain.com", DNS_CNAME);
echo '<h1>'.$CName.'<h1>';
}
echo'<form action="index.php" method="POST" ">
<input type="text" name="ClientDomain">
<input type="submit" name="DomainSubmit">
</form>'
?>
Try to add else so it will be displayed one or another stuff
<?php
if(isset($_POST['DomainSubmit']) && isset($_POST['ClientDomain'])){
$AccountName = $_POST['ClientDomain'];
$CName = dns_get_record($AccountName."domain.com", DNS_CNAME);
echo '<h1>'.$CName.'<h1>';
} else {
echo'<form action="index.php" method="POST" ">
<input type="text" name="ClientDomain">
<input type="submit" name="DomainSubmit">
</form>'
}
?>
Edit:
You forgot to properly write array POST (missing quotes)
$_POST[DomainSubmit]
And it should be
$_POST['DomainSubmit']

Two forms with multiple submit buttons in single PHP file

I am trying to write a dynamic form using PHP. I'd like to have a single webpage that contains two forms:
The upper form allows to search for an element in the mysql database, e.g., for a name
The lower form shows the data that is associated with this name in the database
If I press on the "Search" button of the upper form, then the the lower form is shown and the text fields are filled with data from the database that belong to this name. If I change the user name to some other value and press again "Search", then the data that is associated with the new record is shown and so on.
The lower form also has a button "Update" which allows to transfer changes made to the text boxes (in the lower part) to the database.
Now, I have the following problem: In my script I set initially the value of name (from the upper form) to "". When I then press the "Search" button, then the lower part of the form is shown and the corresponding data is shown in the lower part. When I then press the "Update" button, then the text field associated with name is set to the empty string. This is because in my script I set initially name to the "". I'd like that in this case the data entered in the upper form is not changed, i.e., it stays the same.
I guess, I am missing something here. There is probably an easy solution for this and I am doing something fundamentally wrong. It'd be great if you could help me.
That's what I tried... I deleted lots of details, but I guess that can give you an idea what I am trying to do. Notice that the whole code is in the file update.php.
<?php
function search_bus($mysql, $name)
{
// do some stuff here...
}
function update_bus($mysql, $b_id)
{
// do some stuff here...
}
// some global variables
$b_id = 0;
$username = ""; // username of business
// get b_id that corresponds to username
if (isset($_REQUEST['search']))
{
$b_id =0; // business id
if (isset($_POST['user']))
{
$username = $_POST['user'];
$b_id = search_bus($mysql, $username);
}
}
elseif(isset($_REQUEST['update']))
{
update_bus($mysql, $b_id);
}
?>
<h2>Search:</h2>
<form name="search_bus" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Username: <input type="text" name="user" value="<?= htmlentities($username) ?>"/>
<input type="submit" value="Suchen" name="search"/>
</form>
<?php
if($b_id != 0)
{
?>
<h2>Data:</h2>
<form name="business_design" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<-- some form follows here -->
<?php
}
?>
I think what you're missing is to create a HTML Hidden field to keep the value of Name variable.
<input type="hidden" name="name" value="<?php print $nameVar ?>" />
Add this input to both forms so you can keep the value no matter what button the user clicks.
Hope this helps.
Adding code to verify the
<h2>Search:</h2>
<form name="search_bus" method="post"
action="<?php echo $_SERVER['PHP_SELF'];?>">
Username: <input type="text" name="user" value="<?= htmlentities($username) ?>"/>
<input type="hidden" name="b_id" value="<?php print $b_id?>" />
<input type="submit" value="Suchen" name="search"/>
</form>
<?php if($b_id != 0) { ?>
<h2>Data:</h2>
<form name="business_design" method="post" action="<?php echo $_SERVER['PHP_SELF'];>">
<input type="hidden" name="b_id" value="<?php print $b_id?>" />
<-- some form follows here -->
<?php } ?>
Dont initialize $b_id if it already comes into the http request.
if (!isset($_POST['b_id']))
{
$b_id = 0;
}
else
{
$b_id = $_POST['b_id'];
}
This way you can alway remember the last selected value of b_id.
Hope this can help you.

WAMP - PHP/MySQL - Why is my POST call getting mangled

EDIT: Mangling is fixed - primary issue appears to be the php/mysql connection
In an attempt to learn how to use a MySQL db on a webpage, I'm following a basic tutorial for connecting to a MySQL instance via PHP (all managed through WAMP2)
The tutorial: http://www.freewebmasterhelp.com/tutorials/phpmysql/4 uses a PHP_SELF method (that I understand is now depreciated).
I've tried a few other suggestions that I've found doted around, but I can't find resolution to the following error I see in the apache log:
(20024)The given path is misformatted or contained invalid characters: Cannot map POST /%3C$SEARCH.PHP%3E HTTP/1.1 to file, referer: http://localhost/search.php
This error prevents the HTML page from being returned, and I get a 403 error in my browser
It appears that this line of HTML/PHP is the culprit:
<form name="search" method="post" action="<?=$PHP_SELF?>">
I have seen suggestions that say to either turn on short_open_tag (a bad idea according to some), change the
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
I can't get any of these methods to work, and wondered if anyone could let me know what dumb thing I've missed this time...
The whole php file I am using is:
<?php
// // This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
include("dbinfo.php");
mysql_connect($host,$username,$password);
mysql_select_db("database") or die(mysql_error());
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM main WHERE upper($field) LIKE'%$find%'");
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo $result['Item1'];
echo " ";
echo $result['Item2'];
echo "<br>";
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
<h2>Search</h2>
<form name="search" method="post" action="<?=$PHP_SELF?>">
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="item1">Item1</option>
<Option VALUE="item2">Item2</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
Avoid shortags, they are out of date, make sure to be using:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What does the form's html look like when you load the page?
EDIT:
After reviewing my answer I'd like to rephrase it a bit, as they are not "out of date" per say, but they generally do cause problems (for those that don't know how to set up php fully), so for beginners I'd suggest avoiding them.
I'm sure this is probably bad design, but I've always just hard-coded the script name in cases like that (so, just action="search.php").
The $_SERVER['PHP_SELF'] variable contains the full path of your php script, for example:
/your_server_path/your_file_name.php
Obviously, when launched, your script can't find the file because it's looking for something like
/your_server_path/your_server_path/your_file_name.php
Try to do something like this:
<form method="post" action="<?='http://localhost'.$_SERVER['PHP_SELF']?>">

PHP get input , radio , selection data and insert into MySQL table

i'm new to php , i have been searching for a tutorial regarding inserting form's input(text) , radio and selection data to MySQL database's table using php. i found some tutorials but most are confusing. So i decided to ask.
Okay here's what i want to do. I have a form which have two types of input and a selection
1. input type text
2. input type radio
3. selection
Here's the HTML code :
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
<input type="submit" name="submit" value="Submit">
</form>
I have set the form action to blank because the php code will be in the same file as the HTML (it's a php file btw)
MySQL table : info
structure :
1. name
2. class
3. agree
I want the php code to insert myname into name , selection's selected data into class , radio selected data into agree
P/S Yes i have added a connect to database php script , i just want to know how to get the form data into mysql.
Can someone write a php code example on how can i do this?
Thanks and have a nice day . I hope i have provided enough information. Thanks again if you help.
1. There is a problem with your radio element. The name should be the same for both options.
It should be like this:
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
2. You can access everything in the $_POST array, since you are using the method post for the form.
$name = $_POST['myname'];
$selection = $_POST['selection'];
$agree = $_POST['agree'];
3. If you are not using parametrized SQL with a library such as PDO, MySQLi, etc... you must always escape the data, which will be used in query using mysql_real_escape_string(), in order to protect against SQL injection.
This would be a sample code, to do the escaping and the query.
// write a function somewhere, to use as a shortcut
// for escaping data which will be used in a query
function sql_escape($str){
return "'".mysql_real_escape_string($str)."'";
}
// build the query
$query = sprintf('INSERT INTO table_name(name, class, agree) VALUES(%s, %s, %s)',
sql_escape($_POST['myname']),
sql_escape($_POST['selection']),
sql_escape($_POST['agree']));
// finally run it
$result = mysql_query($query);
I've taken it a little further here, there is still plenty more that can be done and many way's to do it, for instance you could extend the $errors array to include a field id and then highlight the HTML form field so the user can see exactly where they went wrong.
Considering your form is fairly simple you would not need this.
#Shef's code would certainly do the job but I thought you might be interested in some more.
<?php
// check the form has been submitted
if (isset($_POST['submit'])) {
// escape the form fields and assign them to variables
// validate myname to ensure the user entered data
if (isset($_POST['myname']) && $_POST['myname']!='') {
$myname = mysql_real_escape_string($_POST['myname']);
} else {
// create an error variable array to store errors to display
$errors[] = 'Please enter your name';
}
// no need to validate selection here as it alway's has a value
$classtype = mysql_real_escape_string($_POST['selection']);
// validate agree unless you want to add 'checked' to one of the values
if (isset($_POST['agree']) && $_POST['agree']!='') {
$agree = mysql_real_escape_string($_POST['agree']);
} else {
$errors[] = 'Please tell us if you agree?';
}
//if errors found tell the user else write and execute the query
if ($errors) {
$message = '<p class="error">We found a problem:</p><ul>';
foreach($error as $msg){
$message .= '<li>'.$msg.'</li>';
}
$message .= '</ul><p>Please fix the error/s to continue.</p>';
} else {
// write the query
$query = "INSERT INTO table (myname, classtype, agree) VALUES ";
$query .= "('$myname','$classtype','$agree')"
// run the query
mysql_query($query);
$message = '<p class="sucessful">Thanks '.htmlspecialchars($myname).'. Your selection has been saved.</p>';
}
}
// print the message
// show the variables in the form field so they don't need re-input
if ($message!='') { echo $message; }
?>
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="<?php echo htmlspecialchars($myname) ?>" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A"<?php if ($classtype=='A') { echo ' selected'; } ?>>A</option>
<option value="B"<?php if ($classtype=='B') { echo ' selected'; } ?>>B</option>
<option value="C"<?php if ($classtype=='C') { echo ' selected'; } ?>>C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"<?php if ($agree=='Yes') { echo ' checked'; } ?>> or
<input type="radio" name="agree" value="No"<?php if ($agree=='No') { echo ' checked'; } ?>>
<input type="submit" name="submit" value="Submit">
</form>
Also: #sqwk, Don't point people towards w3schools, see this: http://w3fools.com/
Check whether there is any data in the $_POST array and get the values from it.
Have a look hereā€”the second example down is what you need: http://www.w3schools.com/php/php_mysql_insert.asp
(You do have to make the changes that Shef suggested, though.)
Also remember to check your data-integrity, otherwise people could use your insert to run malicious code.
check this simple example:
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Sname: <input type="text" name="sname" />
<input type="submit" />
</form>
after you submit form, you can take name and sname.
welcome.php::
<?php
$name= $_POST["name"];
$sname= $_POST["sname"]; ?>
now you can use this variables as if you want.

Categories