Related
So I have this script which im trying to create a filelist.js file from in php here's the code:
//CREATE fileslist.js
$thumbssize = "1";
$moviesize= "1";
$thumbarray = array_slice(scandir($tpath), 2);
echo print_r($thumbarray) . "<br/>";
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
$script="
fileList = {};
fileList[\"thumbs\"] = {};
fileList[\"movies\"] = {};
fileList[\"title\"]=\"{$foldername}\";";
foreach($thumbarray as $item) {
print "fileList[\"thumbs\"][1]=["$item['0']","$item['2']","$item['3']","$item['4']","$item['5']","$item['6']"];";
}
$script2 = "
fileList[\"thumbs\"][\"size\"]={$thumbssize};
fileList[\"thumbs\"][\"size\"]={$moviesize};";
//$script = preg_replace('/\s\s+/', ' ', $script);
$scriptName= $_SERVER['DOCUMENT_ROOT'] . "/{$foldername}/assets/js/filelist.js";
file_put_contents($scriptName, trim($script . $script2) . "\n", FILE_APPEND);
echo "Generating filelist.js</br>";
}
This here is the example output of the array:
Array ( [0] => 863_example_r003.mp4 [1] => 863_example_r004.mp4 [2] => 863_example_r005.mp4 [3] => 863_example_r006.mp4 [4] => 863_example_r007.mp4 ) 1
This is the filelist.js output as it stands right now:
fileList = {};
fileList["thumbs"] = {};
fileList["movies"] = {};
fileList["title"]="test7";
fileList["thumbs"]["size"]=1;
fileList["thumbs"]["size"]=1;
So up until this point its doing what i want except I cannot figure out how to make a foreach loop to generate this type of output :
fileList = {};
fileList["thumbs"] = {};
fileList["movies"] = {};
fileList["title"]="863-example";
fileList["thumbs"][1]=["863_example_r048.mp4","863_example_r049.mp4","863_example_r050.mp4","863_example_r051.mp4","863_example_r052.mp4","863_example_r053.mp4"];
fileList["thumbs"][2]=["863_example_r054.mp4","863_example_r055.mp4","863_example_r056.mp4","863_example_r057.mp4","863_example_r058.mp4","863_example_r059.mp4"];
fileList["thumbs"][3]=["863_example_r060.mp4","863_example_r061.mp4","863_example_r062.mp4","863_example_r003.mp4","863_example_r063.mp4","863_example_r064.mp4"];
fileList["thumbs"][4]=["863_example_r065.mp4","863_example_r004.mp4","863_example_r067.mp4","863_example_r068.mp4","863_example_r069.mp4","863_example_r070.mp4"];
fileList["thumbs"][5]=["863_example_r005.mp4","863_example_r071.mp4","863_example_r072.mp4","863_example_r073.mp4","863_example_r074.mp4","863_example_r006.mp4"];
fileList["thumbs"][6]=["863_example_r075.mp4","863_example_r076.mp4","863_example_r077.mp4","863_example_r078.mp4","863_example_r007.mp4","863_example_r079.mp4"];
fileList["thumbs"][7]=["863_example_r080.mp4","863_example_r081.mp4","863_example_r082.mp4","863_example_r008.mp4","863_example_r083.mp4","863_example_r084.mp4"];
fileList["thumbs"][8]=["863_example_r085.mp4","863_example_r086.mp4","863_example_r009.mp4","863_example_r087.mp4","863_example_r088.mp4","863_example_r089.mp4"];
The [1], [2], [3] refers to a page number and there needs to be 6 items per page as the example above
Thank you for your feedback. Just a minute ago I refined the code and tested it in my localhost. Here is the changed code that gives the result:
$script1 = "";
$i = 0;
$j = 0;
$inrow = 6; // files in row
foreach($thumbarray as $item => $itemv) {
// beginning of the row
if($j % $inrow == 0){
$script1 .= "\nfileList[\"thumbs\"][".($i+1)."]=[";
}
$script1 .= "\"" . $itemv . "\","; // add filename "863_example_r048.mp4",
// end of the row
if(($j + $inrow + 1) % $inrow == 0){
// Delete comma at end of row
if(substr($script1,-1) == ","){
$script1 = substr($script1, 0, strlen($script1) - 1);
}
$script1 .= "];";
}
if($j % $inrow == 0){
$i++;
}
$j++;
}
Here is the tested result:
fileList["thumbs"][1]=[".AndroidStudio1.3",".ICEauthority",".PlayOnLinux",".Skype",".Xauthority",".adobe"];
fileList["thumbs"][2]=[".android",".audacity-data",".bash_history",".bashrc",".bibletime",".cache"];
fileList["thumbs"][3]=[".claws-mail",".config",".dbus",".directory",".dmrc",".dosbox"];
fileList["thumbs"][4]=[".emacs",".esd_auth",".fltk",".fontconfig",".fonts",".fonts.conf"];
fileList["thumbs"][5]=[".frozen-bubble",".gimp-2.8",".gnome",".gnome2",".gnome2_private",".gnupg"];
fileList["thumbs"][6]=[".gstreamer-0.10",".gtkrc-2.0",".gvfs",".icewm",".inputrc",".ivy2"];
fileList["thumbs"][7]=[".java",".jsword",".kde",".kde4",".kismet",".local"];
fileList["thumbs"][8]=[".macromedia",".mozilla",".mplayer",".mtpaint",".opera",".pki"];
fileList["thumbs"][9]=[".profile",".putty",".pyhistory",".qt",".remmina",".sbt"];
fileList["thumbs"][10]=[".skel",".ssh",".streamtuner",".sword",".themes",".thumbnails"];
fileList["thumbs"][11]=[".thunderbird",".vnc",".wine",".xboardrc",".xdg_menu_cache",".xim.template"];
fileList["thumbs"][12]=[".xinitrc.template",".xiphos",".xscreensaver",".xsession-errors",".xsession-errors-192.168.1.101:1",".xsession-errors-192.168.1.103:1"];
fileList["thumbs"][13]=[".xsession-errors-:0",".xsession-errors-:1",".y2log",".y2usersettings","20150901_134031.jpg","281436_wpmu-dev-dashboard-3.5.3.zip"];
fileList["thumbs"][14]=["Android","AndroidStudioProjects","Bible Analyzer User Modules","Calibre Library","Desktop","Documents"];
fileList["thumbs"][15]=["Downloads","Java","Kismet-20141124-23-54-29-1.alert","Kismet-20141124-23-54-29-1.gpsxml","Kismet-20141124-23-54-29-1.nettxt","Kismet-20141124-23-54-29-1.netxml"];
fileList["thumbs"][16]=["Kismet-20141124-23-54-29-1.pcapdump","Movies","Music","Phpgtk","Pictures","PlayOnLinux's virtual drives"];
fileList["thumbs"][17]=["Public","Templates","Videos","VirtualBox VMs","WPMUDEV_PLUGINS.zip","battery"];
fileList["thumbs"][18]=["bibleanalyzer","bibledesktop-2.0-beta","bin","ca.key","deklaracia.jpg","deklaracia2.jpg"];
fileList["thumbs"][19]=["dfc","http:⁄⁄www.biblestudytools.com⁄niv⁄.desktop","konq","projects","public_html","scala"];
fileList["thumbs"][20]=["somefile","somefile.txt","viber","wget-log","wp-cron.php?import_key=d&import_id=20&action=processing","Запис0003.amr"];
you need to change below part
$index = 1;
foreach($thumbarray as $item) {
$script .= "fileList[\"thumbs\"][$index]= ".json_encode($item).";" ;
$index++;
}
You need two indexes. $i is incremented every time $i is deleted in $inrow times properly with the remainder of 0. If you want 6 rows of files then $i should be increased 6 times less then $j which is increased every time. This way $i would change when $j is 6,12,18,24 and etc. You will need to play a little bit with the code ...
$script1 = "";
$i = 0;
$j = 0
$inrow = 6; // files in row
foreach($thumbarray as $item => $itemv) {
// beginning of the row
if($j % $inrow == 0){
$script1 .= "fileList[\"thumbs\"][".($i+1)."]=[";
}
$script1 .= "\"" . $itemv . "\","; // add filename "863_example_r048.mp4",
// end of the row
if($j % $inrow == 0){
// Delete comma at end of row
if(substr($script1,-1) == ","){
$script1 = substr($script1, 0, strlen($script1) - 1);
}
$script1 .= "]";
$i++;
}
$j++;
}
I have been struggling with this for a while now, I got some help from a similar question but I can't seem to make it work in my example.
I have an RSS feed on my website and what I am trying to do is display a message saying "No Warnings" when the RSS feed is blank/empty. If there is something in the RSS feed then I just want to show that.
For the life of me I can't get this to work! I can't get it to recognize the feed is blank...is this possible??
Here is my code,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" dir="ltr" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Loading directly an RSS feed and displaying it</title></head>
<link type="text/css" href="rss-style.css" rel="stylesheet">
<body bgcolor="#FFE991">
<div id="zone" ><img src="/images/alert-icon-120.png" alt="Weather Warnings for SA. Issued by the Australian Bureau of Meteorology" align="left" style="padding-right: 4pt"width="15" height="15" border="0"/> Current South Australian Statewide Warnings:<small><em><font color="black"> Provided by The Bureau of Meteorology</font></em></small>
</div>
<fieldset class="rsslibbomsa">
<?php
require_once("rsslib.php");
$url = "http://www.bom.gov.au/fwo/IDZ00057.warnings_sa.xml";
$rss = RSS_Display($url, 15, false, false);
if ($rss == '')
{
// nothing shown, do whatever you want
echo 'No Current Warnings';
}
else
{
// something to display
echo $rss123;
}
?>
</fieldset>
</body>
</html>
If it helps RSS_Display is from the rsslib.php file, which I have provided below,
<?php
/*
RSS Extractor and Displayer
(c) 2007-2010 Scriptol.com - Licence Mozilla 1.1.
rsslib.php
Requirements:
- PHP 5.
- A RSS feed.
Using the library:
Insert this code into the page that displays the RSS feed:
<?php
require_once("rsslib.php");
echo RSS_Display("http://www.bom.gov.au/fwo/IDZ00059.warnings_vic.xml", 15);
? >
*/
$RSS_Content = array();
function RSS_Tags($item, $type)
{
$y = array();
$tnl = $item->getElementsByTagName("title");
$tnl = $tnl->item(0);
$title = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("link");
$tnl = $tnl->item(0);
$link = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("pubDate");
$tnl = $tnl->item(0);
$date = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("description");
$tnl = $tnl->item(0);
$description = $tnl->firstChild->textContent;
$y["title"] = $title;
$y["link"] = $link;
$y["date"] = $date;
$y["description"] = $description;
$y["type"] = $type;
return $y;
}
function RSS_Channel($channel)
{
global $RSS_Content;
$items = $channel->getElementsByTagName("item");
// Processing channel
$y = RSS_Tags($channel, 0); // get description of channel, type 0
array_push($RSS_Content, $y);
// Processing articles
foreach($items as $item)
{
$y = RSS_Tags($item, 1); // get description of article, type 1
array_push($RSS_Content, $y);
}
}
function RSS_Retrieve($url)
{
global $RSS_Content;
$doc = new DOMDocument();
$doc->load($url);
$channels = $doc->getElementsByTagName("channel");
$RSS_Content = array();
foreach($channels as $channel)
{
RSS_Channel($channel);
}
}
function RSS_RetrieveLinks($url)
{
global $RSS_Content;
$doc = new DOMDocument();
$doc->load($url);
$channels = $doc->getElementsByTagName("channel");
$RSS_Content = array();
foreach($channels as $channel)
{
$items = $channel->getElementsByTagName("item");
foreach($items as $item)
{
$y = RSS_Tags($item, 1); // get description of article, type 1
array_push($RSS_Content, $y);
}
}
}
function RSS_Links($url, $size = 15)
{
global $RSS_Content;
$page = "<ul>";
RSS_RetrieveLinks($url);
if($size > 0)
$recents = array_slice($RSS_Content, 0, $size + 1);
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0) continue;
$title = $article["title"];
$link = $article["link"];
$page .= "<li>$title</li>\n";
}
$page .="</ul>/n";
return $page;
}
function RSS_Display($url, $size = 15, $site = 0, $withdate = 0)
{
global $RSS_Content;
$opened = false;
$page = "";
$site = (intval($site) == 0) ? 1 : 0;
RSS_Retrieve($url);
if($size > 0)
$recents = array_slice($RSS_Content, $site, $size + 1 - $site);
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0)
{
if($opened == true)
{
$page .="</ul>\n";
$opened = false;
}
$page .="<b>";
}
else
{
if($opened == false)
{
$page .= "<ul>\n";
$opened = true;
}
}
$title = $article["title"];
$link = $article["link"];
$page .= "<li>$title";
if($withdate)
{
$date = $article["date"];
$page .=' <span class="rssdate">'.$date.'</span>';
}
$description = $article["description"];
if($description != false)
{
$page .= "<br><span class='rssdesc'>$description</span>";
}
$page .= "</li>\n";
if($type==0)
{
$page .="</b><br />";
}
}
if($opened == true)
{
$page .="</ul>\n";
}
return $page."\n";
}
?>
Any help would be much appreciated.
Many thanks.
If you look at the rsslib code, you see that if the rss has no articles, the returned string will be \n.
The test to check if the RSS is empty should be if ($rss == "\n")
In addition to this, rsslib seems to be an old code (2010) and it is not object oriented (this is a problem because there are global vars defined outside the functions which can be in conflict with your code.
Moreover, this class does all the formatting of the RSS so if you want to change it, you will need to change the rsslib code.
You should consider using an other class like this one : https://github.com/dg/rss-php which is object oriented and easy to use.
I am using this plugin to paginate my list items but I am confused about how to implement this to query to my table to pull and limit 10 or depending on my needs and display this inside in my <ul> tag.
Here is my sample.
Database.php
class Database{
protected $connection;
public function __construct(PDO $connection)
{
$this->connection = $connection;
}
public function getData(){
try{
$cmd = $this->connection->prepare("SELECT COUNT(*) FROM names");
$cmd->execute();
$rows = $cmd->fetchColumn();
$cmd=null;
return $rows;
}catch(PDOException $ex){
}
}
public function display($start,$perpage){
try{
$cmd = $this->connection->prepare("SELECT name FROM names LIMIT ? , ?");
$cmd->bindParam(1,$start);
$cmd->bindParam(2,$perpage);
$cmd->execute();
$rows = $cmd->fetchAll(PDO::FETCH_ASSOC);
$datali = '';
foreach($rows as $r){
$datali.='<li class="list-group-item">'.$r['name'].'</li>';
}
return $datali;
}catch(PDOException $ex){
}
}
}
index.php
require_once 'includes/config.php';
require_once 'includes/Database.php';
$pdo = new PDO(HOST,USER,PASSWORD);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$connectdb = new Database($pdo);
$rows = $connectdb->getData();
$page = $_GET['page'];
$per_page = 5;
$pages = ceil( $rows / $per_page );
if($page == 0)
$start = 0;
else
$start = ( $page - 1 ) * $per_page;
$data = $connectdb->display($start,$per_page);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
var pages = '<?php echo $pages;?>';
$('#mylist-ul').twbsPagination({
totalPages: pages,
visiblePages: 7,
href: '?page={{number}}'
});
});
</script>
</head>
<body>
<div class="wrapper">
<?php echo $data ?>
<ul class="list-group" id="mylist-ul"></ul>
</div>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery.twbsPagination.min.js"></script>
</body>
</html>
It depends on what you want to display. If you want to display data from a database, here is an example:
Let's say you have table with 10 rows of data in it.
First we need to query the db and get all data from the table
$result = $con->query("SELECT * FROM table");
Now we need to count the rows we got.
$rows = $result->num_rows;
Let's say we want 5 items to be displayed in each page.
$per_page = 5;
We calculate the number of pages with
$pages = ceil( $rows / $per_page );
We will get 2 pages.
Now we will check the page we are on and set the starting point
$page = isset( $_GET['page'] ) ? $con->real_escape_string($_GET['page']) : 0;
$page == 0 ? $start = 0 : $start = ( $page - 1 ) * $per_page;
$curpag = ( $start == 0 ) ? 1 : ( $start / $per_page ) + 1 ;
Now it's time to display data from the table
$result = $con->query("SELECT * FROM table ORDER BY id ASC LIMIT $start, $per_page");
while($row = $result->fetch_array(MYSQLI_ASSOC)):
//display data in table/list/etc.
endwhile;
We add the pagination element with
<ul id="pagination" class="pagination-sm"></ul>
And finally we initialise the plugin
<script>
var pages = '<?php echo $pages;?>'; //We store the number of pages in a variable to use it below
$('#pagination').twbsPagination({
totalPages: pages,
visiblePages: 7,
href: '?page={{number}}' //Very important!
});
</script>
I want to select data from oracle and draw the chart but when I run the my code nothing else drawed.new3.php:
$tns2 = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)) (CONNECT_DATA = (SID = CLUSTDB1)))";
if ($conn = oci_connect("CAKTAS","******", $tns2)) {
echo "";
$stid = oci_parse($conn, "select wonum,STATUS, trunc( (sysdate-STATUSDATE) ) || 'd ' || trunc( mod((sysdate-STATUSDATE)*24,24) ) || ':' || trunc( mod( (sysdate-STATUSDATE)*24*60, 60 ) ) from maximo.WORKORDER_IT_VIEW where VFOPMGRGRP = 'IS_PRICHARHG' and STATUS <> 'COMPLETE' and STATUS <> 'CLOSE'");
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
echo json_encode($row);
} else {
die("could not connect to Maximo DB");
}
And it gives me correct array.
My html code:
<html>
<head>
<title>Kometschuh.de Tracker</title>
<!-- Load jQuery -->
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<!-- Load Google JSAPI -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "new3.php", //my getting data php file
dataType: "json",
async: false
}).responseText;
var obj = window.JSON.stringify(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Kometschuh.de Trackerdaten'
};
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;">
</div>
</body>
</html>
but in browser, I couldnt any chart
Refer my blog: http://howdyharish.wordpress.com/2014/08/11/create-google-charts-using-php-and-oracle-database/#more-3
Here is the code.
Index.php
<?php
ini_set(‘max_execution_time’, 123456);
$conn=oci_connect(‘username‘,’password‘,’DBname‘);
If (!conn)
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$query= oci_parse($conn, “select col1, col2 from tablename“);
oci_execute($query);
$rows = array();
$table = array();
$table['cols'] = array(
array(‘label’ => ‘col1‘, ‘type’ => ‘string‘),
array(‘label’ => ‘col2‘, ‘type’ => ‘number‘),
);
$rows = array();
while($r = oci_fetch_array($query, OCI_ASSOC+OCI_RETURN_NULLS)) {
$temp = array();
//The below col names have to be in upper caps.
echo $r["COL1"];
$temp[] = array(‘v’ => (string) $r["COL1"]);
$temp[] = array(‘v’ => (int) $r["COL2"]);
$rows[] = array(‘c’ => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//Use the line below to see the data in jason format
//echo $jsonTable;
//Use the below lines of code to see data in a HTML table
/*echo “<table border=’1′ >\n”;
echo “<tr><th>col1</th><th>col2</th></tr>\n”;
while ($row = oci_fetch_array($query, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo “<tr>\n “;
foreach ($query as $block) {
echo ” <td>” . ($block !== null ? htmlentities($block, ENT_QUOTES) : “ ”) . “</td>\n”;
}
echo “</tr>\n”;
}
echo “</table>\n”; */
?>
//In head section
<!–Load the Ajax API–>
<script type=”text/javascript” src=”https://www.google.com/jsapi”></script>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js”></script>
<script type=”text/javascript”>
google.load(‘visualization’, ‘1’, {‘packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: ‘name of the chart‘,
is3D: ‘true’,
width: 1000,
height: 600,
fontName: ‘Times-Roman‘,
fontSize: 23,
hAxis: {textStyle: {
fontName: ‘Times-Roman‘,
fontSize: ‘25‘ }}
};
//To create a line chart
var chart = new google.visualization.LineChart(document.getElementById(‘chart_div’));
chart.draw(data, options);
//To create a column chart
var chart2 = new google.visualization.ColumnChart(document.getElementById(‘chart_div2′));
chart2.draw(data, options);
}
</script>
// In body section
<!–this is the div that will hold the pie chart–>
<div id=”chart_div” ></div>
<div id=”chart_div2″ ></div>
You cannot just use json_encode, the PHP output needs to be in the format that the Google API will understand (Google Documentation Here). So basically, you need to have some kind of function in php that transforms the OCI results into a JSON string readable by Google.
I have published a solution that works pretty well in my setup, other users might benefit from it. You can see my code on GitHub:
https://github.com/ernestomonroy/PHP-for-Google-Visualization-API
The php code looks as folows:
<?php
/*
* #author Ernesto Monroy <ehmizmg#gmail.com>
* #version 1.0
* This function takes the Connection Details and the SQL String and creates an two arrays, one for the column info
* and one for the row data. This is then passed to the arrayToGoogleDataTable that builds and outputs the JSON string
*
* Input for this is:
* $un: User Name
* $pw: Password
* $db: Connection String for the DB
* (e.g. '(DESCRIPTION=(CID=MyDB)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521)))(CONNECT_DATA=(SID=MyDB)))' )
* (tip, if you are running your PHP and Oracle Instance on the same server 127.0.0.1 should be used)
*
* WARNINGS:
* -I have not included any Oracle Error Handling
* -I have not included any row limit, so if your query returns an unmanageable amount of rows, it may become an issue for you or your web users.
*FUTURE OPPORTUNITIES:
* -This functions only return type and label properties. If you want to use pattern, id or p (for styling) you can add a check when looping through the columns
* and try to detect a particular column name that you define as the property (EG. if oci_field_name($stid, $i)=="GOOGLE_P_DATA" then ....)
*/
function getSQLDataTable($un,$pw,$db,$SQLString){
$conn=oci_connect($un,$pw,$db);
$stid= oci_parse($conn, "ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
oci_execute($stid);
$stid= oci_parse($conn, $SQLString);
oci_execute($stid);
$ncols = oci_num_fields($stid);
$cols = array();
$rows = array();
$cell = array();
for ($i = 1; $i <= $ncols; $i++) {
$column_label = '"'.oci_field_name($stid, $i).'"';
$column_type = oci_field_type($stid, $i);
switch($column_type) {
case 'CHAR': case 'VARCHAR2':
$column_type='"string"';
break;
case 'DATE':
$column_type='"datetime"';
break;
case 'NUMBER':
$column_type='"number"';
break;
}
$cols[$i-1]=array('"type"'=>$column_type,'"label"'=>$column_label);
}
$j=0;
while (($row = oci_fetch_array($stid, OCI_NUM+OCI_RETURN_NULLS)) != false) {
for ($i = 0; $i <= $ncols-1; $i++) {
switch(oci_field_type($stid, $i+1)) {
case 'CHAR': case 'VARCHAR2':
$cellValue='"'.$row[$i].'"';
$cellFormat='"'.$row[$i].'"';
break;
case 'DATE':
if($row[$i]==null){
$cellValue='""';
$cellFormat='""';
} else {
$cellValue=convertGoogleDate(date_create($row[$i]));
$cellFormat='"'.date_format(date_create($row[$i]), 'd/m/Y H:i:s').'"';
}
break;
case 'NUMBER':
$cellValue=number_format($row[$i], 2, '.', '');
$cellFormat='"'.$row[$i].'"';
break;
} //end of switch
$cell[$i]=array('"v"'=>$cellValue,'"f"'=>$cellFormat);
}
$rows[$j]=$cell;
$j++;
}
arrayToGoogleDataTable($cols, $rows);
}
/*This function takes in the columns and rows created in the previous function and returns the JSON String*/
function arrayToGoogleDataTable($cols, $rows) {
//Convert column array into google string literal
echo "{\n";
echo "\t".'"cols"'.": [\n";
for($i = 0; $i < count($cols)-1; $i++) {
echo "\t\t{";
$n=count($cols[$i]);
foreach($cols[$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "},\n";
}
//Last column without ending comma (},)
echo "\t\t{";
$n=count($cols[$i]);
foreach($cols[$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "}\n\t]";
//Now do the rows
//Check if empty first
if (count($rows)>0){
echo ",\n\t".'"rows"'.": [\n";
//For each row
for($j = 0; $j < count($rows)-1; $j++) {
echo "\t\t{".'"c":[';
//For each cell
for($i = 0; $i < count($rows[$j])-1; $i++) {
echo "{";
$n=count($rows[$j][$i]);
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "},";
}
//Last column without ending comma (},)
$n=count($rows[$j][$i]);
echo "{";
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "}]},\n";
}
//Last row
echo "\t\t{".'"c":[';
//For each cell
for($i = 0; $i < count($rows[$j])-1; $i++) {
echo "{";
$n=count($rows[$j][$i]);
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "},";
}
$n=count($rows[$j][$i]);
echo "{";
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "}]}\n";
echo "\t]";
}
echo"\n}";
}
/*This simply takes in a Date and converts it to a string that the google API recognizes as a Date*/
function convertGoogleDate(DateTime $inDate) {
$googleString='"Date(';
$googleString=$googleString.date_format($inDate, 'Y').',';
$googleString=$googleString.(date_format($inDate, 'm')-1).',';
$googleString=$googleString.(date_format($inDate, 'd')*1).',';
$googleString=$googleString.(date_format($inDate, 'H')*1).',';
$googleString=$googleString.(date_format($inDate, 'i')*1).',';
$googleString=$googleString.(date_format($inDate, 's')*1).')"';
return $googleString;
}
?>
For the rest of the implementation on Java and HTML check the git repo posted above
I know its a late reply, but still a top hit on Google and I have been asked the question a couple of times
I am new to programming so this question of mine might seems irrelevant. I want to know how to hide and show a html element using the original JavaScript not jQuery. Since I'm a total beginner I think I have to learn the primitive JavaScript before jumping into some libraries like jQuery.
First of all I'll paste the code:
index.php
<html>
<head>
<script type="text/javascript" src="myscripts.js"></script>
<style type='text/css'>
#show_description {
min-height: 100px;
min-width: 500px;
max-height: 100px;
max-width: 500px;
background-color: #000;
color: #fff;
}
</style>
</head>
<body>
<div>
<form name="myform" action="index.php" method="get" >
Select Year: <?php echo hspacer(1); ?>
<select id="year_list" name="year_list" onchange="check_year_event();" >
<?php
for($year = (date('Y') - 100); $year <= (date('Y') + 100); $year++ ) {
if ($year == date('Y')) echo "<option value='$year' name='$year' selected='' >" . $year . "</option>";
else echo "<option value='$year' name='$year' >" . $year . "</option>";
}
?>
</select>
<?php echo hspacer(5); ?>
Select Event: <?php echo hspacer(1); ?>
<select id="event_list" name="event_list" onchange="check_year_event();" >
<?php
$events = array("Karate Tournament", "Beauty Pageant", "Film Festival", "Singing Contest", "Wedding");
foreach($events as $event) echo "<option value='$event' name='$event' >" . $event . "</option>";
?>
</select>
<?php echo vspacer(2); echo hspacer(22); ?>
<input type="submit" id="add_description" value="Add Description" onclick="show(); "/>
</form>
</div>
<div id="show_description">
</div>
</body>
</html>
functions.php
<?php
function hspacer($num_of_spaces) {
$spaces = "";
if ($num_of_spaces > 0) for($i=0; $i<$num_of_spaces; $i++ ) $spaces .= " ";
return $spaces;
}
function vspacer($num_of_linefeeds) {
$linefeeds = "";
if ($num_of_linefeeds > 0) for($i=0; $i<$num_of_linefeeds; $i++ ) $linefeeds .= "<br />";
return $linefeeds;
}
?>
myscripts.js
function create2DArray(row, col){
var array2D = new Array(row);
for (var i = 0; i < row; i++) {
array2D[i] = new Array(col);
}
return array2D;
}
function check_year_event() {
var years_and_events = create2DArray(10, 3);
years_and_events[0][0] = 2001;
years_and_events[0][1] = "Karate Tournament";
years_and_events[0][2] = "Annual karate tournament held globally";
years_and_events[1][0] = 2002;
years_and_events[1][1] = "Beauty Pageant";
years_and_events[1][2] = "Beauty pageant held globally";
years_and_events[2][0] = 2003;
years_and_events[2][1] = "Film Festival";
years_and_events[2][2] = "Film festival held globally";
years_and_events[3][0] = 2004;
years_and_events[3][1] = "Singing Contest";
years_and_events[3][2] = "Singing contest tournament held globally";
years_and_events[4][0] = 2005;
years_and_events[4][1] = "Wedding";
years_and_events[4][2] = "Wedding tournament held globally";
years_and_events[5][0] = 2007;
years_and_events[5][1] = "Karate Tournament";
years_and_events[5][2] = "Annual karate tournament held globally";
years_and_events[6][0] = 2008;
years_and_events[6][1] = "Beaty Pageant";
years_and_events[6][2] = "Beauty pageant held globally";
years_and_events[7][0] = 2009;
years_and_events[7][1] = "Film Festival";
years_and_events[7][2] = "Film festival held globally";
years_and_events[8][0] = 2010;
years_and_events[8][1] = "Singing Contest";
years_and_events[8][2] = "Singing contest tournament held globally";
years_and_events[9][0] = 2011;
years_and_events[9][1] = "Wedding";
years_and_events[9][2] = "Wedding tournament held globally";
var year = document.getElementById('year_list').value;
var event = document.getElementById('event_list').value;
for (var i = 0; i < years_and_events.length; i++) {
if ((year == years_and_events[i][0]) && (event == years_and_events[i][1])) {
// This is where I want to put the command to show and hide the div with id = "show_description"
}
}
}
What I want to happen is that when the user changes the value of any of the select element it will automatically check if the combination exists. If there is, it will send the content of the array to the div and that's the only time the div will show.
I'm not pretty sure to what you looking for, some question aren't clear to me. If you say hide or show a div, you can change the style of the div.
//Using visibility
if(show){
document.getElementById('show_description').style.visibility = "visible";
} else {
document.getElementById('show_description').style.visibility = "hidden";
}
//Using display
.style.display = "block"; //To show
.style.display = "none"; //To hide
First, I'd be worried about using the var event, while not a reserve word future developers may get slightly off-balanced to see it in a non DOM-event usage.
Then to start your page off, set that div to visibility:hidden
<div id="show_description" style="visibility:hidden;"></div>
For the code:
var targetNode = document.getElementById('show_description');
var children = targetNode.childNodes;
for(var i=0,len=children.length;i<len;i++){
targetNode.removeChild(children[i]);
}
var newNode = document.createTextNode(year+" "+event);
targetNode.appendChild(newNode);
targetNode.style.visibility = 'visible';
Basically the above selects the div where you want the content to go. Then removes anything inside of it, lastly it creates a new text node of your selected year and event and appends that into the div.
I've found apples DOM script intro to be very helpful for pure js dom manipulating.