jeditable/datables/mysql

jeditable/datables/mysql

jamesgamesjamesgames Posts: 14Questions: 0Answers: 0
edited September 2010 in General
OK...

Allan, this is in follow up to an earlier posting about the need (my need, at least) for a very simple example code for using datatables with jeditable. I think such an example would REALLY be helpful to a lot of noobs such as me. I've read through and tried to figure out the numerous jeditable/datables/mysql questions on the board and have incorporated them into the following question/request.

I'm going to put what I'd like to see in such an example. You'll see it is very basic because most of the questions out there on the forum assume you're already beyond this point.

Here's what I'd like to see:

Assume a Database named "ExampleDatabase" with a table "ExampleTable" with the following structure:

UniqueRecordID (auto incrimenting/unique), CustomerName, AreaCode, State, NonEditableField, Zip. All of the fields are text except the first which is an integer. The NonEditable field should be displayed but not be able to be edited.

The table should NOT display the UniqueRecordID (nor should it edit it).

When you click on any displayed field it should edit, call "ajaxSave.php", save the record, and then update the table.

I've been very specific in the field and table names so that anyone looking at your example will know exactly what is going on. In some of the examples and postings, for instance, ID is used to specify the unique identifier for the element, fieldname, etc.

I envision both a server and client side example file, so we can all see how to bring this functionality to life. While it is true that every server side solution is going to be "unique" I think a complete example of at least one simple version would go a long way.

I've made another small donation to get your attention, but I would be willing to pay more as you deem necessary to compensate you for your time. Your program is truly amazing, and this will make it even more accessible and useful.

Many thanks,

James

Replies

  • allanallan Posts: 63,277Questions: 1Answers: 10,424 Site admin
    Hi James,

    Thanks for the donation! Yes I fully agree that this is something that would be beneficial to DataTables. As you note every server-side implementation will be different, which is why I've not done this yet - there will always need to be some customisation needed (and questions steaming from it), and there are actually several ways to implement it. Some will suit certain situations, others will suit other situations. jEditable will do one cell at a time for example, but you might want to be able to put the whole row into 'edit mode'.

    The basic principle is shown here: http://datatables.net/examples/api/editable.html . In this example you get the following parameters back on the server-side:

    value - value that is being set
    row_id - ID (presumably from a database sid)

    The one thing missing I guess is the column number (the db field). Is this the only thing missing for a full example, to be able to do a simple UPDATE?

    Regards,
    Allan
  • jamesgamesjamesgames Posts: 14Questions: 0Answers: 0
    edited September 2010
    Allan,

    I don't seem to be getting anywhere. I've posted 3 files here. The code that sets up the table, the code that populates the table and the code that is called when the file is to be updated.

    1)In my code NOTHING happens when I click on any of the column contents. Jeditables doesn't seem to kick in.

    2)Your example talks about using the fnCallDrawback. I have no idea how to code that, even after looking at the docs.

    I know there are lots of different ways to make this work, but I'm just looking for ONE simple, working example so I can figure it out from there.
  • jamesgamesjamesgames Posts: 14Questions: 0Answers: 0
    Here is the basic program
    [code]
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">



    Untitled Document


    @import "css/demo_page.css";
    @import "css/demo_table.css";









    var asInitVals = new Array();

    $(document).ready(function() {
    var oTable = $('#example').dataTable( {
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "zero_config_b.php",

    "sPaginationType": "full_numbers",


    });

    /* Apply the jEditable handlers to the table */
    $('td', oTable.fnGetNodes()).editable( 'SaveToFile.php', {
    "callback": function( sValue, y ) {
    var aPos = oTable.fnGetPosition( this );
    oTable.fnUpdate( sValue, aPos[0], aPos[1] );
    },
    "submitdata": function ( value, settings ) {
    return { "row_id": this.parentNode.getAttribute('id') };
    },
    "height": "14px"
    } );

    $("tfoot button").submit( function () {
    /* Filter on the column (the index) of this element */
    oTable.fnFilter( this.value, $("tfoot input").index(this) );
    } );


    $("a").click(function() {
    oTable.fnFilter( "A" );
    return false;
    });

    $(":button").click(function() {
    oTable.fnFilter( this.value );
    return false;
    });




    } );










    Stores Database











    Stores








    CustID
    Name
    City
    State
    Zip
    Phone



    <?php do { ?>


    <?php echo $row_Stores['CustID']; ?>
    <?php echo $row_Stores['Name']; ?>
    <?php echo $row_Stores['City']; ?>
    <?php echo $row_Stores['State']; ?>
    <?php echo $row_Stores['Zip']; ?>
    <?php echo $row_Stores['Phone']; ?>


    <?php } while ($row_Stores = mysql_fetch_assoc($Stores)); ?>




    CustID
    Name
    City
    State
    Zip
    Phone














    Initialisation code






    DataTables © Allan Jardine 2008-2010.






    [/code]
  • jamesgamesjamesgames Posts: 14Questions: 0Answers: 0
    Here is the file that populates the table

    [code]


    <?php

    // include or define your mysql config here

    $hostname_Andover = "localhost";
    $database_Andover = "andover";
    $username_Andover = "***";
    $password_Andover = "****";
    $Andover = mysql_pconnect($hostname_Andover, $username_Andover, $password_Andover) or trigger_error(mysql_error(),E_USER_ERROR);




    mysql_select_db( $database_Andover, $Andover ) or
    die( 'Could not select database '. $gaSql['db'] );


    // the columns to be filtered, ordered and returned
    // must be in the same order as displayed in the table
    $columns = array
    (
    "CustID",
    "Name",
    "City",
    "State",
    "Zip",
    "Phone"
    );


    // the table being queried
    $table = "stores";

    // any JOIN operations that you need to do
    $joins = "";

    // filtering
    $sql_where = "";
    if ($_GET['sSearch'] != "")
    {
    $sql_where = "WHERE ";
    $sql_where .= "Name LIKE '" . mysql_real_escape_string( $_GET['sSearch'] ) . "%' OR ";

    $sql_where = substr($sql_where, 0, -3);
    }

    // ordering
    $sql_order = "";
    if ( isset( $_GET['iSortCol_0'] ) )
    {
    $sql_order = "ORDER BY ";
    for ( $i = 0; $i < mysql_real_escape_string( $_GET['iSortingCols'] ); $i++ )
    {
    $sql_order .= $columns[$_GET['iSortCol_' . $i]] . " " . mysql_real_escape_string( $_GET['sSortDir_' . $i] ) . ", ";
    }
    $sql_order = substr_replace( $sql_order, "", -2 );
    }

    // paging
    $sql_limit = "";
    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    {
    $sql_limit = "LIMIT " . mysql_real_escape_string( $_GET['iDisplayStart'] ) . ", " . mysql_real_escape_string( $_GET['iDisplayLength'] );
    }
    $jno="SELECT SQL_CALC_FOUND_ROWS " . implode(", ", $columns) . " FROM {$table} {$joins} {$sql_where} {$sql_order} {$sql_limit}";


    $main_query = mysql_query($jno)
    or die(mysql_error());

    // get the number of filtered rows
    $filtered_rows_query = mysql_query("SELECT FOUND_ROWS()")
    or die(mysql_error());
    $row = mysql_fetch_array($filtered_rows_query);
    $response['iTotalDisplayRecords'] = $row[0];

    // get the number of rows in total
    $total_query = mysql_query("SELECT COUNT(CustID) FROM {$table}")
    or die(mysql_error());
    $row = mysql_fetch_array($total_query);
    $response['iTotalRecords'] = $row[0];


    // send back the sEcho number requested
    $response['sEcho'] = intval($_GET['sEcho']);

    // this line is important in case there are no results
    $response['aaData'] = array();

    // finish getting rows from the main query
    while ($row = mysql_fetch_row($main_query))
    {
    // put all of the data from the current row into aaData
    $response['aaData'][] = $row;

    }

    // prevent caching and echo the associative array as json
    header('Cache-Control: no-cache');
    header('Pragma: no-cache');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header('Content-type: application/json');
    echo json_encode($response);

    ?>


    [/code]
  • jamesgamesjamesgames Posts: 14Questions: 0Answers: 0
    Finally, here is the code that gets called to write the update down

    [code]


    <?php require_once('Connections/Andover.php'); ?>
    <?php
    if (!function_exists("GetSQLValueString")) {
    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
    {
    if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
    }

    $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

    switch ($theType) {
    case "text":
    $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
    break;
    case "long":
    case "int":
    $theValue = ($theValue != "") ? intval($theValue) : "NULL";
    break;
    case "double":
    $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
    break;
    case "date":
    $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
    break;
    case "defined":
    $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
    break;
    }
    return $theValue;
    }
    }

    $editFormAction = $_SERVER['PHP_SELF'];
    if (isset($_SERVER['QUERY_STRING'])) {
    $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
    }


    $updateSQL = sprintf("UPDATE stores SET Name=%s, city=%s, phone=%s, `state`=%s, zip=%s WHERE Custid=%s",
    GetSQLValueString($_POST['Name'], "text"),
    GetSQLValueString($_POST['city'], "text"),
    GetSQLValueString($_POST['phone'], "text"),
    GetSQLValueString($_POST['state'], "text"),
    GetSQLValueString($_POST['zip2'], "text"),
    GetSQLValueString($_POST['Custid'], "int"));

    mysql_select_db($database_Andover, $Andover);
    $Result1 = mysql_query($updateSQL, $Andover) or die(mysql_error());


    ?>



    [/code]
  • allanallan Posts: 63,277Questions: 1Answers: 10,424 Site admin
    The events aren't being attached (see the first top right FAQ: http://datatables.net/faqs ). Here is part of your code rewritten to use fnDrawCallback ( http://datatables.net/usage/callbacks#fnDrawCallback ):

    [code]
    var oTable = $('#example').dataTable( {
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "zero_config_b.php",
    "sPaginationType": "full_numbers",
    "fnDrawCallback": function () {
    $('td', this.fnGetNodes()).editable( 'SaveToFile.php', {
    "callback": function( sValue, y ) {
    var aPos = oTable.fnGetPosition( this );
    oTable.fnUpdate( sValue, aPos[0], aPos[1] );
    },
    "submitdata": function ( value, settings ) {
    return { "row_id": this.parentNode.getAttribute('id') };
    },
    "height": "14px"
    } );
    }
    });
    [/code]
    Allan
  • jamesgamesjamesgames Posts: 14Questions: 0Answers: 0
    Allan,

    I guess I give up. All I'm trying to do is get the edited value to post to the database, but I can't figure it out. You have said in a number of posts that since every application will want to save differently you don't (won't?) give any specific concrete example. Seems like there are a good number of us who can't get it to work without a working example.

    Take a look at these links:

    http://datatables.net/forums/comments.php?DiscussionID=592
    http://datatables.net/forums/comments.php?DiscussionID=2558&page=1
    http://datatables.net/forums/comments.php?DiscussionID=509



    I appreciate that you rewrote that section of code, and I read the faq you referenced. Did your code fix that issue? Or is it still something I need to do? I couldn't figure it out from the faq.

    I also haven't got a clue why my saving php file fails. Anyway. I really hoped that by a) making multiple donations b) offering to pay you what you thought such an example would be worth both failed, I will move on. Perhaps the jeditable/datatables fusion doesn't work after all and that is the reason you are so loathe to take it on.

    It seems I'm not alone. I hope as I said originally you'll post a real working mysql example.

    Good luck.
  • allanallan Posts: 63,277Questions: 1Answers: 10,424 Site admin
    Sorry to hear you seem a bit disillusioned! I can and will post a real working example for this soon (I can't right now as I'm travelling for business so what I can do is rather limited!). I was hoping to be able to steer you to a solution, so we can all learn on the way.

    As I noted, at the moment you have the following information being posted to you:

    value - value that is being set
    row_id - ID (presumably from a database sid)

    So a simple SQL query like:

    [code]
    'UPDATE table SET column='.$_POST['value'].' WHERE sid='.$_POST['row_id']
    [/code]
    should do the trick. The only think left to do is for the column to be either passed as a variable or defined in the PHP (of course there are a few security things which need to be considered, such as escaping the strings etc).

    Is this the only part you are struggling with, or is there something more?

    Also, yes the code I posted above will take care of the issue mentioned in the FAQ. Is it not working for you?

    Allan
  • allanallan Posts: 63,277Questions: 1Answers: 10,424 Site admin
    I've updated the editable example to include the column position in the submitted data now: http://www.datatables.net/examples/api/editable.html . A quick look up will then be able to convert this integer into a column name in the database (for example column 1 might be called "engines" - this is very installation dependent).

    With that it's now just a case of running the query above to update the database :-).

    Allan
  • jamesgamesjamesgames Posts: 14Questions: 0Answers: 0
    edited September 2010
    Sorry about the frustrated tone of yesterday's email. Chalk it up to a lot of dental work earlier in the day. I am sorry.

    I appreciate your help. I am trying to figure out what I can tell you that will help you to help me.

    I pasted in your revisions to my table's page.

    This is the current code I have in my SaveToFile.php.

    [code]
    <?php require_once('Connections/Andover.php'); ?>
    <?php
    $updateSQL='UPDATE stores SET name='.$_POST['value'].' WHERE sid='.$_POST['row_id'];
    mysql_select_db($database_Andover, $Andover);
    $Result1 = mysql_query($updateSQL, $Andover) or die(mysql_error());

    ?>
    [/code]

    This is what my table creating row looks like:

    [code]


    <?php echo $row_Stores['CustID']; ?>
    <?php echo $row_Stores['Name']; ?>
    <?php echo $row_Stores['City']; ?>
    <?php echo $row_Stores['State']; ?>
    <?php echo $row_Stores['Zip']; ?>
    <?php echo $row_Stores['Phone']; ?>


    [/code]


    I think the thing I'm missing is that I would assume that the receiving program needs to receive 3 pieces of information:
    1) the unique identifier for the row (in my case CustID)
    2) the fieldname being updated
    3) the value being updated.

    I am pretty sure I'm not doing it right.

    Also, and parenthetically, I've noticed that if I do a page source view of my table page none of the data shows. It is there on the screen when I view the page normally. Is this normal?

    I'm sorry to be a pain.
  • allanallan Posts: 63,277Questions: 1Answers: 10,424 Site admin
    Heh - no worries. Dental work is never (ever!) fun...

    Last bit first - you are using server-side processing, so the data is loaded after the page has - hence why it's not in the 'view source' - which is the originally loaded source. If you want to see the live DOM, use Firebug or something like that.

    t looks like you are getting close. If you do a print_r($_POST) - I presume that the row_id, column and value parameters are all there? If not, then the place to start is to figure out why not...

    Assuming it is: the next thing to do is to have a function which will convert the column integer into a db column name. Something like this:

    [code]
    function convertColInt( $i )
    {
    if ( $i == 0 ) return "CustID";
    else if ( $i == 1 ) return "Name";
    ... etc (using whatever your DB column names are!)
    }
    [/code]
    Then just call convertColInt with $name = convertColInt( $_POST['column'] );

    And remember to escape your MySQL input!!! :-)

    Allan
  • jamesgamesjamesgames Posts: 14Questions: 0Answers: 0
    Ok...

    Still no go, but let me ask you a couple of more questions that may help.

    First, where can you run that print_r($_POST) line to see the result. I tried putting it in the SaveToFile.php, but it doesn't seem to make a difference...

    Here is the current version of SaveToFile.php (w/o the print_r)

    [code]

    <?php require_once('Connections/Andover.php'); ?>
    <?php

    function convertColInt( $i )
    {
    if ( $i == 0 ) return "CustID";
    else if ( $i == 1 ) return "Name";

    }

    $MyValue = convertColInt( $_POST['column'] );
    $updateSQL='UPDATE stores SET name='. $MyValue .' WHERE sid='.$_POST['row_id'];
    mysql_select_db($database_Andover, $Andover);
    $Result1 = mysql_query($updateSQL, $Andover) or die(mysql_error());


    ?>
    [/code]
  • allanallan Posts: 63,277Questions: 1Answers: 10,424 Site admin
    You would need to look at the XHR response in Firebug to see the output from the print_r (since it just prints to stdout). Putting it anywhere in the file will do it.

    Try this - I've modified the SQL to use the column name from the function, rather than setting the 'name' column to the column name returned as well... :-)

    [code]
    <?php require_once('Connections/Andover.php'); ?>
    <?php

    function convertColInt( $i )
    {
    if ( $i == 0 ) return "CustID";
    else if ( $i == 1 ) return "Name";

    }

    print_r( $_POST );

    $column = convertColInt( $_POST['column'] );
    $updateSQL='UPDATE stores SET '.$column.'='. $_POST['value'] .' WHERE sid='.$_POST['row_id'];
    mysql_select_db($database_Andover, $Andover);
    $Result1 = mysql_query($updateSQL, $Andover) or die(mysql_error());


    ?>
    [/code]

    Allan
  • jamesgamesjamesgames Posts: 14Questions: 0Answers: 0
    edited September 2010
    Here is what is in the POST

    Array
    (
    [value] => 44444sdfsdf
    [id] =>
    [row_id] => null
    )


    I changed your sid to CustID in the SaveToFile.php

    Seems like this is the error, but I"m not sure what/how to fix.
  • allanallan Posts: 63,277Questions: 1Answers: 10,424 Site admin
    Okay, so there are two errors here, which I'm sure you can see. The first is that there is not 'column' variable in the post array. Did you make use of the updated example which includes this? And secondly the row_I'd is null. This would suggest that the TR elements don't have ids on them, or the getAttribute is looking at the wrong node (the example shows how this should work).

    Allan
  • viperiaviperia Posts: 3Questions: 0Answers: 0
    edited September 2010
    Hi all,

    Ive been watching this topic for a while now, and with your help we have figured alot out.
    so we thought we shared some code so you can aswell, we made alot of this variable so its a bit of a mess.

    ive got it writing to the right box, but is it only inputting numbers, so its saves the value, but only when its a number.

    edit: and that is solved, forgot tho quotes.

    viewtable.php
    [code]
    <?php

    require_once('Connections/vaplanning.php');

    include('inc/LoginCheck.php');
    include('inc/includes.php');

    $_SESSION["PageHistory"] = curPageURL();

    $Tablename = $_GET["Tablename"];

    $WorkTable = mysql_query("SELECT * FROM ".$Tablename." LIMIT 1", $vaplanning) or die(mysql_error());
    $row_WorkTable = mysql_fetch_assoc($WorkTable);
    $Numfields = count($row_WorkTable);

    $Count = 0;
    foreach ($row_WorkTable as $key=>$value) {
    $arr1[$Count] = $key;
    $Count++;
    };

    $_SESSION["TableView"] = $Tablename;
    $_SESSION["TableViewFields"] = $arr1;


    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">



    View <?php print($Tablename); ?>






    $(document).ready(function() {
    var oTable = $('#example').dataTable( {
    "bJQueryUI": true,
    "bSortClasses": false,
    "sPaginationType": "full_numbers",
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "server_processing.php",
    "sScrollY": 440,
    "bScrollCollapse": true,
    "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
    var id = aData[0];
    $(nRow).attr("id",id);
    return nRow;
    },
    "fnDrawCallback": function () {
    $('td', this.fnGetNodes()).editable( 'editable_ajax.php', {
    "callback": function( sValue, y ) {
    var aPos = oTable.fnGetPosition( this );
    oTable.fnUpdate( sValue, aPos[0], aPos[1] );
    },
    "submitdata": function ( value, settings ) {
    return {"row_id": this.parentNode.getAttribute('id'),
    "column": oTable.fnGetPosition( this )[2]
    };
    },
    "height": "14px"
    } );
    }
    } );
    } );


    @import "css/dv/table_page.css";
    @import "css/dv/table_table_jui.css";


    body { font-size: 62.5%; }
    div#users-contain { text-align:left; width: 700px; margin: 0px 0; }
    div#users-contain table { margin: 0em 0; border-collapse: collapse; width: 100%; }
    div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: 3px 10px; text-align: left; }












    <?php
    $Count = 0;
    Do {
    print(''.$arr1[$Count].'');
    $Count++;
    } while ( $Count < $Numfields);

    ?>






    <?php

    $Count = 0;
    Do {
    print('');
    $Count++;
    } while ( $Count < $Numfields);
    ?>








    [/code]

    editable_ajax.php
    [code]
    <?php
    require_once('Connections/vaplanning.php');
    session_start();
    $Fieldnames=$_SESSION['TableViewFields'];
    $ColumnName=$Fieldnames[$_POST['column']];

    // like i set in server_processing.php aswell is that my Indexed column is called Number instead of the usual ID.. So the only thing you have to do is change those 2 values to your indexed column name and your set.
    mysql_query("UPDATE ".$_SESSION['TableView']." SET ".$ColumnName."='".$_POST['value']."' WHERE Number=".$_POST['row_id'], $vaplanning);

    ?>
    [/code]
  • viperiaviperia Posts: 3Questions: 0Answers: 0
    edited September 2010
    server_processing.php part 1
    [code]
    <?php
    include('inc/LoginCheck.php');
    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    * Easy set variables
    */

    /* Array of database columns which should be read and sent back to DataTables. Use a space where
    * you want to insert a non-database field (for example a counter or static image)
    */


    $aColumns = $_SESSION["TableViewFields"];

    /* Indexed column (used for fast and accurate table cardinality) */
    $sIndexColumn = "Number";

    /* DB table to use */
    $sTable = $_SESSION["TableView"];

    /* Database connection information */
    $gaSql['user'] = "root";
    $gaSql['password'] = "";
    $gaSql['db'] = "vaplanning";
    $gaSql['server'] = "localhost";


    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    * If you just want to use the basic configuration for DataTables with PHP server-side, there is
    * no need to edit below this line
    */

    /*
    * MySQL connection
    */
    $gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password'] ) or
    die( 'Could not open connection to server' );

    mysql_select_db( $gaSql['db'], $gaSql['link'] ) or
    die( 'Could not select database '. $gaSql['db'] );


    /*
    * Paging
    */
    $sLimit = "";
    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    {
    $sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ".
    mysql_real_escape_string( $_GET['iDisplayLength'] );
    }


    /*
    * Ordering
    */
    if ( isset( $_GET['iSortCol_0'] ) )
    {
    $sOrder = "ORDER BY ";
    for ( $i=0 ; $i
  • viperiaviperia Posts: 3Questions: 0Answers: 0
    [code]
    /*
    * Output
    */
    $sOutput = '{';
    $sOutput .= '"sEcho": '.intval($_GET['sEcho']).', ';
    $sOutput .= '"iTotalRecords": '.$iTotal.', ';
    $sOutput .= '"iTotalDisplayRecords": '.$iFilteredTotal.', ';
    $sOutput .= '"aaData": [ ';
    while ( $aRow = mysql_fetch_array( $rResult ) )
    {
    $sOutput .= "[";
    for ( $i=0 ; $i
  • jamesgamesjamesgames Posts: 14Questions: 0Answers: 0
    Viperia,

    Thank you so much!!!!! I was able to take your code and with the addition of one more Session Variable make a "universal" table editor that passes the name of the table and the key field.

    Sorry it took so long to get back to you. My dad had a stroke the night before last and I've been at the hospital w/o a machine. Your code and help (and Allan, too) has really helped so much, and I'm sure will be of even more help to those who pass here again.

    Again, a thousand thank yous.
  • allanallan Posts: 63,277Questions: 1Answers: 10,424 Site admin
    Good to hear you got it working as needed!

    Hope your Dad makes a full and quick recovery.

    Regards,
    Allan
  • btwilli1btwilli1 Posts: 1Questions: 0Answers: 0
    James should share his final source code for his universal table editor!
  • alekslktaalekslkta Posts: 5Questions: 0Answers: 0
    Dear, Viperia,

    What the code is in vaplanning.php?

    Thank you very much!
  • michaeloconmichaelocon Posts: 1Questions: 0Answers: 0
    Allan, just want to say brilliant work on datatables and it has been a great use. Where as above is a complicated method of setting up a MYSQL database and JEDITABLE functionality. (Even JEDITABLE team have not perfected this updating db functionality)


    Below I have used submitdata to send values to save.php and below table sent out accordingly. Works perfect and have been very useful for my current project.

    Thanks again and hope the below helps others simply setup a database, JEDITABLE and datatables ability.


    save.php
    [code]
    <?php
    require_once('db-tools.php');
    session_start();

    $column = $_POST['col_id'];
    $id = $_POST['row_id'];
    $updateValue = $_POST['value'];

    mysql_query("UPDATE customer SET ".$column."='".$updateValue."' WHERE customer_id=".$id);

    echo $_POST['value'].' [cDB updated]';
    ?>
    [/code]


    JEDITABLE SETUP
    Have submitted data using row_id, col_id, and column using submitdata.
    [code]
    /* Apply the jEditable handlers to the table */
    $('td.edit', oTable.fnGetNodes()).editable( 'save.php', {
    indicator : 'Saving...',
    tooltip : "Double click to edit.",
    event : "dblclick",
    onblur : 'submit',
    "callback": function( sValue, y ) {
    var aPos = oTable.fnGetPosition( this );
    oTable.fnUpdate( sValue, aPos[0], aPos[1] );
    },
    "submitdata": function ( value, settings ) {
    return {
    "row_id": this.parentNode.getAttribute('id'),
    "col_id": this.getAttribute('id'),
    "column": oTable.fnGetPosition( this )[2]
    };
    },
    "height": "11px"
    } );
    [/code]

    TABLE
    Here ParentNode is set using the unique identifier. Each edit field ID is set using the relative database name.
    [code]
    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
    echo "";
    $dbID = $row['customer_id'];
    echo "".$row['customer_city'].", ".$row['customer_country']."";
    echo "".$row['customer_company']."";
    echo "" .$row['customer_contact']."";
    echo "".$row['customer_email']."";
    echo "".$row['customer_tel']."";
    echo "Edit - Delete";
    echo "";
    }

    [/code]
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    (but of course don't forget to sanitize your input values)

    [code]
    $column = mysql_real_escape_string($_POST['col_id']);
    $id = mysql_real_escape_string($_POST['row_id']);
    $updateValue = mysql_real_escape_string($_POST['value']);
    [/code]
  • ekooekoo Posts: 3Questions: 0Answers: 0
    Could anyone possibly provide a framework of what a typical connection file would look like, please? In terms of this example, what would /connections/vaplanning.php or dbtools.php look like?

    At the moment I have something like:
    [code]
    <?PHP

    $user_name = "user";
    $password = "pass";
    $database = "db_name";
    $server = "db_server";

    $db_handle = mysql_connect($server, $user_name, $password);

    $db_found = mysql_select_db($database, $db_handle);

    if ($db_found) {
    print "Database Found ";
    mysql_close($db_handle);
    }
    else {
    print "Database NOT Found ";
    }

    ?>
    [/code]
    Thanks much.
  • allanallan Posts: 63,277Questions: 1Answers: 10,424 Site admin
    This is more of a PHP question that one about DataTables which is a Javascript framework (I only use PHP as an example) - so I think you'll more likely get a better response from a PHP forum for a PHP question.

    Having said that, as a DB connection, that looks fine. It doesn't do anything with the connection, but I assume you would be executing the queries somewhere else.

    Allan
This discussion has been closed.