So I need help with a required form field. I want the 3 fields (exam_id, subject, exam_date) to be required fields when filling out the PHP form. So when the insert button is hit, if a field is left blank and error will display or the action won't complete unless every field is filled in.
I'm using all php, no HTML and no, I don't want to redo my form as HTML calling the php, I want it like this. There's no security problems either, this is just a simple project.
My code:
<?php
echo '<link rel="stylesheet" type="text/css" href="css/tables.css" />';
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("StudentExams", $con);
if (isset($_POST['update']))
{
$UpdateQuery = "UPDATE Exam SET exam_id='$_POST[exam_id]', subject='$_POST[subject]', exam_date='$_POST[exam_date]' WHERE exam_id='$_POST[hidden]'";
mysql_query($UpdateQuery, $con);
};
if (isset($_POST['delete']))
{
$DeleteQuery = "DELETE FROM Exam WHERE exam_id='$_POST[hidden]'";
mysql_query($DeleteQuery, $con);
};
if (isset($_POST['insert']))
{
$InsertQuery = "INSERT INTO Exam (exam_id, subject, exam_date) VALUES ('$_POST[uexam_id]','$_POST[usubject]','$_POST[uexam_date]')";
mysql_query($InsertQuery, $con);
};
$sql = "SELECT * FROM Exam";
$Data = mysql_query($sql,$con);
echo "<table id='size' border='1'>
<tr>
<th>Exam_ID</th>
<th>Subject</th>
<th>Exam_Date</th>
</tr>";
while($record = mysql_fetch_array($Data))
{
echo "<form action=examisud.php method=post>";
echo "<tr>";
echo "<td>" . "<input type=text name=exam_id value=" . $record['exam_id'] . " </td>";
echo "<td>" . "<input type=text name=subject value=" . $record['subject'] . " </td>";
echo "<td>" . "<input type=text name=exam_date value=" . $record['exam_date'] . " </td>";
echo "<td>" . "<input type=hidden name=hidden value=" . $record['exam_id'] . " </td>";
echo "<td>" . "<input type=image name=update value=update id=submit src=images/update.png" . " </td>";
echo "<td>" . "<input type=image name=delete value=delete id=submit src=images/delete.png" . " </td>";
echo "</tr>";
echo "</form>";
}
echo "<form action=examisud.php method=post>";
echo "<tr>";
echo "<td><input type=text name=uexam_id></td>";
echo "<td><input type=text name=usubject></td>";
echo "<td><input type=text name=uexam_date></td>";
echo "<td>" . "<input type=image name=insert value=insert id=submit src=images/insert.png" . " </td>";
echo "</form>";
echo "</table>";
echo "<a href='ExamForm.html'> Back to main page </a>";
mysql_close($con);
?>
Thanks in advance for anyone who can help me out! I feel there is either a very simple solution i'm missing or it's very convoluted due to the absence of a generic HTML form.
Just do a check on the top with isset
if(!isset($_POST['exam_id'],$_POST['subject'],$_POST['exam_date']))
{
echo "These fields are required ! Please fill it up";
header("location:backtoform.php");exit;
}
Warning : Since you are passing the $_POST parameters directly onto your query, you are prone to SQL Injection attacks.
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
isset( ... ) is only used to see if a field is set or not. It doesn't care if the value of the field is empty.
You need to use empty( .. ) instead. It would return true only if the field was ever set and is not empty. Two apples with one shot.
Across all your if statements, use !empty. Maintain an $error variable and initialize it to FALSE. Whenever an error occurs, set $error to TRUE.
In the end, perform the required operation only when $error == FALSE.
$error = false;
if ( !empty($_POST['update'] ){
// stuff
}
else {
// display error message
$error=true;
}
if(!$error){
// operations
}
This way you can neatly separate validations from operations.
Related
I have code that search for my field name(familycode) then displays a table. I have the code enclosed in the table to update table and database.
My issue - after updating - My display information does't update and won't refresh or ever show correct data from mysql database. Database is updated.
I am new and this is first post. I tried many many different ways no luck. I would appreciate some thoughts!! Thank you!
my code for main page d7.php
<?php
// connection
$dbcon= NEW Mysqli("localhost", "root", "", "xxx");
if (!$dbcon) {
echo " ----------Error connecting to database--------------";
}
else {
echo " ----------Connected to Database Successfully----------- <br>" ;
}
include 'updatedata.php';
?>
<html>
<head>
<title> View_Update Family</title>
<link rel="stylesheet" type="text/css" href="d7css.css">
</head>
<body>
<form action=d7.php method=post>
<input type="text" name="valueToSearchfamily" placeholder="Family To
Search"><br><br>
<input type="submit" name="searchfamily" value="Search Family"><br>
<br>
</form>
<?php
if(isset($_POST['searchfamily']))
{
$valueToSearchfamily=$_POST['valueToSearchfamily'];
// search in all table columns
$select = "SELECT * FROM families WHERE Familycode LIKE
'%".$valueToSearchfamily."%' ";
$mydata=mysqli_query($dbcon, $select);
}
else {
$notselect = "SELECT * FROM families ORDER BY Familycode ";
$mydata=mysqli_query($dbcon, $notselect);
}
echo "<table class='updatetable' >";
echo "<tr>
<th>Id</th>
<th>Familycode</th>
<th>Name</th>
<th>Street</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
</tr>";
while($record = mysqli_fetch_array($mydata)){
echo "<form action=updatedata.php method=post>";
echo "<tr>";
echo "<td>" . "<input type=text name=aid value=" . $record['Aid'] .
" </td>";
echo "<td>" . "<input type=text name=familycode value=" .
$record['Familycode'] . " </td>";
echo "<td>" . "<input type=text name=name_mailing value=" .
$record['Name_mailing'] . " </td>";
echo "<td>" . "<input type=text name=street_mailing value=" .
$record['Street_mailing'] . " </td>";
echo "<td>" . "<input type=text name=city_mailing value=" .
$record['City_mailing'] . " </td>";
echo "<td>" . "<input type=text name=st_mailing value=" .
$record['St_mailing'] . " </td>";
echo "<td>" . "<input type=text name=zip_mailing value=" .
$record['Zip_mailing'] . " </td>";
echo "<td>" . "<input type=hidden name=hidden value=" .
$record['Aid'] . " </td>";
echo "<td>" . "<input type=submit name=update value=update" . "
</td>";
echo "</form>";
};
?>
</body>
</html>
my other file as I tried separating them is updatedata.php
<?php
// connection
$dbcon= NEW Mysqli("localhost", "root", "", "xxx");
if (!$dbcon) {
echo " ----------Error connecting to database--------------";
}
else {
echo " ----------Connected to Database Successfully----------- <br>" ;
}
// ==========================================================
if(isset($_POST['update'])) {
$updatequery="UPDATE families SET Aid='$_POST[aid]',
Familycode='$_POST[familycode]', Name_mailing='$_POST[name_mailing]',
Street_mailing='$_POST[street_mailing]',
City_mailing='$_POST[city_mailing]', St_mailing='$_POST[st_mailing]',
Zip_mailing='$_POST[zip_mailing]' WHERE Aid='$_POST[hidden]'";
mysqli_query($dbcon, $updatequery);
header("location: index_dir.php");
};
?>
Welcome Don T to stackoverflow! It seems like your echoing onto the page in an instance, recall that when you Echo something out, it doesn't change when it changes inside your database because you aren't making the call again, its on the same page. To fix this, you need to use Javascript + Ajax, I recommend picking up jQuery and harnessing its basics for POST'ing and GET'ing data from a PHP page.
Here is the link for jQuery Ajax: http://api.jquery.com/jquery.ajax/
Simple example using jQuery ajax:
$.ajax({
url: 'PHP SCRIPT PAGE URL',
method: 'POST', // Your sending data, use POST
data: 'Your Data!', // This can be also be a form object
success: function(response) { // Response is your PHP scripts answer to this request.
console.log(response); // You may Echo or use JSON format as a response.
} // If you use JSON, add dataType: 'JSON' in the ajax call to the left.
})
Remember if this answer has helped you resolve your issue, select it as the Answer!
Thanks!
I'm trying to make a HTML table as a frontend to a mySQL database. The table displays fine and I can type in the edits I want to make to each row of the table but when I press the submit button the changes aren't actually made. Can anyone see where I'm going wrong?
<?php
include("db.php");
$sql = "SELECT * FROM `artist`";
$result = mysqli_query($conn, $sql);
if (isset($_POST['update'])){
$artID = $_POST['artID'];
$artName = $_POST['artName'];
$key = $_POST['hidden'];
$UpdateQuery = "UPDATE `artist` SET `artID` = '$artID', `artName` = '$artName' WHERE `artist`.`artID` = '$key'";
mysqli_query($conn,$UpdateQuery);
header("Location: {$_SERVER['HTTP_REFERER']}");
exit;
};
echo "<table border='1'>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Name</th>";
echo "</tr>";
if ($result->num_rows > 0) {
echo "<form id ='artisttable' action ='getartiststable.php' method ='post'>";
// output data of each row
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" ."<input type='text' name ='artID' value ='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='text' name ='artName' value ='" . $row["artName"] . "' </td>";
echo "<td>" . "<input type = 'hidden' name ='hidden' value='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='submit' name ='update'" . " </td>";
echo "</tr>";
}
echo "</form>";
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
The db.php file simply includes the connection info to the mySQL database and I'm 100% sure there's nothing wrong with it as it retrieves the table correctly it just doesn't update.
You are putting form tag inside tr which is not allowed td are only allowed
so you have to remove that tr from there.
You have to use jquery or you can replace the table with some other grid structure so that it can look the same and the form can be placed there as well
One more suggestion Don't mix the php and html together separate them for the clean code
If you do all these you code will be like this
Your form is being constructed with multiple elements with the same name. When you submit the form it is using the last elements as the values so regardless of the record you want updated the last record is being updated (or throwing an error because of string encapsulation). You should use parameterized queries as well.
So instead of:
if ($result->num_rows > 0) {
echo "<form id ='artisttable' action ='getartiststable.php' method ='post'>";
// output data of each row
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" ."<input type='text' name ='artID' value ='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='text' name ='artName' value ='" . $row["artName"] . "' </td>";
echo "<td>" . "<input type = 'hidden' name ='hidden' value='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='submit' name ='update'" . " </td>";
echo "</tr>";
}
echo "</form>";
echo "</table>";
Use:
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_array($result)) {?>
<form class='artisttable' action ='getartiststable.php' method ='post'>
<tr>
<td><input type='text' name ='artID' value ='<?php echo $row['artID'];?>' /></td>
<td><input type='text' name ='artName' value ='<?php echo $row["artName"];?>' /></td>
<td><input type = 'hidden' name ='hidden' value='<?php echo $row['artID'];?>' /></td>
<td><input type='submit' name ='update'" . " </td>
</tr>
</form>
<?php } ?>
</table>
So you get a form for each data set. Here's a link on prepared statements with mysqli: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php. You also should update your mark up. Tables for formatting aren't the best approach. Your inputs also weren't closed missing >.
Also this changed artisttable from an id to class because there will be multiples. Update CSS/JS accordingly.
I'm currently trying to get a database updated through a PHP form. Firstly I get all the information from the database within the form, and then trying to update details within that form to reflect on the database.
I could successfully managed to get all the details from the database within the form but unfortunately doesn't update for that reason.
Here is the code to retrieve the info from DB, within the form which works 100%:
include_once 'db_connect.php';
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<form id=updateVehicle action='' method=post";
echo "<div id='vehicleDescription'>";
echo "<div>";
echo "<label for=vin>VIN</label>";
echo "<input type=text id=vin name=vin minlength=17 maxlength=17 placeholder=e.g. BMW1234567890ABCD value=" . $row['vin'] . " />";
echo "<br/>";
echo "</div>";
echo "<div>";
echo "<label for=make>Make</label>";
echo "<input type=text id=make name=make minlength=3 maxlength=13 placeholder=e.g. BMW value=" . $row['make'] . " />";
echo "<br/>";
echo "</div>";
echo "<div>";
echo "<label for=model>Model</label>";
echo "<input type=text id=model name=model minlength=2 maxlength=15 placeholder=e.g. 530D value=" . $row['model'] . " />";
echo "<br/>";
echo "</div>";
echo "<div>";
echo "<input type=text name=id value=" . $row['id'] . " />";
echo "</div>";
echo "<span><?php echo $errorMessage;?></span>";
echo "</div> <!--End of vehicleDescription div-->";
echo "<input type='submit' class='submit' value='Update Ads' />";
echo "</form>";
}
}
The action is empty because it submits to itself, I've tried to use "echo htmlspecialchars($_SERVER["PHP_SELF"]);" but it didn't work, so I left it out.
Here is the code to process the update which doesn't work:
if(isset($_POST['vin'], $_POST['make'], $_POST['model'])) {
$vin = filter_input(INPUT_POST, 'vin', FILTER_SANITIZE_STRING);
$make = filter_input(INPUT_POST, 'make', FILTER_SANITIZE_STRING);
$model = filter_input(INPUT_POST, 'model', FILTER_SANITIZE_STRING);
$id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);
if($insert_stmt = $mysqli->prepare("UPDATE vehicles SET (vin=?, make=?, model=? WHERE id=? ")) {
$insert_stmt->bind_param("sssi", $vin, $make, $model, $id);
if(!$insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: UPDATE');
$mysqli->close();
}
}
header('Location: ../includes/register_success.php');
$mysqli->close();
}
For some unknown reasons to me, it doesn't update the database at all. The 'db_connect.php' works 100% as I'm using it for other database queries.
I'd really appreciate any help if you could point me in the right direction.
Thank you!
Aren't you getting an error when executing the update query? I can see an extra ( after SET in:
UPDATE vehicles SET (vin=?, make=?, model=? WHERE id=?
This should cause the query to fail which is a good reason why things are not updated in the database.
<?php
include('common/connect.class.php');
include('common/admin.class.php');
session_start();
$user = $_SESSION['user'];
$con2 = new connection();
$con = $con2->connect();
$sql = "SELECT * FROM xam_category"; //Select Query
$myData = mysql_query($sql,$con) or die(mysql_error());;
echo "<table align='center'>
<tr>
<th>Category name</th>
<th>Category Description</th>
</tr>";
while($record = mysql_fetch_array($myData))
{
echo "<form action=user_book.php method=post>";
echo "<tr>";
echo "<td>" . "<input type=text size=10 readonly='true' name=usrname value=" . $record['category_name'] . " </td>";
echo "<td>" . "<input type=text size=15 readonly='true' name=usrmail value=" . $record['category_desc'] . " </td>";
echo "<td>" . "<input type=submit name=delete value=DELETE" . " </td>";
echo "<td>" . "<input type=submit name=update value=UPDATE" . " </td>";
echo "</tr>";
echo "</form>";
}
mysql_close($con);
echo "</table>";
?>
My SELECT query and data fetching is working fine. But, while i echo the fetched data, it only shows the first word "Computer" where it's actual value is "Computer Science".
The data stored in database viewed through PhpMyAdmin seems ok. But,
The data shown in the .php page is different and not ok.
I'm Stuck.
How to display the right string from MySQL database on the PHP page?
Note: I'm using html inside echo to loop & display all data. Sorry, I have to use mysql() functions could'nt do msqli(). I also viewed other same type questions in StackOveflow. But, Couldn't find a solution.
If you have a value with a space in it, you must enclose that value within quotes in your HTML. Try with
echo "<td><input type=text size=10 readonly='true' name='usrname' value='".$record['category_name']."'</td>";
Try to use mysql_fetch_assoc instead of mysql_fetch_array if you would like to access to variable like $record['category_name'].
Please read this article: mysql_fetch_row() vs mysql_fetch_assoc() vs mysql_fetch_array()
So, I have the following code: (Don't worry about SQL injections/mysql depreciation for now)
$required = array('uexam_id', 'usubject', 'uexam_date');
$error = false;
//VALIDATION: first check all required fields are not empty. if post has values
if(!empty($_POST))
foreach($required as $field)
if ( empty($_POST[$field]))
$error = true;
//a field was empty, show error
if ($error) {
die ("All fields required!!! <a href='examisud.php'> Back to PHP Form </a>");
}
//no error - try the query
elseif($error === false && !empty($_POST) )
{
$InsertQuery = "INSERT INTO Exam (exam_id, subject, exam_date) VALUES ('$_POST[uexam_id]','$_POST[usubject]','$_POST[uexam_date]')";
$result = mysql_query($InsertQuery, $con) or die('query Failure:'. mysql_error());
}
So when I navigate to this php form (examisud.php), I am first greeted by "All Fields required". I can then navigate back to the form and it works as normal inserting data and displaying errors if not all fields are filled in.
*How can I get the "All fields required" to not display on form page load and only when I need it to (when a field is left blank).
When I also update or delete fields I also get the "All fields required" error display. However everything updates/gets deleted as normal apart from the error popping up.
So basically I just need it to show up when a field is left blank in the insert query!
Thanks in advance for any help you can give me!
*Edit My form:
{
echo "<form action=examisud.php method=post>"; //HTML FORM ECHOED OUT BY PHP
echo "<tr>";
echo "<td>" . "<input type=text name=exam_id value=" . $record['exam_id'] . " </td>";
echo "<td>" . "<input type=text name=subject value=" . $record['subject'] . " </td>";
echo "<td>" . "<input type=text name=exam_date value=" . $record['exam_date'] . " </td>";
echo "<td>" . "<input type=hidden name=hidden value=" . $record['exam_id'] . " </td>";
echo "<td>" . "<input type=image name=update value=update id=submit src=images/update.png" . " </td>";
echo "<td>" . "<input type=image name=delete value=delete id=submit src=images/delete.png" . " </td>";
echo "</tr>";
echo "</form>";
}
echo "<form action=examisud.php method=post>";
echo "<tr>";
echo "<td><input type=text name=uexam_id></td>";
echo "<td><input type=text name=usubject></td>";
echo "<td><input type=text name=uexam_date></td>";
echo "<td>" . "<input type=image name=insert value=insert id=submit src=images/insert.png" . " </td>";
echo "</form>";
echo "</table>";
you have to check whether the form is submitted or not
for example if you have form submit like this
<input type="submit" name="submit">
then in your php check it like this
if(!empty($_POST['submit']))//means the form is submitted
{
//your code
}
else
{
//no form is submitted here display your form normally
?>
<form action="" method="POST">
......
......
<input type="submit" name="submit">
</form>
<?php
}
hope it helps you,all the best
This code should do it, explainations below.
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // check if the user submits data (POST) or just loads the page (GET)
$error = false;
$required = array('uexam_id', 'usubject', 'uexam_date');
foreach($required as $field) {
if (!isset($_POST[$field]) || empty($_POST[$field])) {
$error = true;
break;
}
}
if ($error) {
die("All fields required!!! <a href='examisud.php'> Back to PHP Form </a>");
} else {
$InsertQuery = "INSERT INTO Exam (exam_id, subject, exam_date) VALUES ('".mysql_real_escape_string($_POST["uexam_id"], $con)."','".mysql_real_escape_string($_POST["usubject"], $con)."','".mysql_real_escape_string($_POST["uexam_date"], $con)."')";
$result = mysql_query($InsertQuery, $con) or die('query Failure:'. mysql_error());
}
}
First off, you code has some serious security issues and should never not be used in production.
mysql_* functions are deprecated - use mysqli (which is very similar to mysql) or PDO_MYSQL.
Your code is vulnerable to SQL injection attacks, read this question on how to prevent them (either properly escaping values or using prepared statements).
Currently I used mysql_real_escape_string to escape the variables so this code should be safe.
Finally, my code should still fix your first issue since it checks if the user is actually submitting the form (by checking if the request method is POST) before running the validation, whereas your first code was running the validation (and failing) even if there was no data being submitted.