Updating database with jEditable & mysqli - php

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.

Related

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.

undefined index error while trying to get value returned from the link?

I know its a duplicate one but i'm getting this error while trying to fetch data passed from a link..I dont know how to resolve it.
here is my code:
add_package.php
echo "<td><a href='delete.php?name3=" . $row['package_type']."&id3=".$row['p_id']."'>Delete</a></td>";
echo "<td><a href='edit_package.php?name3=" . $row['package_type']."&id3=".$row['p_id']."'>Update</a></td>";
here the delete link works perfectly but when i click update it takes to the edit_package page where i'm getting an undefined error..
code for edit_package.php:
<?php
include('db.php');
$id4 = $_GET['id3'];//update the page
$name4 = $_GET['name3'];//helps to update the package
echo $id4;
echo $name4;//getting values here correctly..
if(isset($_POST['submit']) )
{
$package=$_POST['package'];
if (ctype_alnum($package) && !empty($id4) && !empty($name4))
{
$sql13="select package_type,id from tbl_package where package_type='".$package."'";
$retvali=mysql_query($sql13,$conn);
$num_rows1 = mysql_num_rows($retvali);
if ($num_rows1 == 0 || $num_rows1=="")
{
$sql = "Update tbl_package set package_type='".$package."' where package_type='".$name4."' and p_id='".$id4."'";
$retval = mysql_query( $sql, $conn );
?><script>alert("Updated Successsfully");window.location ='http://localhost/demo/add_package.php';
</script><?php
}
else
{
?><script>alert("Already Exists");window.location ='http://localhost/demo/add_package.php';
</script><?php
}
}
else
{
?><script>alert("enter only letters and numbers")</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<form id="form-validation" action="edit_package.php" method="post" class="form-horizontal" enctype="multipart/form-data" novalidate="novalidate">
<div class="col-md-6">
<div class="block" style="height:500px;">
<div class="block-title">
<h2><strong>State the Package For Tour</strong></h2>
</div>
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label" for="val_username">Update Package <span class="text-danger">*</span></label>
<div class="col-md-6">
<div class="input-group">
<input type="text" id="package" name="package" class="form-control" required >
<span class="input-group-addon"><i class="fa fa-user"></i></span>
</div>
</div>
</div>
<div class="form-group form-actions">
<div class="col-md-8 col-md-offset-4">
<input type="submit" class="btn btn-info btn-primary " value="Update" name="submit">
</div>
</div>
</fieldset>
</form>
When i press update button i'm getting an undefined error i dont know why?..Thanks in advance
I'm attaching an image to it..
Try to change the <form>'s action URL to include your GET varaibles:
<form id="form-validation" action="edit_package.php?id3=<?php echo $_GET['id3']; ?>&name3=<?php echo $_GET['name3']; ?>" method="post" class="form-horizontal" enctype="multipart/form-data" novalidate="novalidate">
PLEASE NOTE: This is extremely unsafe! You need to sanitize ALL user input before using it. My example above, dis-regards security, and simply is to demonstrate my point. GET and POST data, are user variables. A malicious user could put bad code in the URL (ie ?name3=<badcode>) and it would be printed on the page, well in the source code, which they could easily pop out of. Also, in SQL queries, you need to escape the data or use prepared statements.
You should not be using mysql functions, switch to MySQLi or PDO. MySQL has been killed for a while now..
These are just asking for you to get hacked:
$sql13="select package_type,id from tbl_package where package_type='".$package."'";
and..
$sql = "Update tbl_package set package_type='".$package."' where package_type='".$name4."' and p_id='".$id4."'";
You are vulnerable to SQL injections, would could easily allow a malicious attacker to add/edit/view/delete data in your database.
The problem is, you have $package (which is raw data from POST) and $id4 and $name4 (which is raw data from GET) in your SQL query.
You would use mysql_real_escape_string() on them, but you should be using mysqli or PDO anyways...
Example:
$name4 = mysql_real_escape_string($_GET['name3']);
It's confusing, I don't know what the GET variable is called name3 but you assign it the variable $name4.. Whoever (even you) comes along later on will be lost in your code.
Updated:
Try this code. I swapped your GET for POST in your php code, and passed the GET variables from your URL as hidden fields in your form.
<?php
include('db.php');
if(isset($_POST['submit']) )
{
$package = mysql_real_escape_string($_POST['package']);
$id4 = mysql_real_escape_string($_POST['id3']); // why is variable named id4 but its id3??
$name4 = mysql_real_escape_string($_POST['name3']); // why is variable $name4 but its name3??
if (ctype_alnum($package) && !empty($id4) && !empty($name4))
{
$sql13 = "SELECT package_type,id FROM tbl_package WHERE package_type='$package' LIMIT 1";
$retvali = mysql_query($sql13, $conn);
$num_rows1 = mysql_num_rows($retvali);
if ($num_rows1 == 0 || $num_rows1=="")
{
$sql = "Update tbl_package set package_type='$package' WHERE package_type = '$name4' AND p_id='$id4'";
$retval = mysql_query( $sql, $conn );
echo '<script>alert("Updated Successsfully");window.location = "http://localhost/demo/add_package.php";</script>';
} else {
echo '<script>alert("Already Exists"); window.location = "http://localhost/demo/add_package.php";</script>';
}
} else {
echo '<script>alert("enter only letters and numbers");</script>';
}
}
?>
<form action="edit_package.php" method="post" enctype="multipart/form-data" novalidate="novalidate">
<input type="hidden" name="id3" value="<?php echo htmlspecialchars($_GET['id3'], ENT_QUOTES | ENT_HTML5); ?>" />
<input type="hidden" name="name3" value="<?php echo htmlspecialchars($_GET['name3'], ENT_QUOTES | ENT_HTML5); ?>" />
Update Package: <input type="text" id="package" name="package" class="form-control" required >
<input type="submit" class="btn btn-info btn-primary " value="Update" name="submit">
</form>
I removed your HTML formatting from the form. You had div tags that didn't match up.. I can't see your whole code, but it looks like you have a bunch of div's that are messed up (ie: not closed where they should be). I also added mysql_real_escape_string() to the passed variables, and htmlspecialchars() to the GET variables echo'd in the hidden fields of your form. It's a start.
You might be able to make better sense of your code and troubleshoot errors, if you wrote your code a bit cleaner. Not trying to bash you :) Proper indentation, spacing, and formatting go a long way. It makes it easier on your eyes, and on yourself, in times like these..
I left your <script> tags because I assumed there was a reason your wanted to popup a message box.. I would just use header('Location: /path/to/where.php'); and pass your error message through a session variable or something, like an array of errors, which you get, clear, and show on the page the errors.

Why does my entire code disappear if I remove my form tag?

NOTE: Here is the fiddle, and since that looks awful, Here is the full screen result
Here is the fiddle after I do my changes on my computer and generate the html, and here is the full screen
Note on the fiddle:
I added the entire code into the fiddle since it won't work unless it's the whole code.
Thanks to anyone who will give hints! My only problem here is the one in the title, nothing else. :)
=====
I'm working on an undergraduate project to create an interface that accesses a database (though I'm not a CS student). My code is behaving very strangely. I have code for one window that displays one large div encasing three divs side byside, which is structured this way:
<div id="container">
<div id="window1">
<form></form> //my buttons
</div>
<div id="window2">
<form></form> //my body
</div>
<div id="window3">
//I havent written anything here yet
</div>
</div>
But I realized it makes more sense for me to encase them all in just one form. Like this:
<div id="container">
<form>
<div id="tab1">
</div>
<div id="tab2">
</div>
<div id="tab3">
</div>
</form>
</div>
So in the first case, this is what my website looks like:
But after I change it:
What's weird is, if I put forms in my forms, it starts working again! So this works:
<div id="container">
<form>
<div id="tab1">
<form></form>
</div>
<div id="tab2">
<form></form>
</div>
<div id="tab3">
</div>
</form>
</div>
If you need to see my code, I actually am using PHP to generate the html since it's a lot, so (this is the method that doesn't work):
<div id="search_separator" class="upper_tab">
<form action="" method="post">
<div id="button_container">
<?php
$tbs_a = 1;
$tbs_name = 'table_selector';
$printRetain_button = '';
$fg = input::get($tbs_name);
echo '<label for="',$tbs_name,'"></label>';
foreach($table_arrays AS $ta => $table){
$tbs_val = "table".$tbs_a;
if($tbs_a==1){
echo '<div class="button"><input type="radio" class="tabl_selector" name="',$tbs_name,'" value="',$tbs_val,'" checked="default"/><div class="table_selector">',$ta,'</div></div>';
}else{
echo '<div class="button"><input type="radio" class="tabl_selector" name="',$tbs_name,'" value="',$tbs_val,'"';
if($tbs_val == $fg){
echo ' checked="checked"';
}//make a separate echo for table1 radio button with the default turned on.
echo '/><div class="table_selector">',$ta,'</div></div>';
}
$tbs_a++;
}
?>
<!--<input type="submit" name="submit" value="submit" />-->
</div>
<div id="search_container" class="content">
<?php
$a = 1;
$search = DB::getInstance();
foreach($table_arrays AS $t_a => $table){
$y = 1;
echo '<div id="table',$a,'_content" class="table_content">';
echo "<h2>",$t_a,'</h2><table align="center" id="actualhtmltable">';
foreach($table AS $t => $field){
$name = "table".$a."_field".$y;
$val_sticky = escape(input::get($name));
$val_find = $search->get($t_a, array($t, '=', input::get($name)));
//$val_find = $search->get('user_credentials', array('user_id', '=', 28))->results();
if(!empty($val_find)){
$val = array();
foreach($val_find[0] AS $vfz){
$val[] = $vfz;
}
} elseif(!empty($val_sticky)){
$valu = $val_sticky;
} else {
$valu = "";
}
echo '<tr><div><td>',$t,'</td><td><label for="',$name,'"><input type="text" class="entryfields" name="',$name,'" value="';
if(!empty($val[$y-1])){
echo $val[$y-1];
} else {
echo $valu;
}
echo '" /></label></td></div></tr>';
$y++;
}
echo '</table></div>';
$a++;
}
?>
<div class="Tableformbutton">
<div class="FindModeButtons">
<input type="Submit" name="find" value="Find" id="find" class="findupdateinsert" />
<input type="Submit" name="update" value="Update" id="update" class="findupdateinsert" />
</div>
<input type="Submit" name="insert" value="Insert" id="insert" class="findupdateinsert" />
</div>
</div>
<div id="other_container">
<!--find mode on and other functionalities-->
</div>
<div class="hassubmit" id="searchsubmit_container">
<input type="button" id="findmodetoggler" name="query_submit" value="Toggle Find Mode" class="top_buttons" />
<a href="#" class="tip"><input="button" name="Help" value="Help" class="top_buttons" id="help" />
<span> Click "Toggle Find Mode" to toggle between find/update and insert buttons.<br />
If find mode is on, you will be able to look for existing records and update them. Otherwise, you can only insert new entries.<br />
Find mode is off by default.</span>
<p>Need Help?</p>
</a>
</div>
</form>
</div>
As far as I can tell, it is supposed to work! I don't see anything in my HTML, and as for my CSS, I have styled nothing about forms in there, only divs and labels and input tags. What could be wrong?
Thanks to anyone who'll give hints or ideas!
I found the solution, which really is just so simple. But, I don't know why it happened this way.
I added an id="search_form" into the form I need, then used CSS to say .search_form{ height: 100% } as apparently, when the form was made, it made the height of everything into just a few pixels. This is weird, but at least I found the answer.

PHP form not saving to table

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.

Categories