Update MySQL information as easy as possible

I will give you an example, how easy in nowadays can be information editing (let’s say in admin/user panels). No more endless and boring forms, now we got something new… Everything we need is jquery and it’s plugin called jeditable. So let’s start.
First create an info.php file and put there some content:
<html>
<head>
<title>This is document title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.jeditable.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function(){
$(".edit").editable("response_save.php", {
cancel : 'Cancel',
submit : 'OK',
indicator : '<img src="images/loading.gif">',
tooltip : 'Click to edit...'
});
});
//-->
</script>
</head>
<body>
< ?php
//fetching user
$username = get_user();
//format query
$sql = mysql_query("SELECT * FROM users WHERE username='$username'");
//printing results
$r = mysql_fetch_assoc($sql);
echo '<div class="edit other_class" id="users_age_'.$r['id'].'">'.$r['age'].'';
echo '<div class="edit other_class" id="users_address_'.$r['id'].'">'.$r['address'].'</div>';
echo '<div class="edit other_class" id="users_email_'.$r['id'].'">'.$r['email'].'</div>';
?>
</body></html>
I hope that all parts here are understandable, if no, feel free to ask.
Then let’s create another file called response_save.php:
< ?php
//here do not forget to check and format all data
$id = $_POST['id'];
$value = $_POST['value'];
/*
*Pay attention to info.php output, each div id is declared in that order: table_field_postID.
*This parameter sending via POST as "id", and that div value (innerHTML) is sending as "value"
*/
list($table, $field, $id) = explode('_', $id);
//mysql query
mysql_query("UPDATE $table SET $field='$value' WHERE id='$id'");
//printing answer
echo $value;
?>
In the first file jeditable plugin does his work, reformats all div elements with class “edit” and does them interactive. When you click them, input appears, and when you click them again, ajax query are sending to response_save.php, passing the special formated div id and it’s new value. Then all we have to do is just explode our data as we need and do a single query to mysql. That’s all, we have universal editor, first time it takes a little time to understand how it works, but when you do it, it will save a lot of time for you.
P.S. if you have an “_” symbol in your table name in script as exploding user symbol “*”.
P.P.S. do not forget to completely secure response_save.php! Use sessions and make check from where is query.
P.P.P.S. more useful examples at: http://www.appelsiini.net/projects/jeditable/default.html, and if you see jquery for the first time, do not forget to view it’s documentation: http://docs.jquery.com/Main_Page










1 Trackback(s)