3.2.0

Simple PHP/MySQL example

I am not expert in PHP so please correct me if there is something stupid in this code -

<?php
    $connection = @mysql_connect('localhost', 'user', 'password');
    $query = 'SELECT * FROM myTable LIMIT 0,10';
    $dataset = @mysql_query($query, $connection);

function aw_cells($dataset){

    $recordSeparator = "";
    echo "[\n";

    while ($record = @mysql_fetch_array($dataset)) {

        echo $recordSeparator;
        $cellSeparator = "";
        echo "\t[";
        foreach ($record as $value){
            echo $cellSeparator."\"".$value."\"";
            $cellSeparator = ",";
        }
        echo "]";
        $recordSeparator = ",\n";
    }

    echo "\n];\n";
}

function aw_headers($dataset){

    $cellSeparator = "";
    echo "[\n";

    while ($field = @mysql_fetch_field($dataset)) {

        echo $cellSeparator."\"".$field->name."\"";
        $cellSeparator = ",";
    }

    echo "\n];\n";
}

?>
<html>
<head>
    <link href="../../runtime/styles/xp/aw.css" rel="stylesheet" type="text/css" ></link>
    <script src="../../runtime/lib/aw.js"></script>
</head>
<body>
    <script>

    var myColumns = <?= aw_headers($dataset) ?>
    var myData = <?= aw_cells($dataset) ?>

    var obj = new AW.UI.Grid;

    obj.setCellText(myData);
    obj.setHeaderText(myColumns);

    obj.setRowCount(myData.length);
    obj.setColumnCount(myColumns.length);

    document.write(obj);

    </script>
</body>
</html>
Alex (ActiveWidgets)
February 28,
The code is just fine Alex, but I condensed it to show a little better for some maybe? Some maybe not. None the less, here it is.

<?php
    $connection = @mysql_connect('localhost', 'user', 'password');
    @mysql_select_db('DBName',$connection);
    $query = 'SELECT * FROM myTable LIMIT 0,10';
    $dataset = @mysql_query($query, $connection);

function aw_cells($dataset){
    $rows = array();
    while ($record = @mysql_fetch_array($dataset)) {
        $cols = array();
        foreach ($record as $value)
            $cols[] = '"'.addslashes($value).'"';
        $rows[] = "\t[".implode(",",$cols)."],\n";
    }
    echo "[\n".implode(",\n",$rows)."\n];\n";
}

function aw_headers($dataset){
    while ($field = @mysql_fetch_field($dataset))
        $cols[] = '"'.$field->name.'"';
    echo "[".implode(",",$cols)."];\n";
}

?>
Tony
February 28,
I found that this script duplicates values in myData.

To solve that:

instead of
while ($record = @mysql_fetch_array($dataset)) {

i used this
while ($record = @mysql_fetch_row($dataset)) {

and it works now
joakinen
March 1,
Tony and joakinen, thank you for the corrections - I knew it could be improved :-) !
Here is the complete sample again -

<?php

$connection = @mysql_connect('localhost', 'user', 'password');
@mysql_select_db('database', $connection);
$query = 'SELECT * FROM myTable LIMIT 0,10';
$dataset = @mysql_query($query, $connection);


// print MySQL query results as 2D javascript array
function aw_cells($dataset){

    $rows = array();
    while ($record = @mysql_fetch_row($dataset)) {
        $cols = array();
        foreach ($record as $value) {
            $cols[] = '"'.addslashes($value).'"';
        }
        $rows[] = "\t[".implode(",", $cols)."]";
    }
    echo "[\n".implode(",\n",$rows)."\n];\n";
}

// print MySQL field names as javascript array
function aw_headers($dataset){
    while ($field = @mysql_fetch_field($dataset)) {
        $cols[] = '"'.$field->name.'"';
    }
    echo "[".implode(",",$cols)."];\n";
}

?>
<html>
<head>
    <!-- include AW stylesheet and script -->
    <link href="../../runtime/styles/xp/aw.css" rel="stylesheet" type="text/css" ></link>
    <script src="../../runtime/lib/aw.js"></script>
</head>
<body>
<script>

//	insert javascript arrays produced by PHP functions
    var myHeaders = <?= aw_headers($dataset) ?>
    var myCells = <?= aw_cells($dataset) ?>

//	create grid control
    var obj = new AW.UI.Grid;

//	set grid text
    obj.setHeaderText(myHeaders);
    obj.setCellText(myCells);

//	set number of columns/rows
    obj.setColumnCount(myHeaders.length);
    obj.setRowCount(myCells.length);

//	write grid to the page
    document.write(obj);

</script>
</body>
</html>
Alex (ActiveWidgets)
March 1,
Oh, yeah, I didn't test the code. I only shrunk it. Actually you could also use mysql_fetch_assoc and acheive the same results. The problem with mysql_fetch_array is that you get the indexes as numbers and associate array indexes so you get the same number of rows. Just twice as many columns.
Tony
March 2,
I find it much easier to just consider my data and my widget separate.
use XML to present your fetch up and load it into the widget using the AW Table object.
Of course I have working with XUL for the past year and that may play into my view of how to go about doing this.
CKD
March 23,
when I test the code in server, I don´t see anything, the page is in blank why??? T_T...somebody can help me..please.

PD:sorry for my english I speak español

gracias
SEBA
May 9,

Try looking at the HTML source of the "blank" page or the Javascript Console (if you use Firefox) to start looking for the error.

Mira el codigo fuente HTML de la página que parece estar en blanco, o la consola de Javascript para ver si hay algún error.
joakinen
May 9,
Probé el código y funciona, verifica que la conexión a la base de datos sea la correcta, host, user y password y tambien tu sentencia SQL, el asunto de la consola es buena idea y en el código HTML en teoria deberías tener la variable myCells (a parte de otra bola de cosas) con los datos que has obtenido de tu consulta, en mi prueba se ve así:
...
var myCells = [
["1","1","1","02/05/2005","01:44","-89 39 37","19 55 8","Area agricola de temporal","Campeche","Hopelchen","NO AFECTA","0","0","TERRA"],
["2","2","","02/05/2005","01:44","-90 3 49","19 42 20","Pastizal cultivado","Campeche","Campeche","NO AFECTA","0","0","TERRA"],
["3","2","2","02/05/2005","01:44","-90 3 18","19 41 45","Area agricola de temporal","Campeche","Hopelchen","NO AFECTA","0","0","TERRA"],

...

Si no ves está variable con tus datos dentro del código HTML, entonces tienes problemas con las variables arribas mencionadas

Raul
May 9,
I am using the free trial version and i cannot see the resulting grid in my server, but it works good in my pc (localhost).
I supose this is the license protection.
Anyone knows something about this issue?

Estoy usando la versión de prueba y no puedo ver el grid resultante en mi servidor, perop funciona bien en mi pc (localhost).
Supongo que esta es la protección de licencia.
¿Alguien sabe algo acerca de este tema?

Guillermo Arias, Lima
Guillermo Arias
October 20,
But... How do you save the data back to database?

Practical example needed - not full of geek talk
mike
February 20,
SELECT * FROM myTable LIMIT ...
next|back HOW?
Valeri
February 20,
how can i use multiple query and show it in the same table?
i am using cold fusion query and mssql database.

BELOW IS MY CODE WHICH RUNS CORRECTLY, BUT ONLY USE 1 QUERY.
my code:
var myData = [<cfoutput query="qSearch">["#qSearch.CurrentRow#","<A href='myform.cfm?RefNo=#ID#' target='_blank'>#ID#</a>","#TITLE#","#TYPE#","#COMMENT#","#DATE#","#ACTIONSTATUS#"],</CFOUTPUT>];

var columnTitles = new array();
columnTitles.add("ID", "MY<br>TITLE", "TYPE", "COMMENT", "DATE", "STATUS");

i am confused. anybody knows how? thanks.
ellisegirl
March 28,
sugestion for function aw_cells by alex:
i think it's better to add trim() to the value to free from whitespace.
because i found error if i don't do that.
i Add this trimlike this:
foreach ($record as $value){
$value=trim($value);
echo $cellSeparator."\"".$value."\"";
$cellSeparator = ",";
}

function from alex:
function aw_cells($dataset){

$recordSeparator = "";
echo "[\n";

while ($record = @mysql_fetch_array($dataset)) {

echo $recordSeparator;
$cellSeparator = "";
echo "\t[";
foreach ($record as $value){
echo $cellSeparator."\"".$value."\"";
$cellSeparator = ",";
}
echo "]";
$recordSeparator = ",\n";
}

echo "\n];\n";
}
winotosw
April 15,
Hi ,
I’m a total newbie and yet have found it pretty easy to setup.
I’m using PHP/MYSQL and found the simple example that was easy to cut and paste.
I want the grid to be “live”, so I looked a little further and added the following code.
obj.setCellEditable(true);
    
      obj.onCellValidated = function(text, column, row){ 

        var r = new AW.HTTP.Request; 
        r.setURL("updateSingleCell.php"); 
        r.setRequestMethod("POST"); 
        r.setParameter("column", column); 
        r.setParameter("row", row); 
        r.setParameter("text", text); 
        r.request(); 

        r.response = function(data){ 
            alert(data); // process response data 
        } 
    }


I lucked out and it worked with one exception. The data is not updating the database.
I believe that I need to setup the updateSingleCell.php file to handle the updating and found the following code example for this file.
<?php 
//updateSingleCell.php  

   $column = $HTTP_POST_VARS['column']; 
   $row = $HTTP_POST_VARS['row']; 
   $text = $HTTP_POST_VARS['text']; 

  // processing code here 

   echo "done"; 
?>


I’m thinking that this is missing a few things and the average guy would have no problems finishing this from this point but like I said I’m a newbie.

1. Connection Settings to mysql I think I got this one with something like this
$connection = mysql_connect($host,$user,$password)
               or die ("Couldn't connect to server.");   
  $db = mysql_select_db($database, $connection)
               or die ("Couldn't select database.");



2. Processing Code
Some form of UPDATE ? not sure this is where I need help.

Seven
June 10,
you still need help? (That code doesn't work for me, but I have some other code that does)
comptech
June 26,
Comptech... can you please post your code? I'm trying to do something similar and could use the example.

Thank you.
AJAX Newbie
July 3,
This is my code:

<html>
<head>
    <title>ActiveWidgets Examples</title>
    <style>body {font: 12px Tahoma}</style>

<!-- include links to the script and stylesheet files -->
    <script src="runtime/lib/aw.js"></script>
    <link href="runtime/styles/xp/aw.css" rel="stylesheet"></link>

<!-- change default styles, set control size and position -->
<style>

    #myGrid {width: 525px; height: 125px;}
    #myGrid .aw-alternate-even {background: #eee;}

</style>
</head>
<body>
<?php 
  mysql_connect("localhost" , "root" , "") or die ( "Cannot connect to the database host, or the user/password is wrong. Check load.php" );

  mysql_select_db("easy5") or die ("Check database. Current database (".$db.") does not exist.");

?>
<span id="myGrid"></span>

<script>
var obj = new AW.UI.Grid;
    var grid = new AW.UI.Grid;
    grid.setId("myGrid");
  grid.setHeaderText(["Status", "Gebruikersnaam"]);
  
<?php
    $kQuery = mysql_query("SELECT * FROM leden");
    $totaal = mysql_num_rows($kQuery);
?>
  var myCells = [
<?php 
    while ($obj = mysql_fetch_object($kQuery))
            {
?>
     ["<?php echo $obj->status; ?>","<?php echo $obj->gebruikersnaam; ?>"],
<?php 
      }
?>
  ];

  grid.setCellText(myCells);     
  grid.setColumnCount("2");
  grid.setRowCount(<?php echo $totaal; ?>);
  grid.refresh();
</script>
</body>
</html>
Youri
July 17,
Hi everyone,

I am using the data grid in edit mode. I would like to know how to update the data that has been edited into my mysql database using ajax. Please help.

Regards,

Jay
Jay
August 5,
Hey every 1!

After reading and searching through the docs and forums and looking at the examples, it appears to me that the 2.0 Grid isn't natively setup to handle server side paging. Is this right?

Virtual rendering still loads all the data from the server and allows it to be scrolled through on the client side. Is this correct?

In order to make it scroll through a large database, you have to make your own Javascript (kind of like this: http://www.activewidgets.com/javascript.forum.13524.9/when-will-ajax-paging-be.html - which doesn't work for sorting btw)

Is that correct? Or is there a easier way in 2.0.2?

I was hoping for some server-side interaction like OpenRico's Livegrid.

I am happy to write this, but I want to know if it is already done - no sense writing something that already exists if it does.

Could someone (Alex?) tell me about this?

Thanks,

Jim
Jim Nickel
October 29,
Jim,

This is the simple paging Alex's suggestion:
/javascript.forum.12092.28/paging-with-version-2-0.html

And this is my workaround to make it "sortable".
/javascript.forum.15805.5/blank-page-during-paging.html

Anyway it would be great to have more paging methods/options we can count on, so..., really appreciate all contibutions.
T & B.R.
Carlos

Carlos
October 30,
Thanks so much Carlos! Very helpful!

Alex - are you going to include server side paging abilities in Version 2.5?

Jim
Jim Nickel
October 30,
No, AW 2.5 is still client-side javascript code. Maybe AW 3.0 :-)
Alex (ActiveWidgets)
October 30,

This topic is archived.

See also:


Back to support forum