Why is php script not deleting the table? - javascript

I've quickly made a page that shows the current items in the database. I've created the function to adjust stocks levels but I am now trying to add the function to delete items. For some reason all it does is reduce the stock level to 0 but doesn't delete the item from the database.
Also would it be possible/better to put the code the generates the table into another file and load it here? As I need it to auto update when you run either the stock update or deletion function.
AJAX/HTML CODE
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$('#dataSubmit').on('submit',function(e){
$.ajax({
url:'files/update.php',
data:$(dataSubmit).serialize(),
type:'POST',
success:function(data){
console.log(data);
if(data != "Error") {
$("#data").html(data).show().fadeOut(9000);
}
else {
$("#data").html(data).show().fadeOut(9000);
}
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
document.getElementById("dataSubmit").reset();
});
});
$(document).ready(function(){
$('#deleteItem').on('dsubmit',function(e){
$.ajax({
url:'files/delete.php',
data:$(deleteItem).serialize(),
type:'POST',
success:function(data){
console.log(data);
if(data != "Error") {
$("#datad").html(data).show().fadeOut(9000);
}
else {
$("#datad").html(data).show().fadeOut(9000);
}
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
document.getElementById("deleteItem").reset();
});
});
</script>
</head>
<body>
<h2> Update Stock Levels </h2>
<form name="dataSubmit" id="dataSubmit" action="">
Product ID: <input type="number" name="Product_ID" value=""><br>
New Stock Amount: <input type="text" name="Product_Stock" value=""><br>
<input type="submit" name="submit" >
<div id="data"></div>
<h2> Delete Items </h2>
<form name="deleteItem" id="deleteItem" action="">
Product ID: <input type="number" name="Product_ID" value=""><br>
<input type="submit" name="dsubmit" >
<div id="datad"></div>
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Product Name</th><th>Product Description</th> <th>Product Price</th><th>Product Stock Amount</th></tr>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cms";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Product_ID, Product_Name, Product_Desc, Product_Price, Product_Stock FROM Products");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
</body>
</html>
PHP CODE
<?php
$dsn = 'mysql:host=localhost;dbname=cms';
$user = 'root';
$password = '';
try {
$pdo = new PDO($dsn, $user, $password);
$pdo ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "DELETE FROM Products WHERE Product_ID = :Product_ID";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Product_ID', $_POST['Product_ID'], PDO::PARAM_INT);
$stmt->execute();
?>

You are not binding to a submit event on the delete action, you have a typo
$('#deleteItem').on('dsubmit',function(e){
^
The form is just submitting instead.

Related

Store name and value of a Button in a mysql table row

I've been hanging on this problem for 3 days and just can't solve it. It seems relatively simple, but unfortunately, I can't do it, because I'm a noob.
I would like to use the button's onclick function to get its 2 pieces of information
```html
<input id="'.$row['id'].'" type="button" value="Pause" name="'.$row['name'].'" onclick="pushDataToDB()">```
name = "'. $ row [' name '].'" [the name reference from a database
table]
and value="Pause"
this two informations i would like to store in some other database table.
I have tried to solve this problem in different ways.
I have tried to store in different ways the event.target.name & event.target.event javascript output in PHP Variables and then use it in the mysql insert line but i failed.
I have tried to post the value to the ajax.php then store the value in a PHP variable and use this as Value to push it to the database, but this also doesn't work
index.php
<div class="button2">
<form action="ajax.php" method="POST">
<input id="'.$row['id'].'" type="button" value="Pause" name="'.$row['name'].'" onclick="pushDataToDB()">
</Form>
</div>'
script.js:
function pushDataToDB() {
$.get("ajax.php");
return false;
}
ajax.php
<?php
include_once ('dbh.php');
if(isset($_POST['name'])){
$sqlAufPause = "INSERT INTO aktuellaufpause (name, pausenart) VALUES ('$name', 'BP')";
}
if ($conn->query($sqlAufPause) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
I would say this is the reason, why the name Value is empty,
but i don't know how to fix ist..
emptyNameValue
You can use JQuery + AJAX to perform asynchronous POST
<?php
$con = mysqli_connect("localhost", "root", "", "testdb");
$query = mysqli_query($con, "SELECT * FROM mytable WHERE id = 1");
$row = mysqli_fetch_assoc($query);
print_r($row);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="button2">
<form id="frm">
<input id="<?php echo $row['id'] ?>" type="button" value="Pause" name="<?php echo $row['name'] ?>" onclick="pushDataToDB()">
</Form>
</div>
</body>
<script type="text/javascript">
function pushDataToDB() {
var name = "<?php echo $row['name'] ?>";
var value = "Pause";
$.ajax({
url: "ajax.php",
type: "POST",
data: {
"name": name,
"value": value
},
success: function(e) {
if (e == "1") {
alert("Success!");
} else {
alert("error!");
}
}
});
}
</script>
</html>
ajax.php
<?php
$con = mysqli_connect("localhost", "root", "", "testdb");
$name = $_POST['name'];
$value = $_POST['value'];
$query = "INSERT INTO mytable(name, value) values('$name','$value')";
$result = mysqli_query($con, $query);
if ($result) {
echo "1";
} else {
echo "Error!";
}
EDITTTT****
I changed
var name = "<?php echo $row['id'] ?>";
to
var name = "<?php echo $row['name'] ?>";
since it is the "name" you want stored in the database
I solved the problem this way.
Thank you so much!!!
index.php
<?php
$sql = "SELECT * FROM `DB-TABLENAME` ORDER BY `VALUE1`, `VALUE2`";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td>";
echo '<input style="margin: 0 auto 6px 17px;" type="checkbox" id="scales" name="scales">';
echo "</td>";
echo "<td>";
echo $row['VALUE1'];
echo "</td>";
echo "<td>";
echo $row['VALUE2'];
echo "</td>";
echo "<td>";
echo '<div class="button1">
<input id="'.$row['id'].'" type="button" value="BP" name="'.$row['VALUE2'].'" onclick="pushDataToDB()">
</div>';
echo "</td>";
echo "<td>";
echo '<div class="button2">
<form id="frm">
<input id="'.$row['id'].'" type="button" value="Mittagspause" name="'.$row['name'].'" onclick="pushDataToDB()">
</form>
</div>';
echo "</td>";
echo "</tr>";
}
} else {
echo "there are no comments";
}?>
<script type="text/javascript">
function pushDataToDB() {
var name = event.target.name;
var value = event.target.value;
$.ajax({
url: "ajax.php",
type: "POST",
data: {
"name": name,
"value": value
},
success: function(e) {
if (e == "1") {
alert("Success!");
} else {
alert("error!");
}
}
});
}
</script>
ajax.php
<?php
include_once('dbconnectioncredentials.php');
$con = mysqli_connect($servername, $username, $password, $dbname);
$name = $_POST['VALUE1'];
$value = $_POST['VALUE2'];
$query = "INSERT INTO aktuellaufpause (VALUE1, VALUE2) VALUES ('$name','$value')";
$result = mysqli_query($con, $query);
if ($result) {
echo "1";
} else {
echo "Error!";
}
?>

How to link my simple jQuery Input with PHP script and Store data into a MYSQL DB?

What I'm trying to do is very simple.
Have a simple input, that allows me to input a name+link, add it to a list and save it to a DB so it's saved.
In my HTML file I currently have:
<form id="form">
<input id="create-input" type="text" placeholder="To do">
<input id="create-link" type="text" placeholder="http://">
<button id="submit" type="button">Add Item</button>
</form>
In my JS file I have:
$(function(){
$('#submit').on('click', addListItem);
});
function addListItem() {
// Grab Input Data
var text = $('#create-input').val();
var link = $('#create-link').val();
// Creating To Do List
$('#todo').append('<li>' +text+' - '+link+ ' <button class="delete">Edit</button> <button class="delete">Delete</button> <button class="delete">Bukkaked!</button></li>');
$('#create-input').val('');
$('#create-link').val('http://');
}
In my PHP file (connecting to DB) I have:
<?php
$servername = "localhost";
$database = "bucketlist";
$username = "bucketuser";
$password = "125632";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "INSERT INTO bucketlist (item, link) VALUES ('Thom', 'www.google.com')";
// Check for Success
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
// Check for Fail
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Now I know I need to somehow pass the vars (text and link) through to the PHP file:
$sql = "INSERT INTO bucketlist (item, link) VALUES ('Thom', 'www.google.com')";
But I have no idea how.
Any tips?
Why do you need JQuery you can pass values using php only
here is a change in your code:-
<form id="form" method="post" action="process.php">
<input id="create-input" name="item" type="text" placeholder="To do">
<input id="create-link" name="link" type="text" placeholder="http://">
<button id="submit" type="button">Add Item</button>
</form>
<ul>
<?php include('conn.php');
$sql = "SELECT * FROM bucketlist";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<li>Item-'. $row["item"].' & Link-'. $row["link"].'</li>';
}
} else {
echo "<li>No List</li>";
}
?>
</ul>
conn.php
<?php
$servername = "localhost";
$database = "bucketlist";
$username = "bucketuser";
$password = "125632";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
process.php
<?php
include('conn.php');
$item = $_POST['item'];
$item = $_POST['link'];
$sql = "INSERT INTO bucketlist (item, link) VALUES ($item,$link)";
// Check for Success
if (mysqli_query($conn, $sql)) {
header('location:yourpage.php');
}
// Check for Fail
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Hope this helps.
Use ajax to post the values of the item and link in your html form to your PHP script.
Something like :
var myItem = $('#create-input').html();
var myLink = $('#create-link').html();
$.ajax({
type: 'POST',
url: 'https://yoururl/api/post.php',
data: {item:myItem,link:myLink},
success: SuccessCall,
error : FailureCall,
cache:false,
async:true,
dataType: 'html'
});
function SuccessCall(data,status){
alert("response from server is "+data);
}
function FailureCall(data,status){
alert("Server connection error");
}
Use the PHP script posted by SYB to retrieve the values of item and link that were sent from your html form.

Get the value of input field through ajax then pass it to php

I am new with ajax somebody help me I want to create a form that include input field.
Whenever I click the button I will get the value of input field and it declared it as data in AJAX and the value from ajax it pass to PHP script. It will display a table.
My question is how to get the value of input field and declared it as data in AJAX. After click the table will declared in success in AJAX Script that will show a table.
Thank you in advance
UPDATE:
#J_D, Here's my html code for my form:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<table cellpadding="15px">
<tr>
<td>Transmittal #</td>
<td><input type="text" class="form-control" style="padding-left:5px;" name="transmittal_number_inquiry" id="transmittal_number_inquiry" class="transmittal_number_inquiry" onKeyPress="return isNumberKey(event)" required></td>
</tr>
</table>
<div style="float:right; padding-right:110px; padding-top:10px;">
Inquire
<?php /*?><input type="submit" class="btn btn-info" data-toggle="modal" id="btn-inquire-transmittal-number" name="btn-inquire-transmittal-number" data-backdrop="false" value="Inquire"><?php */?>
<?php /*?><button type="submit" class="btn btn-info" data-toggle="modal" id="btn-inquire-transmittal-number" name="btn-inquire-transmittal-number" data-backdrop="false">Inquire</button><?php */?>
</div>
</form>
Here's my AJAX Code:
$(document).ready(function(){
$('.btn-inquire-traensmittal-number').click(function(){
$inputtextval = $('#transmittal_number_inquiry').val();
$.ajax({
type: 'POST',
url: getTransmittalNum.php,
data: {'transmittal_number_inquiry' : $inputtextval},
success: function(res){
}
});
});
});
Here's the getTransmittalNum.php code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "etransmittal";
$selectedTransmittal = $_GET['q'];
$con = mysqli_connect($servername,$username,$password,$dbname);
if(!$con){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['inquire-transmittal-number'])){
$query = "SELECT en.transid, en.transdate, CONCAT(userlist.lname, ', ', userlist.fname, ' ', userlist.mname) AS sender_name,
userlist.`department`, en.document_number, doctype.document_type, doctype.document_description, vendor.`vendor_name`, en.`remarks`,
en.status_id, stat.status_name, en.total_amount
FROM tbl_encode_transmittal en
LEFT JOIN tbl_vendor vendor ON vendor.`vendor_id` = en.vendor_id
LEFT JOIN tbl_doctype doctype ON doctype.`doc_id` = en.doctype_id
LEFT JOIN tbl_userlist userlist ON userlist.userid = en.sender_id
LEFT JOIN tbl_userlist userlist1 ON userlist1.userid = en.`receiver_id`
LEFT JOIN tbl_status stat ON stat.status_id = en.status_id
WHERE en.`transid` = '{$_POST['transmittal_number_inquiry']}'";
$result = mysqli_query($con, $query);
$rows = array();
if($result){
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
}
else{
echo 'MYSQL Error: ' . mysqli_error();
}
$json = json_encode($rows);
echo $json;
mysqli_close($con);
}
?>
Try following code :
$(document).ready(function(){
$('#btn-inquire-transmittal-number').click(function(){
$inputtextval = $('#transmittal_number_inquiry').val();
$.ajax({
type: 'POST',
url: 'getTransmittalNum.php', // wrap code with quote
data: {'transmittal_number_inquiry' : $inputtextval},
dataType : 'json', // expecting result type json
success: function(res){
// once you got result,
// populate table here
}
});
});
});
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "etransmittal";
//$selectedTransmittal = $_GET['q']; //<---- u need this?????
$con = mysqli_connect($servername,$username,$password,$dbname);
if(!$con){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['transmittal_number_inquiry'])){ // <-- check for existence
$query = "SELECT en.transid, en.transdate, CONCAT(userlist.lname, ', ', userlist.fname, ' ', userlist.mname) AS sender_name,
userlist.`department`, en.document_number, doctype.document_type, doctype.document_description, vendor.`vendor_name`, en.`remarks`,
en.status_id, stat.status_name, en.total_amount
FROM tbl_encode_transmittal en
LEFT JOIN tbl_vendor vendor ON vendor.`vendor_id` = en.vendor_id
LEFT JOIN tbl_doctype doctype ON doctype.`doc_id` = en.doctype_id
LEFT JOIN tbl_userlist userlist ON userlist.userid = en.sender_id
LEFT JOIN tbl_userlist userlist1 ON userlist1.userid = en.`receiver_id`
LEFT JOIN tbl_status stat ON stat.status_id = en.status_id
WHERE en.`transid` = '{$_POST['transmittal_number_inquiry']}'";
$result = mysqli_query($con, $query);
$rows = array();
if($result){
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
}
else{
echo 'MYSQL Error: ' . mysqli_error();
}
$json = json_encode($rows);
echo $json;
mysqli_close($con);
}
?>

Uncaught ReferenceError: getPrice is not defined

I am trying to run a script. The script needs to show me data from the database. In my script I am using 1 dropdown and 1 textbox. When I change the selected value (product) in my dropdown it needs to show the price of the selected value. The price needs to be shown in the textbox.
The script is not working. I tried to figure out what the problem is. I used developer console tool of my browser. The developer console tool gives me the error:
Uncaught ReferenceError: getPrice is not defined | onchange # (index):1
Can someone help me with this problem?
The pages that I am using for this script are the following pages:
index.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM forms";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control select2' id='product1' name='product1' onChange='getPrice(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<body>
<!-- Your text input -->
<input id="product_name" type="text">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.product1 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
</body>
</html>
get.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error)
{
die('Connection failed: ' . $conn->connect_error) ;
}
else
{
$product1 = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT) ;
$query = 'SELECT price FROM forms WHERE id=" . $product1 . " ' ;
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo "<input type='text' value='";
echo json_encode($result['price']);
echo "'>";
}
else
{
echo "<input type='text' value='";
echo json_encode('no results') ;
echo "'>";
}
}
?>
First close <script> tag :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Your scripts tags should be before </html> and inside <body> tag :
<html>
<body>
<!-- Your text input -->
<input id="product_name" type="text">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.product1 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
</body>
</html>
The PHP condition could be simple and you don't need any json encoding, e.g:
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo $result['price'];
}else{
echo 'no results';
}
Hope this helps.

Updating Edited Value Using Jquery/PHP/Mysql

can some one help me out in updating edited value in mysql db using jquery/php.
I have three buttons edit/save/cancel
when i click on edit button span data pushed into input text and edit button replaced with save button!!
when i click on edit button i'll get span data in my text box with save and cancel button but when i try to update using save button its not updating in my db and in UI
Code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function showdata()
{
$.ajax({
url:"pages/feeds.php",
type:'post',
async:false,
data:{
showtable:1
},
success:function(re){
$('#showdata').html(re);
}
});
}
$('#orders').delegate('.editOrder','click',function(e){
e.preventDefault(e);
var $li = $(this).closest('li'); $li.find('input.name').val($li.find('span.name').html());
$li.addClass('edit');
});
$('#orders').delegate('.cancelEdit','click',function(e){
e.preventDefault(e);
$(this).closest('li').removeClass('edit');
});
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
$.ajax({
url:"pages/feeds.php",
type:"post",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
$('#id').val(show.id);
$('#url1').val(show.url);
}
});
});
//Ends
//Update Starts
$('.update').click(function(){
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
$('input[type=text]').val('');
showdata();
},
error:function(){
alert('error in updating');
}
});
});
//UPdate Ends
</script>
<style type="text/css">
ul li .edit{
display:none;
}
ul li.edit .edit{
display:initial;
}
ul li.edit .noedit{
display:none;
}
</style>
</head>
<body>
<ul id="orders">
<?php
$sql = "select * from demo";
$result = mysql_query($sql);
while($row = mysql_fetch_object($result))
{
?>
<li>
<span class="noedit name" value='<?php echo $row->id;?>'><?php echo $row->url;?></span>
<input id="url1" class="form-control edit name" value="<?php echo $row->id;?>"/>
<a ide='<?php echo $row->id;?>' id="edit" class='editOrder' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update saveEdit' href='#' style='display:none;'>SAVE</a>
<a idd='<?php echo $row->id;?>' id="delete" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
</li>
<?php } ?>
</ul>
</body>
</html>
<?php
//Edit Starts
if(isset($_POST['editvalue']))
{
$sql = "select * from deccan where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
//Ends
//UPdate Starts
if(isset($_POST['update']))
{
$sql = "
update deccan
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
?>
Alright. I was still missing the following code from you, so you'll have to add these yourself:
The HTML element with parameter id="id" needed for $('#id').val(text.id);
The HTML element with parameter id="url1" needed for $('#url1').val(text.url);
The PHP response code for JS function showdata(); inside feeds.php
Since I don't have your database here, I was unable to test the code. It should work fine, but if anything is wrong, just let me know:
PHP file: index.php
<?php
// Include PDO class
include_once("pdo.class.php");
// Database connection settings
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "database");
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- CSS resources -->
<link rel="stylesheet" type="text/css" href="style.css">
<!-- Javascript resources -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="main.js"></script>
<title>Update Script</title>
</head>
<body>
<ul id="orders">
<?php
// Instantiate database
$db = new Database;
// Try getting data from database
Try {
// Query
$db->query("SELECT * FROM demo");
// Get results
$data = $db->resultset();
// Echo reults
foreach($data as $row){ ?>
<li>
<span class="noedit name" value="<?php echo $row['id']; ?>"><?php echo $row['url']; ?></span>
<input id="url1" class="form-control edit name" value="<?php echo $row['id']; ?>" />
<a data-ide="<?php echo $row['id']; ?>" class='editOrder' href="#" style="display:block-inline;">EDIT</a>
<a data-idu="<?php echo $row['id']; ?>" class='update saveEdit' href='#' style='display:none;'>SAVE</a>
<a data-idd="<?php echo $row['id']; ?>" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a data-idc="<?php echo $row['id']; ?>" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
</li>
<?php }
//Catch any database errors
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
?>
</ul>
</body>
</html>
Javascript file: main.js
$('#orders').delegate('.editOrder','click',function(e){
e.preventDefault();
var $li = $(this).closest('li');
$li.find('input.name').val($li.find('span.name').html());
$li.addClass('edit');
});
$('#orders').delegate('.cancelEdit','click',function(e){
e.preventDefault();
$(this).closest('li').removeClass('edit');
});
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('data-ide');
$.ajax({
url: "pages/feeds.php",
type: "POST",
data: 'editvalue=1&id='+IdEdit,
success: function(text){
$('#id').val(text.id);
$('#url1').val(text.url);
}
});
});
//Update Code
$('.update').click(function(){
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
url: "pages/feeds.php",
type: "POST",
async: false,
data: 'update=1&id='+id+'&upurls='+urls,
success: function(text){
$('input[type=text]').val('');
showdata();
},
error:function(){
alert('Error in updating');
}
});
});
function showdata(){
$.ajax({
url: "pages/feeds.php",
type: "POST",
async: false,
data: 'showtable=1',
success:function(text){
$('#showdata').html(text);
}
});
}
CSS file: style.css
ul li .edit{
display:none;
}
ul li.edit .edit{
display:initial;
}
ul li.edit .noedit{
display:none;
}
PHP file: feeds.php
<?php
// Include PDO class
include_once("pdo.class.php");
// Database connection settings
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "database");
// Instantiate database
$db = new Database;
// Edit
if(isset($_POST['editvalue']) && $_POST['editvalue'] == 1){
// Try getting data from database
Try {
// Query
$db->query("SELECT * FROM deccan WHERE id = :id");
// Prepare POST data (to prevent SQL injection)
$db->bind(":id", $_POST['id']);
// Get result
$data = $db->single();
// Set header JSON
header("Content-type:text/x-json");
// Return result
echo json_encode($rows);
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
} else if(isset($_POST['update']) && $_POST['update'] == 1){
// Try updating data in database
Try {
// Query
$db->query("UPDATE deccan SET url = :url WHERE id = :id");
// Prepare POST data (to prevent SQL injection)
$db->bind(":url", $_POST['upurls']);
$db->bind(":id", $_POST['id']);
// Execute Query
$db->execute();
// Return succes
echo 'updated successfully';
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
} else if(isset($_POST['showtable']) && $_POST['showtable'] == 1){
/*
This part was not included in your code, so write it
yourself using above data as examples
*/
}
?>
PHP file: pdo.class.php
<?php
Class Database {
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
return $this->error;
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function column(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_COLUMN);
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
public function beginTransaction(){
return $this->dbh->beginTransaction();
}
public function endTransaction(){
return $this->dbh->commit();
}
public function cancelTransaction(){
return $this->dbh->rollBack();
}
public function debugDumpParams(){
return $this->stmt->debugDumpParams();
}
}
?>
I would normally have two scripts (.php) files.
One to display the form and one to catch the submission (possibly via ajax)
You can have both in the same .php file but then you'd want to check before outputting any text whether you have any POST data to process.
If you go with two files
view file:
<html>
<body>
<form method="POST" action="path/to/formname_submit.php">
your form fields go here
<input name="somefield"/>
...
</form>
<script>
//your jquery code
....
</script>
<body>
</html>
submit file
<?php
if (empty($_POST['id'])){
die("no ID");
};
if (empty($_POST['editvalue'])){
die("no editvalue");
}
//get a database connection
$db = mysqli(DBHOST,DBUSER,DBPASS,DBNAME);
$db->set_charset("utf8");
// read in the POST data
//should do some more validation / anti SQL injection
$editvalue = $db->escape_string($_POST['editvalue']);
$id = intval($_POST['id']);
$sql = "UPDATE sometable SET `field` = '$editvalue' WHERE id=$id";
if ($db->query($sql)){
echo 'Success';
}
else {
echo 'UPDATE ERROR:'.$db->errno.': '.$db->error;
}
your jquery can now send the data to the second script and see if the data coming back from the call is 'Success' and display an error if it's not.

Categories