Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 16 total  RSS 

PHP Dynamic Checkbox Table Creator (data retrieved from MySQL DB)

Hi All.
This is a function for Dynamically Create a Checbox Table retrieving information for from a MySQL Database.
As it is quite commented, it's also good for learning how this things work :)
Hope you find it useful.
Feedback is welcome.
Cheers
Dan

function dynamic_checkbox_table ($sql_str, $col_label, $col_name, $val_checked="S", $cant_cols_tbl=3){
/*
	by Daniel Neumann
	this script creates dynamically permite a table containing checkboxes 
	getting the data for the checkboxes from a MySQL DB
	$sql_str, SQL select string to retrieve data from DB (see example in last comment line)
	$col_label, DB column that has values for the checkbox label 
	$col_name, DB column that has values for the checkbox name
	$val_checked="S", value when checked (value="" attribute) it uses the same value for all of them. If you whish to use a dynamic value from a DB, you should comment the line (it´s explained next to the code in the middle of the function) and de-comment the other line (check the code,. you'll understand what I mean). Also, you should use this parameter to specify the column name for the values
	$cant_cols_tbl=3, quantity of columns for the table, it defaults to 3
	usage example: dynamic_checkbox_table("SELECT * FROM keywords", "Keyword", "ID_Keywrd");
*/
	
	//connect DB and run query
	$db="MyDB";
	$db_user="MyUser";
	$pass="MyPass";
	$host="localhost";
	@mysql_connect($host,$db_user,$pass);
	@mysql_select_db($db) or die ("cannot connect to DB");
	$q_resultado = mysql_query($sql_str);
	mysql_close();
	if (mysql_num_rows($q_resultado)==0) exit("no rows returned");
	
	$next_row = mysql_fetch_array($q_resultado); //fetch first row
	
	$output = "<table  border=\"1\">\n"; //open table tag
	do {
		$output .= "<tr>\n"; //open row tag
		for ($i=1 ; $i <= $cant_cols_tbl ; $i++ ){ //loops as many times as $cant_cols_tbl
			$row=$next_row; //assign $row, next row will be checking next one, that avoids starting a new row when it's gonna be empty
			$output .= "<td>"; //open TD tag
			$output .= (!$row) ? "" : '<input type="checkbox" name="'.$row[$col_name].'" value="'.$val_checked.'" />'.$row[$col_label]; //create checkbox and data from $row (**** you should comment this line if you whish to use dynamic $val_checked****)
//			echo (!$row) ? "" : '<input type="checkbox" name="'.$row[$col_name].'" value="'.$row[$val_checked].'" />'.$row[$col_label]; //create checkbox and data from $row (**** you should de-comment this line if you whish to use dynamic $val_checked****)
			$next_row = mysql_fetch_array($q_resultado); //retrieve next row
			$output .= "</td>\n"; //close TD
		} //close for loop
		$output .= "</tr>\n"; //close row
	} while ($next_row); //close do-while (and checks if there's another row)
	$output .= "</table>\n"; //close table
	return $output; 
}

SQL -> Check Column exists in table, if not, add

// Check to see if column exists and then create if not

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ‘TEST’ AND COLUMN_NAME = ‘TEST_DATE’)
BEGIN
   ALTER TABLE TEST ADD TEST_DATE DATETIME
END

How to draw your own table header... (with borders)

// It's a bit hacky at the beginning, but nstableheadercell wasn't exactly making things easy for me

- (void)_drawThemeContents:(NSRect)cellFrame highlighted:(BOOL)highlighted inView:(NSTableHeaderView *)view;
{
	int index = [view columnAtPoint:NSMakePoint(cellFrame.origin.x + 1,cellFrame.origin.y + 1)];
	NSRect headerRect;
	if(index != -1)
		headerRect = [view headerRectOfColumn:index];
	else
		headerRect = NSZeroRect;
	
	[headerImage drawInRect:cellFrame
				   fromRect:NSZeroRect
				  operation:NSCompositeSourceOver
				   fraction:1.0];
	
	[[NSColor colorWithCalibratedRed:207.0/255.0
							   green:207.0/255.0
								blue:207.0/255.0
							   alpha:1.0] set];
	NSRectFill(NSMakeRect(headerRect.origin.x, headerRect.origin.y + 1, headerRect.size.width, headerRect.size.height - 2));
	[headerImage drawInRect:NSMakeRect(headerRect.origin.x, headerRect.origin.y, headerRect.size.width - 1, headerRect.size.height)
				   fromRect:NSZeroRect
				  operation:NSCompositeSourceOver
				   fraction:1.0];
}

Helper for quicly creating standard tables

I often want to display an array of objects as a table on a page, and I end up doing the the same things over and over again. I wrote this helper method to speed things up:

def table(collection, headers, options = {}, &proc)
  options.reverse_merge!({
    :placeholder  => 'Nothing to display',
    :caption      => nil,
    :summary      => nil,
    :footer       => ''
  })
  placeholder_unless collection.any?, options[:placeholder] do
    summary = options[:summary] || "A list of #{collection.first.class.to_s.pluralize}"
    output = "<table summary=\"#{summary}\">\n"
    output << content_tag('caption', options[:caption]) if options[:caption]
    output << "\t<caption>#{options[:caption]}</caption>\n" if options[:caption]
    output << content_tag('thead', content_tag('tr', headers.collect { |h| "\n\t" + content_tag('th', h) }))
    output << "<tfoot><tr>" + content_tag('th', options[:footer], :colspan => headers.size) + "</tr></tfoot>\n" if options[:footer]
    output << "<tbody>\n"
    concat(output, proc.binding)
    collection.each do |row|
      proc.call(row, cycle('odd', 'even'))
    end
    concat("</tbody>\n</table>\n", proc.binding)
  end
end


Writing...

<% table(@posts, %w{ID title}) do |post, klass| -%>
    <tr class="<%= klass %>">
      <td><%= post.id</td>
      <td><%= post.title </td>
    </tr>
<% end -%>


results in...

<table summary="A list of posts">
  <thead>
    <tr>
      <th>ID</th>
      <th>Title</th>
    </tr>
  </thead>
  <tfoot><tr><td colspan="2"></td></tr></tfoot>
  <tbody>
    <tr>
      <td>1</td>
      <td>My first post</td>
    </tr>
  </tbody>
</table>


Or, when the collection is an empty array (collection.any? returns false), a placeholder message is displayed:

<p class="placeholder">Nothing to display</p>


So you pass in your collection and an array of strings as your table headers as the first two arguments, and the third is a hash of options you can use to set the contents of the table's summary-attribute, the caption and footer-elements and the placeholder.

The summary attribute defaults to "A list of [objects]", where 'objects' is derived from the class name of the collection.

The function finally takes a block for every element in the collection, yeilding it the element and either 'odd' or 'even' so you can use CSS-classes to apply a zebra stripes effect.

Model from Table Name

Get the Rails model based on the table name. Assumes standard table name conventions.

def model_for_table(table_name)
  table_name.classify.constantize
end

Check whether table exists

Checks whether mysql table exists.

SHOW TABLES LIKE 'table_name'

ZebraStripes

/*
 * This script requires:
 *   1. Prototype version 1.5 or greater
 *     - Homepage: http://prototype.conio.net/
 *     - Download: http://script.aculo.us/downloads
 *   2. DomReady addon for Prototype
 *     - Homepage: http://www.vivabit.com/bollocks/2006/06/21/a-dom-ready-extension-for-prototype
 *     - Download: http://www.vivabit.com/code/domready/domready.js
 */

/*
 * I needed something capable of not just unobtrusively running when a page
 * was loaded but also easily being called at my whim as a part of an Ajax
 * transaction.
 */
var ZebraStripes = {
    /*
     * Call this function when you want something striped.  It will figure out
     * how to stripe the element.
     */
    stripe: function(el) {
        el = $(el);
        switch (el.tagName) {
            case "TABLE":
                this._stripeTable(el);
                break;
            case "OL":
            case "UL":
                this._stripeNormalList(el);
                break;
            case "DL":
                this._stripeDefinitionList(el);
                break;
        }
    },
    /***************************************************************************
     * Everything below here is psuedo-private
     **************************************************************************/
    /*
     * This class name will be applied to the odd numbered elements
     */
    _altClassName: "alt",
    /*
     * This property persists the data that tells the object whether
     * to stripe (_isEven == false) or unstripe (_isEven == true) an element
     */
    _isEven: true,
    /*
     * Cycles the _isEven property of this object between true and false
     */
    _cycle: function() {
        this._isEven = ! this._isEven;
    },
    /*
     * As a part of the Ajax-friendliness, it is important that we remove the
     * alt class from elements as well as add it.
     */
    _stripeElement: function(el) {
        el = $(el);
        if (this._isEven) {
            el.removeClassName(this._altClassName);
        } else {
            el.addClassName(this._altClassName);
        }
    },
    /*
     * This works to stripe the child nodes of TABLE, TBODY, OL and UL elements.
     */
    _stripeElements: function(els) {
        els = $(els);
        if (els.length == 0) {
            return
        }
        var parent = els[0].parentNode;
        this._isEven = true;
        for (var i = 0; i < els.length; i++ ) {
            if ((parent == els[i].parentNode) && (els[i].visible)) {
                this._stripeElement(els[i]);
                this._cycle();
            }
        }
    },
    /*
     * TBODY is not necessary, but I recommend it.  I debated about striping
     * THEAD and TFOOT, but chose not to.  Might be added later.
     */
    _stripeTable: function(table) {
        table = $(table);
        if (table.getElementsByTagName("tbody")) {
            var tableBodies = table.getElementsByTagName("tbody");
            for (var i = 0; i < tableBodies.length; i++) {
                this._stripeElements(tableBodies[i].getElementsByTagName("tr"));
            }
        } else {
            this._stripeElements(table.getElementsByTagName("tr"));
        }
    },
    /*
     * This stripes OL and UL since they both have LI and only LI child nodes.
     */
    _stripeNormalList: function(list) {
        list = $(list);
        this._stripeElements(list.getElementsByTagName("li"));
    },
    /*
     * I have seen other function out there that can stripe DL, but they all
     * assumed that each DT would have only one DD following it.  That is not
     * always the case, and not the case in the project that spawned this
     * javascript.
     */
    _stripeDefinitionList: function(list) {
        list = $(list);
        Element.cleanWhitespace(list);
        var children = list.childNodes;
        var previousDt;
        for (var i = 0; i < children.length; i++) {
            switch (children[i].tagName) {
                case "DT":
                    if (children[i].visible) {
                        this._stripeElement(children[i]);
                        this._cycle();
                    }
                    previousDt = children[i];
                    break;
                case "DD":
                    if (previousDt.visible) {
                        this._stripeElement(children[i]);
                    }
                    break;
            }
        }
    }
};

/*
 * This function will go ahead and stripe all the elligible elements on the
 * page when the page first loads.
 */
function initZebraStripes() {
    var toStripe = $$("dl.striped")
        .concat($$("ol.striped"))
        .concat($$("table.striped"))
        .concat($$("ul.striped"));

    toStripe.each(
        function(el) {
            ZebraStripes.stripe(el);
        }
    );
}

Event.onDOMReady(initZebraStripes);
// Or you could substitute a different loader:
//Event.observe(window, 'load', initZebraStripes)

pretty tables for rails models

From http://www.rubyinside.com/columnized-text-datasets-in-rails-71.html:
Inspired by: http://blog.caboo.se/articles/2006/06/10/pretty-tables-for-ruby-objects

It gives a MySQL-command-line-client style textual view of data stored in your Rails database. The syntax worked like this:
Something.find(:all, :conditions => ‘whatever‘).pretty_print


class Array

  protected

    def columnized_row(fields, sized)
      r = []
      fields.each_with_index do |f, i|
        r << sprintf(�%0-#{sized[i]}s“, f.to_s.gsub(/\n|\r/, ‘’).slice(0, sized[i]))
      end
      r.join(’ | ‘)
    end

  public

  def columnized(options = {})
    sized = {}
    self.each do |row|
      row.attributes.values.each_with_index do |value, i|
        sized[i] = [sized[i].to_i, row.attributes.keys[i].length, value.to_s.length].max
        sized[i] = [options[:max_width], sized[i].to_i].min if options[:max_width]
      end
    end

    table = []
    table << header = columnized_row(self.first.attributes.keys, sized)
    table << header.gsub(/./, ‘-‘)
    self.each { |row| table << columnized_row(row.attributes.values, sized) }
    table.join(�\n“)
  end
end

class ActiveRecord::Base
  def columnized(options = {})
    [*self].columnized(options)
  end
end



To use:
>> puts Post.find(:all).columnized(:max_width => 10)
updated_at | title      | private | url | thumb      | metadata | movie      | id  | views | content    | user_id | created_at
——————————————————————————————————————————
Wed May 31 | tetwer     | 0       |     |            |          |            | 909 | 0     | video:xyzz | 1       | Wed May 31
Wed May 31 | bbbb       | 0       |     |            |          |            | 1   | 15    | // descrip | 1       | Tue May 23
Wed May 31 | cxzcxzx    | 0       |     |            |          |            | 906 | 19    | // descrip | 1       | Tue May 23
Wed May 31 | jklklkl;   | 0       |     |            |          |            | 907 | 35    | // descrip | 1       | Tue May 23


If you want to use it with your project, put the code into lib/columnized.rb, use require ‘columnized’, and you’re ready to roll. Unlike courtenay’s version, mine only supports max_width, but I didn’t consider changing the column separator too important.

go from model to associated table name and back

Given a table object, it returns the related string object; e.g. SubAttribute => 'sub-attribute'. Useful if you want to make a list of all your tables with perhaps their fields listed out to the side.

def stringify_table( table, replace_char = '-', pluralize = false )
  string = table.to_s.gsub( /([A-Za-z])([A-Z])/, '\1' << replace_char.to_s << '\2' )
  string = string.pluralize if pluralize
  string
end


Given a string akin to the name of a table, it returns the related table object; e.g. 'sub_attributes' => SubAttribute.

def tablify_string( string )
  eval( string.to_s.gsub( /_id/, '' ).singularize.split( '_' ).collect { |word| word.capitalize }.join )
end

PHP - InversoMoltiplicativo

// Calcolo degli inversi moltiplicativi

<html>
	<head>
		<title>Calcolo degli inversi moltiplicativi</title>
	</head>

	<body>
		<center>
		<b>Cancolo dell'Inverso Moltiplicativo</b>
		<br><hr><br>
		<table border="1" align="center">
		<?php
			for($i=0; $i<26; $i++)
			{
		?>
			<tr>
		<?php
				for($j=0; $j<26; $j++)
				{
					if($i==0) echo "<td bgcolor=\"yellow\" align=\"center\">" . $j . "</td>";
					else
					if($j==0) echo "<td bgcolor=\"yellow\" align=\"center\">" . $i . "</td>";
					else
					{
						echo "<td align=\"center\">" . $i*$j . "</td>";
						$matrice[$i-1][$j-1] = $i*$j;
					}
				}
		?>
			</tr>
		<?php
			}

			for($i=0; $i<25; $i++)
				for($j=0; $j<25; $j++)
					$matrice[$i][$j] = $matrice[$i][$j]%26;
		?>
		</table>
		<br><hr>
		<b>Tabella dell'Inverso Moltiplicativo</b>
		<br><hr><br>
		<table border="1" align="center">
		<?php
			for($i=0; $i<26; $i++)
			{
				echo "<tr>";
				
				for($j=0; $j<26; $j++)
				{
					if($i==0) echo "<td bgcolor=\"yellow\" align=\"center\">" . $j . "</td>";
					else
					if($j==0) echo "<td bgcolor=\"yellow\" align=\"center\">" . $i . "</td>";
					else
					{
						echo "<td align=\"center\" " . (($matrice[$i-1][$j-1] == 1)?"bgcolor=\"red\"":"") . "\">" . $matrice[$i-1][$j-1] . "</td>";
						
						if($matrice[$i-1][$j-1] == 1)
							$np[] = $i;
					}
				}

				echo "</tr>";
			}
		?>
		</table>
		<br>
		<i><b>I numeri primi con 26 sono:
		<?php
			for($i=0; $i<count($np); $i++)
				echo $np[$i] . " ";
		?>
		</b></i>
		<br><br>
		Si prendono le coppie di numeri che contengono il numero 1 al loro interno, esempio (1,1), (3,9)......
		</center>
	</body>
</html>
« Newer Snippets
Older Snippets »
Showing 1-10 of 16 total  RSS