webismymind / editablegrid-mysql-example

This example shows how to use EditableGrid with a MySQL database
MIT License
58 stars 38 forks source link

One mysql table doesn't update but the others do it #31

Closed pipemg closed 8 years ago

pipemg commented 8 years ago

I have a DB which Im editing with this but one of the tables doesnt work and I really don't know why, the one that works is biologicos and fotografias doesn't

pipemg commented 8 years ago

This is the one that works (loaddata.php)

<?php session_start();    
/*
 * examples/mysql/loaddata.php
 * 
 * This file is part of EditableGrid.
 * http://editablegrid.net
 *
 * Copyright (c) 2011 Webismymind SPRL
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://editablegrid.net/license
 */

/**
 * This script loads data from the database and returns it to the js
 *
 */

require_once('config.php');      
require_once('EditableGrid.php');            

/**
 * fetch_pairs is a simple method that transforms a mysqli_result object in an array.
 * It will be used to generate possible values for some columns.
*/
function fetch_pairs($mysqli,$query){
    if (!($res = $mysqli->query($query)))return FALSE;
    $rows = array();
    while ($row = $res->fetch_assoc()) {
        $first = true;
        $key = $value = null;
        foreach ($row as $val) {
            if ($first) { $key = $val; $first = false; }
            else { $value = $val; break; } 
        }
        $rows[$key] = $value;
    }
    return $rows;
}

// Database connection
$mysqli = mysqli_init();
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
$mysqli->real_connect($config['db_host'],$config['db_user'],$config['db_password'],$config['db_name']); 

// create a new EditableGrid object
$grid = new EditableGrid();

/* 
*  Add columns. The first argument of addColumn is the name of the field in the databse. 
*  The second argument is the label that will be displayed in the header
*/
$grid->addColumn('id_muestra', 'Clave', 'string', fetch_pairs($mysqli,'SELECT id,clave FROM muestras WHERE muestras.id_salida='.$_SESSION['idsalida']  ),true); 
$grid->addColumn('especie', 'Especie', 'string');
$grid->addColumn('colector', 'Colector', 'string');
$grid->addColumn('perforaciones', 'Perforaciones', 'boolean');
$grid->addColumn('vermes', 'Vermes', 'boolean');
$grid->addColumn('ectoparasitos', 'Ectoparásitos', 'boolean');
$grid->addColumn('hongos_bacterias', 'Hongos o Bacterias', 'boolean');
$grid->addColumn('deformidades', 'Deformidades', 'boolean');
$grid->addColumn('lesiones', 'Lesiones', 'boolean');
$grid->addColumn('olores', 'Olores', 'boolean');
$grid->addColumn('observaciones', 'Observaciones', 'string');  
$grid->addColumn('verificado', 'Verificado', 'boolean');  
$grid->addColumn('borrar', 'Borrar', 'boolean');  

$result = $mysqli->query('SELECT * FROM biologicos WHERE biologicos.id_muestra IN (SELECT id FROM muestras WHERE muestras.id_salida='.$_SESSION['idsalida'].' ) or biologicos.id_muestra<0 '); // LIMIT 100'
$mysqli->close(); 

// send data to the browser
$grid->renderXML($result);

This is the one that not

<?php session_start();    

/*
 * examples/mysql/loaddata.php
 * 
 * This file is part of EditableGrid.
 * http://editablegrid.net
 *
 * Copyright (c) 2011 Webismymind SPRL
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://editablegrid.net/license
 */

/**
 * This script loads data from the database and returns it to the js
 *
 */

require_once('config.php');      
require_once('EditableGrid.php');      

// create a new EditableGrid object
$grid = new EditableGrid();      

/**
 * fetch_pairs is a simple method that transforms a mysqli_result object in an array.
 * It will be used to generate possible values for some columns.
*/
function fetch_pairs($mysqli,$query){
    if (!($res = $mysqli->query($query)))return FALSE;
    $rows = array();
    while ($row = $res->fetch_assoc()) {
        $first = true;
        $key = $value = null;
        foreach ($row as $val) {
            if ($first) { $key = $val; $first = false; }
            else { $value = $val; break; } 
        }
        $rows[$key] = $value;
    }
    return $rows;
}

// Database connection
$mysqli = mysqli_init();
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
$mysqli->real_connect($config['db_host'],$config['db_user'],$config['db_password'],$config['db_name']); 

#$grid->addColumn('id_muestra', 'Clave', 'string', fetch_pairs($mysqli,'SELECT id,clave FROM muestras WHERE muestras.id_salida='.$_SESSION['idsalida']  ),true); 
$grid->addColumn('identificador', 'ID', 'integer', NULL, true); 
$grid->addColumn('id_muestra', 'muestra', 'integer', NULL, true); 
$grid->addColumn('id_submuestra', 'submuestra', 'integer', NULL, true); 
$grid->addColumn('id_laminilla', 'laminilla', 'integer', NULL, true); 
$grid->addColumn('nombre', 'Nombre', 'string', NULL, true); 
$grid->addColumn('localizacion', 'localizacion', 'string', NULL, true); 
$grid->addColumn('observaciones', 'Observaciones', 'string', NULL, true);  
$grid->addColumn('verificado', 'Verificado', 'boolean', NULL, true);  
$grid->addColumn('borrar', 'Borrar', 'boolean', NULL, true); 

$result = $mysqli->query('SELECT * FROM fotografias where 1'); // LIMIT 100'

$mysqli->close(); 

// send data to the browser
$grid->renderXML($result);
pipemg commented 8 years ago

This are the js files, the one that works

/**
 *  highlightRow and highlight are used to show a visual feedback. If the row has been successfully modified, it will be highlighted in green. Otherwise, in red
 */
function highlightRow(rowId, bgColor, after)
{
    var rowSelector = $("#" + rowId);
    rowSelector.css("background-color", bgColor);
    rowSelector.fadeTo("normal", 0.5, function() { 
        rowSelector.fadeTo("fast", 1, function() { 
            rowSelector.css("background-color", '');
        });
    });
}

function highlight(div_id, style) {
    highlightRow(div_id, style == "error" ? "#e5afaf" : style == "warning" ? "#ffcc00" : "#8dc70a");
}

/**
   updateCellValue calls the PHP script that will update the database. 
 */
function updateCellValue(editableGrid, rowIndex, columnIndex, oldValue, newValue, row, onResponse)
{      
    $.ajax({
        url: 'update.php',
        type: 'POST',
        dataType: "html",
        data: {
            tablename : editableGrid.name,
            id: editableGrid.getRowId(rowIndex), 
            newvalue: editableGrid.getColumnType(columnIndex) == "boolean" ? (newValue ? 1 : 0) : newValue, 
            colname: editableGrid.getColumnName(columnIndex),
            coltype: editableGrid.getColumnType(columnIndex)            
        },
        success: function (response) 
        { 
            // reset old value if failed then highlight row
            var success = onResponse ? onResponse(response) : (response == "ok" || !isNaN(parseInt(response))); // by default, a sucessfull reponse can be "ok" or a database id 
            if (!success) editableGrid.setValueAt(rowIndex, columnIndex, oldValue);
            highlight(row.id, success ? "ok" : "error"); 
        },
        error: function(XMLHttpRequest, textStatus, exception) { alert("Ajax failure\n" + errortext); },
        async: true
    });

}

function DatabaseGrid() 
{ 
    this.editableGrid = new EditableGrid("biologicos", {
        enableSort: true,
        tableLoaded: function() { datagrid2.initializeGrid(this); },
        modelChanged: function(rowIndex, columnIndex, oldValue, newValue, row) {
            updateCellValue(this, rowIndex, columnIndex, oldValue, newValue, row);
        }
    });
    this.fetchGrid(); 

}

DatabaseGrid.prototype.fetchGrid = function()  {
    // call a PHP script to get the data
    this.editableGrid.loadXML("loaddata_biologicos.php");
};

DatabaseGrid.prototype.initializeGrid = function(grid) {
    grid.renderGrid("tablecontent", "testgrid");
};    

This is the one that doesnt work

/**
 *  highlightRow and highlight are used to show a visual feedback. If the row has been successfully modified, it will be highlighted in green. Otherwise, in red
 */
function highlightRow(rowId, bgColor, after)
{
    var rowSelector = $("#" + rowId);
    rowSelector.css("background-color", bgColor);
    rowSelector.fadeTo("normal", 0.5, function() { 
        rowSelector.fadeTo("fast", 1, function() { 
            rowSelector.css("background-color", '');
        });
    });
}

function highlight(div_id, style) {
    highlightRow(div_id, style == "error" ? "#e5afaf" : style == "warning" ? "#ffcc00" : "#8dc70a");
}

/**
   updateCellValue calls the PHP script that will update the database. 
 */
function updateCellValue(editableGrid, rowIndex, columnIndex, oldValue, newValue, row, onResponse)
{      
    $.ajax({
        url: 'update.php',
        type: 'POST',
        dataType: "html",
        data: {
            tablename : editableGrid.name,
            id: editableGrid.getRowId(rowIndex), 
            newvalue: editableGrid.getColumnType(columnIndex) == "boolean" ? (newValue ? 1 : 0) : newValue, 
            colname: editableGrid.getColumnName(columnIndex),
            coltype: editableGrid.getColumnType(columnIndex)            
        },
        success: function (response) 
        { 
            // reset old value if failed then highlight row
            var success = onResponse ? onResponse(response) : (response == "ok" || !isNaN(parseInt(response))); // by default, a sucessfull reponse can be "ok" or a database id 
            if (!success) editableGrid.setValueAt(rowIndex, columnIndex, oldValue);
            highlight(row.id, success ? "ok" : "error"); 
        },
        error: function(XMLHttpRequest, textStatus, exception) { alert("Ajax failure\n" + errortext); },
        async: true
    });

}

function DatabaseGrid() 
{ 
    this.editableGrid = new EditableGrid("fotografias", {
        enableSort: true,
        tableLoaded: function() { datagrid2.initializeGrid(this); },
        modelChanged: function(rowIndex, columnIndex, oldValue, newValue, row) {
            updateCellValue(this, rowIndex, columnIndex, oldValue, newValue, row);  }
    });
    this.fetchGrid(); 

}

DatabaseGrid.prototype.fetchGrid = function()  {
    // call a PHP script to get the data
    this.editableGrid.loadXML("loaddata_fotografias.php");
};

DatabaseGrid.prototype.initializeGrid = function(grid) {
    grid.renderGrid("tablecontent", "testgrid");
};    
pipemg commented 8 years ago

I tried the demo exactly as it is and still dont work

I change only the config.php file in order to add the db info and the table doesnt appear

coolguys5253 commented 8 years ago

Please check this url /loaddata.php

Please share, what data it has??