2

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';
                }
            }
    ?>
9
  • 1
    Do you know that the mysql extension in php is deprecated ? Commented Sep 11, 2015 at 8:42
  • If you want to update the value in db, try using ajax Commented Sep 11, 2015 at 8:43
  • So, what have you tried yourself? So far all I see is the code for everything else. But nothing related to what you wish to achiev? Keep in mind dat Stack Overflow isn't here to do your work for you. We're here if you've got issues with whatever you've tried yourself. Commented Sep 11, 2015 at 8:47
  • @raveenanigam Thank You!! Im using Ajax Ive reedited my code Commented Sep 11, 2015 at 8:57
  • @icecub I've reedited my code, 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 any help is Appreciated ThankS Commented Sep 11, 2015 at 8:59

2 Answers 2

2

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();
    }
}

?>
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.