PHP form not saving to table - php

I have a page called service.php that uses a modal window to open a form. The action on the form was service.php.
<div class="modal hide fade" id="myServiceModal" tabindex="-1" role="dialog" aria-labelleby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Service Failure Form</h3>
</div>
<div class="modal-body">
<p>
<form class="well-small" action="service.php" method="POST" id="serviceModalForm" name="serviceModalForm">
<label>Container Selected</label>
<input type="text" name="containerNumber" id="containerNumber" />
<label>Bol Selected</label>
<input type="text" name="bolNumber" id="bolNumber" />
<input type="submit" id="modal-form-submit" name="submit" class="btn btn-success btn-small" href="#" value="Save" />
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
if(isset($_POST['submit'])){
$sql_query_string =
"INSERT INTO import_view_svc_fail (bol, container_num) VALUES
('$bol', '$container');";
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Added New Service Failure')
</script>");
}
?>
</form>
This form worked, and it saved to the appropriate table.
Here is my problem: I had to move that form to another page, called dispatch.php. All I did was copy the code, and put it on dispatch.php.
I changed the action of the form to dispatch.php, and that's where I think the problem starts. When I change the action back to service.php, it works for whatever reason.
When I remove the form completely from service.php, the form on dispatch.php no longer works.
I've tried everything to make this work. I removed all of the code from service.php. I even removed the whole file from the folder.
Any insight would be helpful.

You tell the script what to do but you don't tell it to do it.
In order to excecute a your SLQ-query you have to use mysql_query($sql_query_string);
You will also want to connect to your database. Take a look at http://php.net/manual/de/function.mysql-connect.php for more information.

so.. you change the action in service.php:
<form class="well-small" action="dispatch.php" method="POST" id="serviceModalForm" name="serviceModalForm">
Move to dispatch.php
<?php
if(isset($_POST['submit']))
{
$bol = (isset($_POST['bolNumber'])) ? $_POST['bolNumber'] : '';
$container = (isset($_POST['containerNumber'])) ? $_POST['containerNumber'] : '';
if (!empty($bol) && !empty($container))
{
$sql_query_string =
"INSERT INTO import_view_svc_fail (bol, container_num) VALUES
('$bol', '$container');";
// run the query here
print "<br/><br/>".$sql_query_string."<br/><br/>";
}
else { print "<br/><br/>empty values;<br/>"; }
}
else { print "<br/><br/>\$_POST info not received;<br/>"; }
?>
prints (after submit):
INSERT INTO import_view_svc_fail (bol, container_num) VALUES ('input one value', 'input two value');
you probably should check and make sure you got all your post values inside the if(isset($_POST['submit'])) statement, too. or re-work the logic as a whole... it depends if you want to allow blank values, too.
Also, read up on sql injection and why you should learn to use mysqli_ or pdo.

Related

delete button in PHP website behaving like static when clicked

i have a simple delete button in PHP which uses simple SQL query to delete the data from database, I have used the following code:
$myid = $this->uri->segment('3');
if (isset($_POST['submit'])){
$ret = mysqli_query($con,"delete * from smart_category where name='$myid'");
header("Location: https://cloudclassmate.com/jewelry-catalogue/admin/viewcategory");
}
<div style="margin-left:38%" class="clearfix">
<a href="https://cloudclassmate.com/jewelry-catalogue/admin/viewcategory">
<button type="button" class="cancelbtn bemine">Cancel</button></a>
<form action="" method="post" ><button type="submit" name="submit" class="deletebtn bemine">Delete</button></form>
</div>
the problem here is if I click the delete button, its not responding, nothing is happening. the button is like static. can anyone please tell me what could be wrong here
If any Javasscript is not involved, than just put form action.
Also send myid in the request or in URI.
please see below:
<div style="margin-left:38%" class="clearfix">
<button type="button" class="cancelbtn bemine">Cancel</button>
<form action="abc.php" method="post" ><button type="submit" name="submit" class="deletebtn bemine">Delete</button></form>
</div>
You should add an action url/path to where your PHP file is located and add a Method to your form. Also, I noticed you deleting an entry where "name" is equal to $myid please check if that is correct.
<div style="margin-left:38%" class="clearfix">
<button type="button" class="cancelbtn bemine">Cancel</button>
<form action="url-to-server.php" method="post" >
<button type="submit" name="submit" class="deletebtn bemine">Delete</button>
</form>
</div>
$myid = $this->uri->segment('3');
if (isset($_POST['submit'])){
$ret = mysqli_query($con,"delete * from smart_category where name='$myid'");
header("Location: https://cloudclassmate.com/jewelry-catalogue/admin/viewcategory");
}

How to update data using bootstrap modal in php

I'm trying to edit the profile of each user by the admin using bootstrap modal in php.
Here is the summary what I'm doing.
An anchor tag in admin.php page :
Modal at admin.php page.
<div id="theModal" class="modal fade text-center">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
And javascript in the same page i.e admin.php
$('.li-modal').on('click', function(e){
e.preventDefault();
$('#theModal').modal('show').find('.modal-content').load($(this).attr('href'));
});
here is editprofile.php.
In this page I've selected that user's information who has been clicked to edit, on that above anchor tag.
<?php
$connect = mysqli_connect('localhost','root','','db');
if(isset($_GET['id'])){
$id = $_GET['id'];
$query = "SELECT * FROM user where id = '$id'";
$run = mysqli_query($connect,$query);
}
?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">X</button>
</div>
<div class="modal-body">
<div class="panel panel-default">
<div class="panel-heading text-center">
User Information
</div>
<form action="edit.php" method="POST" id = 'myform'>
<!-- body of the bootstrap modal -->
<?php
while($row = mysqli_fetch_assoc($run)){
?>
<label for="name">First Name</label>
<input type="text" name = 'fname' value = '<?php echo $row['fname'] ?>' class = 'form-control'>
<?php
}
?>
<div class="modal-footer">
<input type="button" name="save" class="btn btn-primary" data-dismiss="modal" value="Save Changes" form = 'myform'>
</div>
Here is I want to do:
I want to submit a form (which is there in modal) with updated data by clicking on button that says Save Changes
And I want to redirect the user back to the admin.php page when the admin click outside the modal or when s/he click on the close icon at the top right of the modal.
Also want to show the success message when the admin successfully update the data.
How would I do that?
I don't know how to use a form with in a modal and then how to submit that , there may be some non standard approach , bare me with that.
I never used bootstrap, but I have noticed that you have PHP syntax error in Your 'inline php' or mixed html/php portion inside while loop.
This:
<?php echo $row['fname'] ?>
Should look like this:
<?php echo $row['fname']; ?>
semicolon is missing in Your example.
Other than that, when You just want to echo something in mixed html/php, You don't need php open tag.
Although one should avoid mixing html/php directly as it is very old PHP fashion,
something like this is recommended (semicolon at the end is not needed in this case):
<?=$row['fname']?>
// wrapped in "()" is ok as well, kinda more readable
<?=($row['fname'])?>
And not only that..
You cannot write html tag argument values separated with blank space everywhere. Won't work.
Not like this:
name = 'fname' value =
But like this:
<tagname attribute='value' otherattribute='value'> ...
Try to fix those first.

Submitting session username back to database in query

Basically i want whoever creates a note on my website to be the "author" of that note.
So whoever is logged in when they create the note should be the author.
At the moment in login_form.php i have created a session which is the "included" in my general_notes.php. In general_notes.php i have the following code for when the user clicks to add a note:
<p class="fa fa-plus hover-cursor icon-spin noSelect" data-toggle="modal" data-target="#addGeneralNote" style="font-size: 16pt;"></p>
which runs:
<!-- Modal -->
<div id="addGeneralNote" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header header-notes">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add General Note</h4>
</div>
<!-- Form submission data -->
<form action="addNewNote.php" method="POST">
<div class="modal-body">
<p>Please enter the note you wish to create.</p>
<textarea id="addGeneralNoteName" placeholder="Enter a note name..." name="title" maxlength="100"></textarea>
<textarea id="addGeneralNoteText" placeholder="Enter note here..." name="content"></textarea>
<input type="checkbox" name="pinned"> Pin Note to your homepage
</div>
<div class="modal-footer footer-notes">
<button type="submit" class="btn btn-success">Create</button>
</div>
</form>
</div>
</div>
</div>
You'll see in the form there is addNewNote.php which runs:
<?php
if (isset($_POST['title'], $_POST['content'], $_SESSION['username']))
{
$title = $_POST['title'];
$content = $_POST['content'];
$author = $_SESSION['username'];
$stmt = "INSERT INTO Notes (NoteName, Note, Author, DateCreated) VALUES (?, ?, ?, GETDATE())";
$params = array($title, $content, $author);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
header('location: general_notes.php');
}
else
{
echo "No Data";
}
?>
Before i added to the isset $_SESSION['username'] it ran fine.
At the moment it hits this part:
else
{
echo "No Data";
}
of the isset function
So how how do i pass through the session username into my addNewNote.php script?
The simple answer is that you didn't call session_start() in addNewNote.php. But I'd also like to elaborate on a comment you made above, hopefully to help future readers:
i for some reason presumed it would get the session from the previosu page
The "previous page" was a separate HTTP request entirely, and the two have no connection to one another. Much in the same way that a JavaScript application re-starts with each page load, so does a PHP application start anew with each page load.
Consider each individual HTTP request to be its own separate instance of the application. While these instances can share data via external data stores, such as a database or session state, the application itself retains nothing in-memory about any other running or previous instance.
So while the data may indeed be in the session data store (which is external to the application itself), each instance of the application needs needs to connect to that data store in order to use it. Just as one must connect to a database in order to use it, one must also invoke session_start() in order to use the session.

Form action attribute not working properly

I wrote a simple php script for a form, tested it out, and worked as expected. But when I actually added the script into the original project that I am working on, it suddenly stopped working? I am sure it has nothing to do with the php script as for it worked properly when I tested it; so basically what I am thinking about is that I probably wrote the action attribute wrong? I am pretty sure it is a rookie mistake. Eventually, I am really new to php.
Regards.
HTML code:
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">New message</h4>
</div>
<div class="modal-body">
<form action="contact.html" method="post">
<div class="form-group">
<label name="email" class="control-label">Email:</label>
<input type="text" class="form-control" id="recipient-name">
</div>
<div class="form-group">
<label name="phone" class="control-label">Phone:</label>
<input type="text" class="form-control" id="recipient-mobile">
</div>
<div class="form-group">
<label name="message" class="control-label">Message:</label>
<textarea class="form-control img-responsive" rows="5" id="messageText"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="resetText" class="btn btn-default">Reset</button>
<input type="button" value="Send message" name="send" class="btn btn-danger colorbg"/>
</div>
</div>
</div>
</div>
PHP Code:
<?php
if(isset($_POST['send'])){
$to = 'domain#mail.com';
$subject = 'Solutions';
$mail = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$mailHeader = "From: $mail \r\n Phone: $phone";
$formcontent="Message: $message";
if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
echo "<script language='javascript'>
alert('E-mail address is not valid');
var email = document.getElementById('recipient-name');
email.className += ' border-red';
</script>";
} else {
echo "<script language='javascript'>
var email = document.getElementById('recipient-name');
email.className = '';
email.className += ' form-control';
</script>";
if (mail($to , $subject, $formcontent, $mailHeader)) {
echo "<script>
window.setTimeout(function () {
window.location.href = 'test.html';
}, 3000);
</script>";
} else {
echo "<script language='javascript'>alert('There was an error. Please try again.')</script>";
}
}
}
?>
Please note that I uploaded the project on my website in order to actually test the script so the link is something like this: website.com/project/index.html. And I changed the action to action="script/contact.php", action="./script/contact.php, action="contact.php" none worked.
There are two things that makes this not work.
The "submit" button (or any of the other buttons for that matter) is not inside the form-tags. They can be outside, if you assign an ID to the form and assign inputs outside the form, to that form.
There isn't actually a submit-button. You have a regular button. It should be of type="submit", not type="button" (and type="reset" for reset buttons).
In HTML5, you can assign inputs to a form, even outside the actual form-tags. You can do that by assigning an ID to the form (in this example, "myform") and then specifying the form-attribute on your input, like this.
<form id="myform" method="get" action="something.php">
<input type="text" name="name" />
</form>
<input type="submit" form="myform" />
You also, as the other answer already pointed out, the action targets a .html file, which under normal configurations would not parse PHP, but display it as text instead.
I don't see any submit.
Or is that handled by JavaScript somewhere?
Also, the form action= is a html file, if you want the php to work in there, you'll need a .php file.
There is nothing being posted in the html you're showing that is named "send". ( if(isset($_POST['send'])) )
I found the solution here for a similar problem. I hope this is the right place for my answer.
I use buttons A-Z to filter last names in 'listContacts.php'.
Each button triggers a submit. The submit was working from the beginning on
var $char='';
var $characterfilter=function charfilter($char){;
$('#coll').prop('value', $char);
var val2=$('#coll').val();
$('#listcontacts').submit();
};
$('#a').click(function(){
$characterfilter('a');
});
The problem:
<form id='listcontacts' href='' title='use the tabulator to move in the form' style='position: relative; overflow:hidden; height:25em; width:95%' method='post' accept-charset='UTF-8' action='admin.php?listContacts'>
A switch-function in 'admin.php' as below controls the actions:
switch ($action){
case 'login':
login();
break;
case 'logout':
logout();
break;
case 'editService':
editService();
break;
case 'deleteService':
deleteService();
break;
case 'listContacts':
listContacts();
break;
case 'newContact':
newContact();
break;
case 'editContact':
editContact();
break;
case 'deleteContact':
deleteContact();
break;
default:
listServices();
}
When I submitted the form, the Switch in 'admin.php' always returned the default, so I saw the form 'listServices.php' instead after submitting 'listContacts' by using one of the filterbuttons.
The reason for this flaw was: the first call to 'listContacts.php' had been executed by a command:
<a href='admin.php?action=listContacts' >List Contacts</a>
so 'action' had already been set to 'listContacts'
After removing 'action=...' from the formcall as below the form was working.
<form id='listcontacts' href='' title='use the tabulator to move in the form' style='position: relative; overflow:hidden; height:25em; width:95%' method='post' accept-charset='UTF-8'>
It was a little puzzle, took me a few hours and I hope I can help others saving time by posting this.

Updating database with jEditable & mysqli

First of all, jEditable works for me - I can enter a value, hit enter and enjoy the sight of the new value in the table. However, this value is never inserted into the database.
As far as I understand, the jQuery code from the jEditable website
$(document).ready(function() {
$('.edit').editable('http://www.example.com/save.php');
});
which I have changed to link to my update.php script
error_reporting(E_ALL ^ E_NOTICE);
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$database = "database";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['value'];
$id = $_POST['id'];
echo $value;
$updateTest=$conn->query("UPDATE table SET column='".$value."' WHERE ID='".$id."'");
should update the database, but nothing happens. When I look at the network log function of Firefox, I can see that there is no ID submitted (I do not know where this ID is supposed to come from in the first place, there is nothing in the example), but the value is there. There does not seem to be a response from the server, however.
Maybe the table itself is the problem:
while($row = $results->fetch_assoc()) {
$ID = $row["ID"];
print '<tr>';
print '<td><div class="edit" data-pk="'.$ID.'">'.$row["column"].'</div></td>';
print '</tr>';
(I left out the SELECT statement because everything else is displayed correctly)
Sadly, there is no explanation why the div should have an id - it's apparently not what is submitted in the POST request.
I have googled around a bit, but I could not find an answer to this. It's probably obvious, but I just can't find it. Ever since I changed my original prepared statement to this I don't get errors anymore, either.
I would be very grateful for any help, especially if you could explain my mistake to me so I won't repeat it in the future.
If there is any place on the internet with an actual complete (mysqli) example of what the save.php file mentioned in the Jeditable documentation looks like and you have the link (I certainly didn't find it...), I'd take that too.
This is incorrect:
print '<td><div class="edit" data-pk="'.ID.'">'.$row["column"].'</div></td>';
^^
There's no $, so ID is an undefined constant. PHP will probably try to be polite and assume you meant 'ID' isntead (a string containing the letters I and D), which means ALL of your rows are going to show up in the client as data-pk=ID, and not data-pk=1, data-pk=2, etc...
As there seems to be no solution to this (or, more precisely, I'm running out of time for this project), I switched to modals. If anyone comes across this and considers modals a viable option, here's what I've done:
I'm using a GET form and an update page that updates different tables depending on which page the request comes from - that's what "ref" is for.
update.php:
$updateID=$_GET['id'];
$updateRef=$_GET['ref'];
$col1=$_GET['col1'];
$col2=$_GET['col2'];
if($updateRef == "refpage"){
$updateTable=$conn->query("UPDATE my_table SET col1='".$col1."', col2='".$col2."' WHERE ID='".$updateID."'");
header("Location: refpage.php");
die();
}
My modals are generated with the table rows, which is probably the ugliest solution anyone ever used for anything, but it works... (Can't display the form in a table, though, because tables within divs within tables are a terrible idea.)
$results = $conn->query("SELECT col1, col2 ID FROM my_table");
while($row = $results->fetch_assoc()) {
$ID = $row["ID"];
$modalID = $modalID + 1;
print '<tr>';
print '<td>'.$row["col1"].'</td>';
print '<td>'.$row["col2"].'</td>';
print '<td><span class="glyphicon glyphicon-pencil" style="float: right !important"></span></td>';
print '</tr>';
echo '<div class="modal fade" id="editModal'.$modalID.'" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Delete</h2>
</div>
<div class="modal-body">
<form action="update.php" method="get">
<div class="row">
<div class="col-xs-6">
col1:
</div>
<div class="col-xs-6">
<input type="text" value="'.$row["col1"].'" id="col1" name="col1" />
</div>
</div>
<div class="row">
<div class="col-xs-6">
col2:
</div>
<div class="col-xs-6">
<input type="text" value="'.$row["col2"].'" id="col2" name="col2" />
</div>
</div>
<input type="hidden" id="ref" name="ref" value="refpage" />
<input type="hidden" name="id" value="'.$ID.'" />
<input class="btn btn-md" type="submit" id="update" name="update" value="Update" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-md" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>';}
Hope this helps someone. And in case anyone has an idea what was wrong with my original idea, I'd be happy to read the answer. I still think in place updates would be much cooler.

Categories