I have a form with 4 required inputs. They are being passed into the url if they are missing.
If all 4 is missing it'll look like:
?required[0]=field_name&required[1]=field_email&required[2]=field_number&required[3]=field_desc
If the first one field_name is missing, the array will be pushed forward one, so field_email will be [0]. Which means that the array is always in the 0,1,2,3 order.
What I want to find out is how can I retrieve the information so I can put a red border around the input that is missing? What I need is something like:
while ($i=0,$i<=3,$i++) {
do ($requiredArray[i] == 'field_email') {
echo '<script type="text/javascript">$("#name)".css("border","1px solid #ff0000");</script>';
} while ();
endwhile;
}
You can also use array_search in php as follows :
array_search("field_name",$_GET['required']);
if the value is greater than or equal to zero then you can do the processing.
Like, you can have all the values in a array variable say $required_array and you can use foreach loop like as follows:
foreach($required_array as $val){
if(!(array_search($val,$_GET['required'])>=0)){
echo '<script type="text/javascript">$("#'.$val.')".css("border","1px solid #ff0000");</script>';
}
}
Look into form validation using Jquery it will be simpler and more extensible.
http://docs.jquery.com/Plugins/Validation
Here's an example for a form that preforms the validations on the server-side:
<?php
$first_name = $_GET['fname'];
$last_name = $_GET['lname'];
$email = $_GET['email'];
$submit = $_GET['submit'];
if(empty($first_name) && !empty($submit)){
$missing_fname = 1;
}
if(empty($last_name) && !empty($submit)){
$missing_lname = 1;
}
if(empty($email) && !empty($submit)){
$missing_email = 1;
}
?>
<table><form action="" method="get">
<tr><td>Enter First Name:</td><td><input type="text" id="fname" name="fname" value="<?php echo $first_name; ?>" ></td><td><?php if($missing_fname == 1) echo "<font color='red'>This field is Mandatory!</font>" ?></td></tr>
<tr><td>Enter Last Name:</td><td><input type="text" id="lname" name="lname" value="<?php echo $last_name; ?>" ></td><td><?php if($missing_lname == 1) echo "<font color='red'>This field is Mandatory!</font>" ?></td></tr>
<tr><td>Enter email:</td><td><input type="text" id="email" name="email" value="<?php echo $email; ?>"></td><td><?php if($missing_email == 1) echo "<font color='red'>This field is Mandatory!</font>" ?></td></tr>
<tr><td></td><td><input type="submit" value="submit" name="submit" id="submit"></td></tr>
</form>
</table>
Related
I write a conversion from celsius to fahrenheit and vice versa. The problem is that in the form fields now random values are displayed to me. How to convert this code so that after entering the value, the converted value in the second field appears in the first field?
Is it possible to use only php at all?
if(isset($_POST['fah'])){
$cel=($_POST['fah']+32)/1.8;
}
if(isset($_POST['cel'])){
$fah=($_POST['cel']-32)*1.8;
}
?>
<html>
<body>
<form method="post" action="calc.php">
Fahrenheit: <input id="inFah" type="text" placeholder="Fahrenheit" value="<?php echo $fah; ?>" name="fah">
Celcius: <input id="inCel" type="text" placeholder="Celcius" value="<?php echo $cel; ?>" name="cel">
<input type="submit" value="Calc">
</form>
I want the value entered in the first field to be shown in the second transformed.
You can do all php if you post back to itself. If the page with the input is calc.php
Add an else to set the value to empty string.
if(isset($_POST['fah'])){
$cel=($_POST['fah']+32)/1.8;
} else {
$cel = '';
}
if(isset($_POST['cel'])){
$fah=($_POST['cel']-32)*1.8;
} else {
$fah = '';
}
Try something like this
$cel="";
$fah="";
if(isset($_POST['fah']) && !empty($_POST['fah'])){
$cel=($_POST['fah']+32)/1.8;
}
if(isset($_POST['cel']) && !empty($_POST['cel'])){
$fah=($_POST['cel']-32)*1.8;
}
You can try this example:
$celValue = $_POST['cel'];
$fahValue = $_POST['fah'];
if( ! empty($fahValue)){
$celValue = fahrenheitToCelcius($_POST['fah']);
}
if( ! empty($celValue)){
$fahValue = celciusToFahrenheit($_POST['cel']);
}
function celciusToFahrenheit($cel) {
return ($cel - 32) * 1.8;
}
function fahrenheitToCelcius($fah) {
return ($fah + 32) / 1.8;
}
?>
<html>
<body>
<form method="post" action="calc.php">
Fahrenheit: <input id="inFah" type="text" placeholder="Fahrenheit" value="<?php echo $celValue; ?>" name="fah">
Celcius: <input id="inCel" type="text" placeholder="Celcius" value="<?php echo $fahValue; ?>" name="cel">
<input type="submit" value="Calc">
</form>
Since both the variables give isset() true so we can have something like this
if(isset($_POST['fah']) && isset($_POST['cel'])) {
//if cel is not empty
if(!empty($_POST['cel'])) {
$cel = $_POST['cel'];
$fah=($cel-32)*1.8;
} else if(!empty($_POST['fah']){
$fah = $_POST['fah'];
$cel = ($fah+32)/1.8;
}
}
?>
<html>
<body>
<form method="post" action="calc.php">
Fahrenheit: <input id="inFah" type="text" placeholder="Fahrenheit" value="<?php echo $fah; ?>" name="fah">
Celcius: <input id="inCel" type="text" placeholder="Celcius" value="<?php echo $cel; ?>" name="cel">
<input type="submit" value="Calc">
</form>
You just missing set default values that will overwrite if other post value exist, and else if to load only one parameter so other will be empty
<?php
$cel = "";
$fah = "";
if(isset($_POST['fah'])){
$cel=($_POST['fah']+32)/1.8;
}elseif(isset($_POST['cel'])){
$fah=($_POST['cel']-32)*1.8;
}
?>
<html>
<body>
<form method="post" action="calc.php">
Fahrenheit: <input id="inFah" type="text" placeholder="Fahrenheit" value="<?php echo $fah; ?>" name="fah">
Celcius: <input id="inCel" type="text" placeholder="Celcius" value="<?php echo $cel; ?>" name="cel">
<input type="submit" value="Calc">
</form>
I am working on a page that I need to be able to update single records from my MySQL database using PHP. Can someone please help me? When I try to update one record all my other records are updated.
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>Name: *</strong> <input class="form-control" type="text" name="name" value="<?php echo $name; ?>" /><br/>
<strong>Month: *</strong> <input class="form-control" type="text" name="month" value="<?php echo $month; ?>" /><br/>
<strong>event1: *</strong> <input class="form-control" type="text" name="event1" value="<?php echo $event1; ?>" /><br/>
<strong>event2: </strong> <input class="form-control" type="text" name="event2" value="<?php echo $event2; ?>" /><br/>
<strong>event3: </strong> <input class="form-control" type="text" name="event3" value="<?php echo $event3; ?>" /><br/>
<strong>event4: </strong> <input class="form-control" type="text" name="event4" value="<?php echo $event4; ?>" /><br/>
<strong>timesub: </strong> <input class="form-control" type="text" name="timesub" value="<?php echo $timesub; ?>" readonly /><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit" class="btn btn-info">
<input type=reset name="reset" value="Reset" class="btn btn-danger">
</div>
</form>
That is my form, and then I follow it with this code:
<?php
}
include('db_connect.php');
if (isset($_POST['submit'])) {
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id'])) {
$id = $_POST['id'];
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$month = mysql_real_escape_string(htmlspecialchars($_POST['month']));
$event1 = mysql_real_escape_string(htmlspecialchars($_POST['event1']));
$event2 = mysql_real_escape_string(htmlspecialchars($_POST['event2']));
$event3 = mysql_real_escape_string(htmlspecialchars($_POST['event3']));
$event4 = mysql_real_escape_string(htmlspecialchars($_POST['event4']));
$timesub = mysql_real_escape_string(htmlspecialchars($_POST['timesub']));
// check thatfields are filled in
if ($name == '' || $month == '' || $event1 == '' || $timesub == ''){
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $name, $month, $event1, $event2, $event3, $event4, $timesub, $error);
} else {
// save the data to the database
mysql_query("UPDATE announcement SET name='$name', month='$month', event1='$event1', event2='$event2', event3='$event3', event4='$event4', timesub='$timesub'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
} else {
// if the 'id' isn't valid, display an error
echo 'Error!';
}
} else
// if the form hasn't been submitted, get the data from the db and display the form
{// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) {
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM announcement WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row) {
// get data from db
$name = $row['name'];
$month = $row['month'];
$event1 = $row['event1'];
$event2 = $row['event2'];
$event3 = $row['event3'];
$event4 = $row['event4'];
$timesub = $row['timesub'];
// show form
renderForm($id, $name, $month, $event1, $event2, $event3, $event4, $timesub, '');
} else {// if no match, display result
echo "No results!";
}
} else {// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
echo 'Error!';
}
}
?>
I got the code from: http://www.killersites.com/community/index.php?/topic/1969-basic-php-system-vieweditdeleteadd-records/
Great article!
Thanks in advance for the help.
First of all stop using mysql_* its deprecated and closed in PHP 7. You can use mysqli_* or PDO.
Whats wrong with your query:
This is very important, if you not use WHERE CLAUSE in your UPDATE STATEMENT than it will update the all rows.
You must need to add WHERE CLAUSE in your query at end, something like:
WHERE id = '$id'
Also note that, your code is open for SQL INJECTION, you must need to prevent with SQL INJECTION, you can learn about the prepared statement. This post will help you to understand: How can I prevent SQL injection in PHP?
*If you want to know How mysqli_* works, this document will help you: http://php.net/manual/en/book.mysqli.php
If you want to work on PDO, you can follow this manual: http://php.net/manual/en/book.pdo.php
Take a close look at your query:
mysql_query("UPDATE announcement SET name='$name', month='$month', event1='$event1', event2='$event2', event3='$event3', event4='$event4', timesub='$timesub'")
Your query is missing a WHERE clause. Without a WHERE clause, your query will update all rows in the table announcement. You need to add something like:
WHERE id='$id'
This will restrict the update to only the row you want to update.
I want to get three values separated by a comma when the form is submitted. The value from the checkbox, textbox 1 and textbox 2.
This is my code that retrieves values from mysql database and generates checkboxes and two corresponding textboxes.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$query = "SELECT * FROM subject";
$data = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($data)){
$s = $row['sub'];
echo $s;
?>
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="<?php echo $s; ?>" placeholder="Total Number" />
<input type="text" name="<?php echo $s; ?>" placeholder="Pass Number" />
<?php
}
?>
<input type="submit" name="submit" value="Add">
</form>
Suppose the user checks the first three boxes , and enters the values like in this picture -
when I click add, I get the values --
Physics
Math
Chemistry
by using the code below:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
echo $selected."</br>";
}
}
}
?>
but how do I get the values like this-
Physics,40,30
Math,40,30
Chemistry,30,25
I want this output in a variable so that I can store it in my database table.
I have spent several hours behind this in last few days. Please help me with this one.
you need to assign unique names to the <input type="text" ... /> so you can recieve its values in the PHP.
Second, you need to write PHP code, that's concatenating those values.
For example, your HTML code might be:
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="total[<?php echo $s; ?>]" placeholder="Total Number" />
<input type="text" name="pass[<?php echo $s; ?>]" placeholder="Pass Number" />
and your PHP code might be:
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
$total = $_POST['total'][$selected];
$pass = $_POST['pass'][$selected];
$var = $selected . ',' . $total . ',' . $pass;
echo $var . '<br />';
}
}
}
It seems my code is correct, however the posted variables in the form do not echo in the update user settings page in the form. I have echoed the posted ids from the input in the database but I cannot get the variables to show. I have done this in Codeigniter fine but am trying to do it in pure php with my own framework.
$users = new Users($db);
comes from my init.php file that is called at the beginning of the file below.
when I do
<?php var_dump($user['first_name'])?>
I get Null
<input type="text" name="first_name" value="<?php if (isset($_POST['first_name']) )
{echo htmlentities(strip_tags($_POST['first_name']));} else { echo
$user['first_name']; }?>">
Try $_REQUEST['first_name'] first before submitting it to array.
<?=$_REQUEST['first_name']?>
<input type="text" name="first_name" value="<?php if (isset($_POST['first_name']) )
{echo htmlentities(strip_tags($_POST['first_name']));} else { echo
$user['first_name']; }?>">
try this code
Is your form using get or post method? If it is using get method $_POST will be null. If you use $_REQUEST, it will show the result regardless of the http method used.
try it i think its work fine and solve your problam
<?php
if(isset('name of submit button ')) // example $_POST['submit'];
{
?>
<input type="text" name="first_name" value="<?php echo htmlentities(strip_tags($_POST['first_name'])) ?> " >
<?php
}
else
{
?>
<input type="text" name="first_name" value="<?php echo $user['first_name']; ?> " >
<?php
}
?>
try it
<?php
$first_name = $_POST['first_name'];
?>
<input type="text" name="first_name" value="<?php if (isset($first_name)){ echo htmlentities(strip_tags($first_name));} else { echo $users['first_name']; } ?> ">
my code works as expected but a little issue occurred, i try retrieving values from checkboxes with same name and hidden fields with the same name, it works but one of the hidden field keeps on returning the first value even if the checkbox was not selected.
here is my code
while($row=mysql_fetch_array($res1)){
?>
<tr><td class='bold'><?php echo $sn;?><input type="hidden" name="snum[]" value="<?php echo $sn; ?>" /></td>
<td><?php echo $row['subLocationName']; ?>
<input type="hidden" name="location[]" value="<?php echo $row['dllink_id']; ?>"/></td>
<td><input type="checkbox" name="available[]" value="<?php echo $row['subLocationName']; ?>"/></td>
<input type="hidden" name="locationID[]" value="<?php echo $row['locationName']; ?>"/>
<input type="hidden" name="sublocation[]" value="<?php echo $row['subLocationName']; ?>"/>
<input type="hidden" name="device[]" value="<?php echo $row['deviceName']; ?>"/>
<td></td><td></td></tr>
<?php
$sn++;
}
the values are from my database.
the retrieving code is this
if(isset($_POST['submit_btn'])){
$serial_num = $_POST['snum'];
$locationDeviceLink = $_POST['location'];
$linkAvailable =$_POST['available'];
$location = $_POST['locationID'];
$subLocation = $_POST['sublocation'];
$device = $_POST['device'];
$measure_date = date("Y-m-d");
$sn = count($linkAvailable);
for ($i=0; $i<$sn; $i++ ){
if(!empty($linkAvailable[$i])){
echo "serial number:".$serial_num[$i]." location:".$locationDeviceLink[$i]." available:".$linkAvailable[$i]." Location:".$location[$i]." subLocation:".$subLocation[$i]." Device:".$device[$i]." Date:".$measure_date."<br/>";
}
}
}
the problem is the subLocation value, it keeps returning the first value then the second as it appears even if the associated checkbox is not checked and another checkbox is checked, please can anyone help me out, cant't think of anything more.
thanks in advance
joseph O
Rather then testing for !empty try using php's function isset.
for ($i=0; $i<$sn; $i++ ){
if(isset($linkAvailable[$i])) {
echo "serial number:".$serial_num[$i]." location:".$locationDeviceLink[$i]." available:".$linkAvailable[$i]." Location:".$location[$i]." subLocation:".$subLocation[$i]." Device:".$device[$i]." Date:".$measure_date."<br/>";
}
}