simon
simon

Reputation: 2377

How to make an inline editable content?

I have a list of products that I wish to be editable. When a user hits the edit button, then the content of only the selected product needs to be changed (for example to a textbox so the user can edit the title on the fly). But how do I prevent php to echo for example a textbox to all the products- I guess it would do that automatically?

I also guess that i should use some Jquery stuff to make the content editable :P ?

The list is being looped like this:

$items = $mysqli->query("SELECT product_name, product_id FROM products");
  while($products = $items->fetch_assoc(){
    echo $products['product_name'];
    echo '<a href="editindiv">Edit me</a>';
  }

Upvotes: 0

Views: 733

Answers (2)

Jonty
Jonty

Reputation: 11

Not necessarily the most efficient, but if there aren't a huge number of products how about including a simple form for each product but just hiding it until the 'Edit' link is clicked?

The list/forms:

$items = $mysqli->query("SELECT product_name, product_id FROM products");
while($products = $items->fetch_assoc(){
  echo "<span>" . $products['product_name'] . "</span>";
  echo "<a class='editButton'>Edit</a>";
  echo "<form action='products.php' method='post' style='display: none;'>
        <input type='hidden' name='product' value='" . $products['prodcut_id'] . "' >
        <input type='text' name='title' value='" . $products['product_name'] . "' >
        <input type='submit' value='Update' >
        </form>";
  echo "<br/>";  
}

The jQuery:

$(".editButton").click(function(){
  //Hide the text entry and the edit link
  $(this).prev().hide();
  $(this).hide();
  //Show the form
  $(this).next().show();
});

If you'd rather not reload the page to submit changes you could submit them via ajax too for a more dynamic user experience.

Upvotes: 1

As your first commenter pointed out, PHP alone is not enough here. You'll need on-page JS code that can communicate the changes in the browser, and a PHP script that can take those changes and work them back into the database. You can either write that yourself, or use proven libraries that exist specifically for this purpose, like http://backbonejs.org/ or http://angularjs.org/

These are model/view frameworks that let you show a view of your database data on a page, while keeping them editable, updating the database records when you update the entry online. But be warned: if you've never worked with MVC frameworks, you get to look forward to probably being very confused at first. The approach is completely different from the much simpler "get data from db with PHP, generate page content, send off to client, the end" approach.

Upvotes: 1

Related Questions