jqGrid How to use EditUrl - jqgrid

I'm using jqGrid to maintain a database in MySQL using jSON data. I'm able to display the data in the grid but when I try to add or edit a data row through the modal form I get a message saying "Url is not set". But what is the editurl suppose to contain? mysql insert statements? I'm using the grid's predefined add and edit functions.
Also, if you take a look at the trirand demo page under Manipulating then under Grid Data. They specify their url as url:'server.php?q=2' and their editurl:"someurl.php" They never say what the someurl.php contains. This is where I get lost and I can't find a resource to give me any hints as to what is suppose to be in the editurl php file.
Thanks for any advice.
UPDATE:
Code in my editurl php file: I put the POST values from the col model in variables. I only need insert and update statements in the switch statement. Take a look at my insert statement to see which one I should be using. I also have to make you aware that I'm not listing all the columns in the database but I'm listing all the columns that the user sees in the grid. The first insert statement is commented and it states the columns that the values are suppose to be inserted based on their order. The second insert statement is following the order that is in the database. Where you see ' ' are the columns that I didn't want to display to the data grid for the user to see because that information wasn't relevant.
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "**********";
$dbname = "codes";
// connect to the database
$mysql_connect($dbhost, $dbuser, $dbpass) or die("Connection Error: " . mysql_error());
mysql_select_db($dbname) or die("Error conecting to db.");
$div = $_POST['div_id'];
$l2 = $_POST['l2_id'];
$l1l2 = $_POST['l1l2_id'];
$l1l3 = $_POST['l1l3_id'];
$l2l3 = $_POST['l2l3_id'];
$beg = $_POST['exec_beg'];
$end = $_POST['exec_end'];
$csa = $_POST['csa_id'];
$area = $_POST['area_id'];
$areadesc = $_POST['area_desc'];
$shortdesc = $_POST['short_desc'];
$longdesc = $_POST['long_desc'];
$enabled = $_POST['avail_ind'];
switch($_POST['oper'])
{
case "add":
$query = "INSERT INTO divcodes values ($div,'',$l1l2,$l2,$l1l3,$l2l3,$beg,$end,'',''$csa,$area,$areadesc,$shortdesc,$longdesc,$enabled,'','','','','',''";
$run = mysql_query($query);
break;
case "edit":
//do mysql update statement here
break;
}
When I set the editurl to my php file and I try to add new row of data to the grid it gives me internal server error 500. I don't know how to debug it any further and the error 500 is such a general error.
I thought that since I was using the predefined operations of the grid (add/edit) that the grid would just know to perform an insert or update statement into my database but it looks like that's not the case?
UPDATE TAKE 2: I changed the syntax to use the mysqli extension. Once I restructured my insert statements I stopped getting the 'Internal Server Error Code 500'. When I click add new record then fill in test data then click on submit the modal window disappears like the data has been added to the grid. But no where in the grid can I find the data (maybe the grid is not reloading with the new data). I checked phpmyadmin and the new row is no where to be found. When I edit an existing row and click submit the dialog box stays open but I'm not getting the error 500 which is a relief.
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "**********";
$dbname = "codes";
// connect to the database
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Connection Error: " . mysql_error());
mysqli_select_db($conn,$dbname) or die("Error conecting to db.");
$div = $_POST['div_id'];
$l2 = $_POST['l2_id'];
$l1l2 = $_POST['l1l2_id'];
$l1l3 = $_POST['l1l3_id'];
$l2l3 = $_POST['l2l3_id'];
$beg = $_POST['exec_beg'];
$end = $_POST['exec_end'];
$csa = $_POST['csa_id'];
$area = $_POST['area_id'];
$areadesc = $_POST['area_desc'];
$shortdesc = $_POST['short_desc'];
$longdesc = $_POST['long_desc'];
$enabled = $_POST['avail_ind'];
switch($_POST['oper'])
{
case "add":
$query = "INSERT INTO divcodes (div_id,l1l2_id,l2_id,l1l3_id,l2l3_id,exec_beg,exec_end,csa_id,area_id,area_desc,short_desc,long_desc,avail_ind) values ($div,$l1l2,$l2,$l1l3,$l2l3,$beg,$end,$csa,$area,$areadesc,$shortdesc,$longdesc,$enabled)";
mysqli_query($conn,$query);
break;
case "edit":
$query = "UPDATE divcodes SET div_id=$div,l1l2_id=$l2,l2_id=$l1l2,l1l3_id=$l2l3,l2l3_id=$l2l3,exec_beg=$beg,exec_end=$end,csa_id=$csa,area_id=$area,area_desc=$areadesc,short_desc=$shortdesc,long_desc=$longdesc,avail_ind=$enabled";
mysqli_query($conn,$query);
break;
}
?>

The editurl is the PHP file that will do your INSERTS, UPDATES and DELETES.
There are several parameters passed to this file including the parameter: oper which will be either add, edit or del depending on which operation you did.
In your PHP file (the editurl file) I would just do a switch:
switch ($_POST["oper"]) {
case "add":
// do mysql insert statement here
break;
case "edit":
// do mysql update statement here
break;
case "del":
// do mysql delete statement here
break;
}
Also passed to that file will be all of your data from that row in name:value pairs, just like the oper parameter. The name will be the index property you defined in your colModel array when you setup your grid.
So if you had a column (from the colModel) that looked like:
{
name: 'name1',
index: 'name1',
width: 95,
align: "center",
hidden: false
}
In your editurl PHP file, you can access that column's value to build your queries above by using:
$_POST["name1"]
Hope this helps and let me know if you have any further questions. I struggled with this part of jQGrid just like you are so I know the pain!! lol
UPDATE
Your MySQL Insert statement is incorrect. You do not need to include every column in that exists in your table, just the ones that are required (the columns that can't be null).
For instance, I have a table (tableName) with three columns:
ID (required, not null)
Name (required, not null)
Phone (not required)
If I want to perform an insert onto this table, but I don't want to insert anything into the Phone column, my Insert statement would look like:
INSERT INTO tableName (ID, Name) VALUES (123, "Frank")
On the left side of VALUES is where you specify which columns you will be inserting into. On the right side of VALUES are the actual values we will be inserting.
Here is a simple, helpful link on MySQL syntax: http://www.w3schools.com/php/php_mysql_insert.asp
As you can see, in that first example on that link, they don't specify which columns, meaning they will be inserting data into ALL columns. In your case, that is not what you want, so I would check out their second example, which does specify the columns you are inserting into.

Related

Update a database field with Joomla UpdateObject method with a calculated field from same table

Right to the point.
I need to update a field in the database using the field to calculate the new value first.
E.g of fields: https://i.stack.imgur.com/FADH6.jpg
Now I am using the Joomla updateObject function. my goal is to take the "spent" value from the DB table without using a select statement.
Then I need to calculate a new value with it like (spent + 10.00) and update the field with the new value. Check out the code below:
// Create an object for the record we are going to update.
$object = new stdClass();
// Must be a valid primary key value.
$object->catid = $item['category'];
$object->spent = ($object->spent - $item['total']);
// Update their details in the users table using id as the primary key.
$result = JFactory::getDbo()->updateObject('#__mytable', $object, 'catid');
The bit which i need to make the calculation on is
$object->spent = ($object->spent - $item['total']);
I realise I can use a seperate insert statement but I am wondering if there is a better way. Any help is much appreciated.
It needs to work like this, WITHOUT THE SELECT (working example)
$query = $db->getQuery(true);
$query->select($db->quoteName('spent'));
$query->from($db->quoteName('#__mytable'));
$query->where($db->quoteName('catid')." = ". $item['category']);
// Reset the query using our newly populated query object.
$db->setQuery($query);
$oldspent = $db->loadResult();
// Create an object for the record we are going to update.
$object = new stdClass();
// Must be a valid primary key value.
$object->catid = $item['category'];
$object->spent = ($oldspent - $item['total']);
// Update their details in the users table using id as the primary key.
$result = JFactory::getDbo()->updateObject('#__mytable', $object, 'catid');
The sticking point with trying to use updateObject('#__mytable', $object, 'catid'); is that your query logic needs to reference the column name in the calculation to assign the "difference" as the new value. The raw mysql query syntax to update a column value with the value minus another value is like:
"`spent` = `spent` - {$item['total']}"
updateObject() will convert spent - {$item['total']} to a literal string, the database will expect a numeric value, so UPDATE results in a 0 value recorded. In other words, $db->getAffectedRows() will give you a positive count and there will be no errors generated, but you don't get the desired mathematical action.
The workaround is to discard updateObject() as a tool and build an UPDATE query without objects -- don't worry it's not too convoluted. I'll build in some diagnostics and failure checking, but you can remove whatever parts that you wish.
I have tested the following code to be successful on my localhost:
$db = JFactory::getDBO();
try {
$query = $db->getQuery(true)
->update($db->quoteName('#__mytable'))
->set($db->quoteName("price") . " = " . $db->qn("price") . " - " . (int)$item['total'])
->where($db->quoteName("catid") . " = " . (int)$item['category']);
echo $query->dump(); // see the generated query (but don't show to public)
$db->setQuery($query);
$db->execute();
if ($affrows = $db->getAffectedRows()) {
JFactory::getApplication()->enqueueMessage("Updated. Affected Rows: $affrows", 'success');
} else {
JFactory::getApplication()->enqueueMessage("Logic Error", 'error');
}
} catch (Exception $e) {
JFactory::getApplication()->enqueueMessage("Query Syntax Error: " . $e->getMessage(), 'error'); // never show getMessage() to public
}
Here is a StackOverflow page discussing the mysql subtraction logic: update a column by subtracting a value

How to remove or hide the data value not required from table in birt tool

How do I remove or hide the data value not required from table in birt tool?
I tried with the values it works in some places but now in groups which has multiple values.
I need to filter some of the values which should not be displayed in the data tab of the table.
I have a column which does not have any value that I need to filter out (But its not an empty value because when I check I got to know that it has some blank spaces). It should display only the columns with non-blank value.
How can I remove those columns from the data set.
You can of course try scripting the data source query but you can also run a script on the table when it is created to hide the empty column.
Try this script in the table's onCreate event:
var mycolumnCount = this.getRowData().getColumnCount();
var DisNull = false;
for(i=1;i<mycolumnCount;i++) {
var temp = this.getRowData().getColumnValue(i)
if(this.getRowData().getColumnValue(i) == "") {
DisNull = true;
}else{
DisNull = false;
i = mycolumnCount+1;
}
}
if(DisNull == true) {
this.getStyle().display = "none"
}

Using Rails Update to Append to a Text Column in Postgresql

Thanks in advance for any help on this one.
I have a model in rails that includes a postgresql text column.
I want to append (i.e. mycolumn = mycolumn || newdata) data to the existing column. The sql I want to generate would look like:
update MyOjbs set mycolumn = mycolumn || newdata where id = 12;
I would rather not select the data, update the attribute and then write the new data back to the database. The text column could grow relatively large and I'd rather not read that data if I don't need to.
I DO NOT want to do this:
#myinstvar = MyObj.select(:mycolumn).find(12)
newdata = #myinstvar.mycolumn.to_s + newdata
#myinstvar.update_attribute(:mycolumn, newdata)
Do I need to do a raw sql transaction to accomplish this?
I think you could solve this problem directly writing your query using the arel gem, that's already provided with rails.
Given that you have these values:
column_id = 12
newdata = "a custom string"
you can update the table this way:
# Initialize the Table and UpdateManager objects
table = MyOjbs.arel_table
update_manager = Arel::UpdateManager.new Arel::Table.engine
update_manager.table(table)
# Compose the concat() function
concat = Arel::Nodes::NamedFunction.new 'concat', [table[:mycolumn], new_data]
concat_sql = Arel::Nodes::SqlLiteral.new concat.to_sql
# Set up the update manager
update_manager.set(
[[table[:mycolumn], concat_sql]]
).where(
table[:id].eq(column_id)
)
# Execute the update
ActiveRecord::Base.connection.execute update_manager.to_sql
This will generate a SQL string like this one:
UPDATE "MyObjs" SET "mycolumn" = concat("MyObjs"."mycolumn", 'a custom string') WHERE "MyObjs"."id" = 12"

Can I refer to items within a LINQ result set by index?

I'm trying to work with a LINQ result set of 4 tables retrieved with html agility pack. I'd like to process each one slightly differently by setting a variable for each (switch statement below), and then processing the rows within the table. The variable would ideally be the index for each of the tables in the set, 0 to 3, and would be used in the switch statement and to select the rows. I haven't been able to locate the index property, but I see it used in situations such as SelectChildNode.
My question is can I refer to items within a LINQ result set by index? My "ideal scenario" is the last commented out line. Thanks in advance.
var ratingsChgs = from table in htmlDoc.DocumentNode
.SelectNodes("//table[#class='calendar-table']")
.Cast<HtmlNode>()
select table;
String rtgChgType;
for (int ratingsChgTbl = 0; ratingsChgTbl < 4; ratingsChgTbl++)
{
switch (ratingsChgTbl)
{
case 0:
rtgChgType = "Upgrades";
break;
case 1:
rtgChgType = "Downgrades";
break;
case 2:
rtgChgType = "Coverage Initiated";
break;
case 3:
rtgChgType = "Coverage Reit/ Price Tgt Changed";
break;
//This is what I'd like to do.
var tblRowsByChgType = from row in ratingsChgs[ratingsChgTbl]
.SelectNodes("tr")
select row;
//Processing of returned rows.
}
}
ElementAt does what you're asking for. I don't recommend using it in your example, though, because each time you call it, your initial LINQ query will be executed. The easy fix is to have ratingsChgs be a List or Array.
You can also refactor out the switch statement. It is overkill when you only need to iterate through a list of items. Here is a possible solution:
var ratingsChgs = from table in htmlDoc.DocumentNode
.SelectNodes("//table[#class='calendar-table']")
.Cast<HtmlNode>()
select table;
var rtgChgTypeNames = new List
{
"Upgrades",
"Downgrades",
"Coverage Initiated",
"Coverage Reit/ Price Tgt Changed"
};
var changeTypes = ratingsChgs.Zip(rtgChgTypeNames, (changeType, name) => new
{
Name = name,
Rows = changeType.SelectNodes("tr")
});
foreach( var changeType in changeTypes)
{
var name = changeType.Name;
var rows = changeType.Rows;
//Processing of returned rows.
}
Also, why not store your rating change types in the HTML doc? It seems odd to have table information defined in the business logic.

Reading/Writing DataTables to and from an OleDb Database LINQ

My current project is to take information from an OleDbDatabase and .CSV files and place it all into a larger OleDbDatabase.
I have currently read in all the information I need from both .CSV files, and the OleDbDatabase into DataTables.... Where it is getting hairy is writing all of the information back to another OleDbDatabase.
Right now my current method is to do something like this:
OleDbTransaction myTransaction = null;
try
{
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
command.Transaction = myTransaction;
strSQL = "Insert into TABLE " +
"(FirstName, LastName) values ('" +
FirstName + "', '" + LastName + "')";
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
command.ExecuteNonQuery();
conn.close();
catch (Exception)
{
// IF invalid data is entered, rolls back the database
myTransaction.Rollback();
}
Of course, this is very basic and I'm using an SQL command to commit my transactions to a connection. My problem is I could do this, but I have about 200 fields that need inserted over several tables. I'm willing to do the leg work if that's the only way to go. But I feel like there is an easier method. Is there anything in LINQ that could help me out with this?
If the column names in the DataTable match exactly to the column names in the destination table, then you might be able to use a OleDbCommandBuilder (Warning: I haven't tested this yet). One area you may run into problems is if the data types of the source data table do not match those of the destination table (e.g if the source column data types are all strings).
EDIT
I revised my original code in a number of ways. First, I switched to using the Merge method on a DataTable. This allowed me to skip using the LoadDataRow in a loop.
using ( var conn = new OleDbConnection( destinationConnString ) )
{
//query off the destination table. Could also use Select Col1, Col2..
//if you were not going to insert into all columns.
const string selectSql = "Select * From [DestinationTable]";
using ( var adapter = new OleDbDataAdapter( selectSql, conn ) )
{
using ( var builder = new OleDbCommandBuilder( adapter ) )
{
conn.Open();
var destinationTable = new DataTable();
adapter.Fill( destinationTable );
//if the column names do not match exactly, then they
//will be skipped
destinationTable.Merge( sourceDataTable, true, MissingSchemaAction.Ignore );
//ensure that all rows are marked as Added.
destinationTable.AcceptChanges();
foreach ( DataRow row in destinationTable.Rows )
row.SetAdded();
builder.QuotePrefix = "[";
builder.QuoteSuffix= "]";
//forces the builder to rebuild its insert command
builder.GetInsertCommand();
adapter.Update( destinationTable );
}
}
}
ADDITION An alternate solution would be to use a framework like FileHelpers to read the CSV file and post it into your database. It does have an OleDbStorage DataLink for posting into OleDb sources. See the SqlServerStorage InsertRecord example to see how (in the end substitute OleDbStorage for SqlServerStorage).
It sounds like you have many .mdb and .csv that you need to merge into a single .mdb. This answer is running with that assumption, and that you have SQL Server available to you. If you don't, then consider downloading SQL Express.
Use SQL Server to act as the broker between your multiple datasources and your target datastore. Script each datasource as an insert into a SQL Server holding table. When all data is loaded into the holding table, perform a final push into your target Access datastore.
Consider these steps:
In SQL Server, create a holding table for the imported CSV data.
CREATE TABLE CsvImport
(CustomerID smallint,
LastName varchar(40),
BirthDate smalldatetime)
Create a stored proc whose job will be to read a given CSV filepath, and insert into a SQL Server table.
CREATE PROC ReadFromCSV
#CsvFilePath varchar(1000)
AS
BULK
INSERT CsvImport
FROM #CsvFilePath --'c:\some.csv'
WITH
(
FIELDTERMINATOR = ',', --your own specific terminators should go here
ROWTERMINATOR = '\n'
)
GO
Create a script to call this stored proc for each .csv file you have on disk. Perhaps some Excel trickery or filesystem dir piped commands can help you create these statements.
exec ReadFromCSV 'c:\1.csv
For each .mdb datasource, create a temp linked server.
DECLARE #MdbFilePath varchar(1000);
SELECT #MdbFilePath = 'C:\MyMdb1.mdb';
EXEC master.dbo.sp_addlinkedserver #server = N'MY_ACCESS_DB_', #srvproduct=N'Access', #provider=N'Microsoft.Jet.OLEDB.4.0', #datasrc=#MdbFilePath
-- grab the relevant data
--your data's now in the table...
INSERT CsvImport(CustomerID,
SELECT [CustomerID]
,[LastName]
,[BirthDate]
FROM [MY_ACCESS_DB_]...[Customers]
--remove the linked server
EXEC master.dbo.sp_dropserver #server=N'MY_ACCESS_DB_', #droplogins='droplogins'
When you're done importing data into that holding table, create a Linked Server in your SQL Server instance. This is the target datastore. SELECT the data from SQL Server into Access.
EXEC master.dbo.sp_addlinkedserver #server = N'MY_ACCESS_TARGET', #srvproduct=N'Access', #provider=N'Microsoft.Jet.OLEDB.4.0', #datasrc='C:\Target.mdb'
INSERT INTO [MY_ACCESS_TARGET]...[Customer]
([CustomerID]
,[LastName]
,[BirthDate])
SELECT Customer,
LastName,
BirthDate
FROM CsvImport

Resources