When I edit row in grid, changes show only in this grid. But when I reload grid all updates disappear, because data hasn't been updated in database
who can prompt where I was mistaken.
here my test.html
<script type="text/javascript" src="js/jquery.js"></script>
<script src="js/i18n/grid.locale-ru.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqgrid.min.js" type="text/javascript"></script>
<script src="js/grid.common.js" type="text/javascript"></script>
<script src="js/grid.formedit.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$('#table').jqGrid({
url:'test.php',
datatype: 'json',
mtype: 'POST',
height: 500,
colNames:['Код страны','Код региона', 'Город','Долгота','Широта','nbip'],
colModel :[
{name:'country_code', index:'country_code', width:80, editable:true, edittype:'text'},
{name:'region_code', index:'region_code', width:180, editable:true, edittype:'text'},
{name:'city', index:'city', width:190, editable:true, edittype:'text'},
{name:'latitude', index:'latitude', width:160, editable:true, edittype:'text'},
{name:'longitude', index:'longitude', width:160, editable:true, edittype:'text'},
{name:'nbip', index:'nbip', width:130, editable:true, edittype:'text'}],
pager: $('#tablePager'),
pgtext : "Page {0} of {1}",
rowNum:100,
rowList:[10,20,30,100],
sortname: 'city',
sortorder: 'asc',
caption: 'Загрузка JSON данных',
rownumbers: true,
rownumWidth: 40
});
jQuery("#table").jqGrid('navGrid','#tablePager',
{edit:true,add:true,del:true,search:true}, //options
{url:'edit.php', height:280,reloadAfterSubmit:false, closeAfterEdit: true}, // edit options
{height:280,reloadAfterSubmit:false}, // add options
{reloadAfterSubmit:false}, // del options
{} // search options
);
}
});
</script>
</head>
<body>
<table id="table"></table>
<div id="tablePager"></div>
</form>
</body>
</html>
test.php
<?php
$db = mysql_connect($db_host, $db_login, $db_passwd);
mysql_select_db($db_name);
$page = $_POST['page'];
$limit = $_POST['rows'];
$sidx = $_POST['sidx'];
$sord = $_POST['sord'];
if(!$sidx) $sidx =1;
$result = mysql_query("SELECT COUNT(*) AS count FROM cities");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];
if( $count > 0 && $limit > 0) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
$start = $limit*$page - $limit;
if($start <0) $start = 0;
$query = "SELECT id, country_code, region_code, city, latitude, longitude, nbip FROM cities ORDER BY ".$sidx." ".$sord." LIMIT ".$start.", ".$limit;
$result = mysql_query($query);
$data->page = $page;
$data->total = $total_pages;
$data->records = $count;
$i = 0;
while($row = mysql_fetch_assoc($result)) {
$data->rows[$i]['id'] = $row[id];
$data->rows[$i]['cell'] = array($row[country_code],$row[region_code],$row[city],$row[latitude],$row[longitude],$row[nbip]);
$i++;
}
header("Content-type: text/script;charset=utf-8");
echo json_encode($data);
?>
edit.php
$db = mysql_connect($db_host, $db_login, $db_passwd) or die("Connection Error: " . mysql_error());
mysql_select_db($db_name) or die("Error conecting to db.");
//mysql_query("SET NAMES 'utf8'");
// And so on for the other form values
$id = $_POST['id'];
$country_code = mysql_real_escape_string($_POST['country_code']);
$region_code = mysql_real_escape_string($_POST['region_code']);
$city = $_POST['city'];
$latitude = mysql_real_escape_string($_POST['latitude']);
$longitude = mysql_real_escape_string($_POST['longitude']);
$nbip = mysql_real_escape_string($_POST['nbip']);
if($_POST['oper']=='add'){
// mysql insert
}else if($_POST['oper']=='edit'){
// mysql update
$query = "UPDATE cities SET city = '".$city."' WHERE id = ".$id;
$result = mysqli_query($db,$query) or die(mysql_error());
break;
}else if($_POST['oper']=='del'){
// mysql delete
}
?>
Thanks.
you are using mysqli for data updates and using mysql_real_escape_string, mysql_connect, mysql_select_db in your code as well.
update your code to use only mysqli instead of using both mysql and mysqli
Related
<?php>
if (isset($_POST['search']))
{
$startDate = $_POST['start'];
$startDate = str_replace('/', '-', $startDate );
$startDate = date("Y-m-d", strtotime($startDate));
echo $startDate;
$endDate = $_POST['end'];
$endDate = str_replace('/', '-', $endDate );
$endDate = date("Y-m-d", strtotime($endDate));
echo $endDate;
$model = $_POST['model'];
echo $model;
$dates = getDatesStartToLast($startDate, $endDate);
for ($i=0; $i < count($dates); $i++){
echo "<tr>";
echo "<td><text class = 'dateselect'>$dates[$i]</text></td>";
$query = mysqli_query($conn, "SELECT * from electec_db where DateInputTime >= '$dates[$i]' and DateInputTime <= '$dates[$i] 23:59:59' and Model = '$model'");
$count = mysqli_num_rows($query);
// echo $count;
echo "<td>$count</td>";
$arrays = array("Result = 'NG'", "Species = 'Burr'", "Species = 'Dirt'", "Species = 'Scratch'", "Species = 'Cracked'", "Species = 'Gas'" );
for ($j=0; $j < count($arrays); $j ++){
$query = mysqli_query($conn, "SELECT * from electec_db where DateInputTime >= '$dates[$i]' and DateInputTime <= '$dates[$i] 23:59:59' and Model = '$model' and $arrays[$j]");
$count = mysqli_num_rows($query);
echo "<td>$count</td>";
// And this is jsp code
<script>
$('.dateselect').click(function() {
var dateSelect = $(this).text();
alert(dataSelect)
}
</script>
This is php code and javascript code.
When I click echo "$dates[$i]"; part,
I want to make react in script like alert dateSelect variable. But it doesn't make any reaction.
How to make a table react in javascript when clicked in php?
Do you have jQuery installed in your project? That's what the $ indicates.. Not sure what the jsp comment is about.
In straight javascript you could do something like this:
document.querySelectorAll('.dateSelect').forEach(item => {
item.addEventListener('click', event => {
alert(event.target.innerHTML)
})
})
<p class="dateSelect">thing1</p>
<p class="dateSelect">thing2</p>
<p class="dateSelect">thing3</p>
I have a small problem of requete mysql I explain I would like to put one day the column "status" via a checkbox by clicking a plus button, then I click the button nothing happens.
I would like to know if my code is good
Requette.php
<?php
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "Mm101010";
$dbname = "smartphone";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* Database connection end */
$data_ids = $_REQUEST['data_ids'];
$data_id_array = explode(",", $data_ids);
if(!empty($data_id_array)) {
foreach($data_id_array as $Or_Affectation) {
$sql = "UPDATE abonnements SET Statut = 'Non Affecté' ";
$sql.=" WHERE Or_Affectation = '".$Or_Affectation."'";
$query=mysqli_query($conn, $sql) or die("supr_Affect.php: Suprimer Affectation");
}
}
?>
index.php
<!DOCTYPE html>
<html>
<title>Smartphone</title>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="css/bouton.css">
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" >
$(document).ready(function() {
var dataTable = $('#vu_affect_empl').DataTable( {
"processing": true,
"serverSide": true,
"columnDefs": [ {
"targets": 0,
"orderable": false,
"searchable": false
} ],
"ajax":{
url :"Affectation.php", // json datasource
type: "post", // method , by default get
error: function(){ // error handling
$(".vu_affect_empl-error").html("");
$("#vu_affect_empl").append('<tbody class="vu_affect_empl-error"><tr><th colspan="3"></th></tr></tbody>');
$("#vu_affect_empl_processing").css("display","none");
}
}
} );
$("#action_ligne").on('click',function() { // bulk checked
var status = this.checked;
$(".updateRow").each( function() {
$(this).prop("checked",status);
});
});
$('#update_affect').on("click", function(event){ // triggering delete one by one
if( $('.updateRow:checked').length > 0 ){ // at-least one checkbox checked
var ids = [];
$('.updateRow').each(function(){
if($(this).is(':checked')) {
ids.push($(this).val());
}
});
var ids_string = ids.toString(); // array to string conversion
$.ajax({
type: "POST",
url: "supr_Affect.php",
data: {data_ids:ids_string},
success: function(result) {
dataTable.draw(); // redrawing datatable
},
async:false
});
}
});
} );
</script>
<style>
div.container {
margin: 0 auto;
max-width:760px;
}
div.header {
margin: 100px auto;
line-height:30px;
max-width:760px;
}
body {
background: #f7f7f7;
color: #333;
font: 90%/1.45em "Helvetica Neue",HelveticaNeue,Verdana,Arial,Helvetica,sans-serif;
} </style>
</head>
<body>
<h2 align="center">Affectation</h2><br/><br/><br/>
<center>
<button href="Abonnement.php" id="update_affect" class="bouton_dans_page">Abonnement</button>
Employe
Equipement
Modele
Nouvelle Affectation
Employe
Menu Smarphone
<table id="vu_affect_empl" cellpadding="0" cellspacing="0" border="0" class="display" width="100%"><br/><br/><br/><br/>
<thead>
<tr>
<th><input type="checkbox" id='action_ligne' /></th>
<th>USER ID</th>
<th>Nom</th>
<th>Prenom</th>
<th>Num SIM</th>
<th>PIN Terminal</th>
<th>PIN SIM</th>
<th>Num EMEI</th>
<th>Date Debut</th>
<th>Date Fin</th>
<th>Vitre</th>
<th>Coque</th>
<th>Support Vehicule</th>
<th>Actif</th>
<th>Statut</th>
</tr>
</thead>
</table><br><br>
<button type="button" class="Menu" id="update_affect" name="Supprimer_affect">Suprimer Affectation</button>
<button class="Menu" type="button" id="C_R_E" onclick="javascript:Confirmer" name="C_R_E">Confirmer Retour Equipement</button>
Remplacer Equipement
<button class="Menu" type="button" id="A_S_L" name="A_S_L">Ajout et Supression Ligne</button>
<button class="Menu" type="button" id="C_R_A" name="C_R_A">Confirmer Retour Abonnement</button>
<button class="Menu" type="button" id="Reaff_Equip" name="Reaff_Equip">Reaffectation Equipement</button>
</center>
</body>
</html>
thank you
$('.updateRow').each(function(){
if($(this).is(':checked')) {
ids.push($(this).data('yourID'));
}
});
I think that you are passing the wrong information regarding the ID's you need (you are using ids.push($(this).val()); and if the value of the checkbox does not contain the ID needed you will not get anything).
EDIT:
Change the class of the checkbox at line:
$nestedData[] = "<input type='checkbox' class='deleteRow' value='".$row['Or_Affectation']."' /> N°".$i ;
to
$nestedData[] = "<input type='checkbox' class='updateRow' value='".$row['Or_Affectation']."' /> N°".$i ;
Yes of course
<?php
$servername = "localhost";
$username = "root";
$password = "Mm101010";
$dbname = "smartphone";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
$requestData = $_REQUEST;
$columns = array(
0 => 'USER_ID',
1 => 'Nom',
2 => 'Prenom',
3 => 'Num_SIM',
4 => 'PIN_Terminal',
5 => 'PIN_SIM',
6 => 'Num_IMEI',
7 => 'Date_Debut',
8 => 'Date_Fin',
9 => 'Vitre',
11 => 'Coque',
12 => 'Support_Vehicule',
13 => 'Actif',
14 => 'Statut'
);
$sql = "SELECT Or_Affectation ";
$sql.=" FROM vu_affect_empl";
$query=mysqli_query($conn, $sql) or die("Affectation.php: get employees");
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData;
$sql = "SELECT Or_Affectation, USER_ID, Nom, Prenom, Num_SIM, PIN_Terminal, PIN_SIM, Num_IMEI, Date_Debut, Date_Fin, Vitre, Coque, Support_Vehicule, Actif, Statut ";
$sql.=" FROM vu_affect_empl WHERE 1=1";
if( !empty($requestData['search']['value']) ) {
$sql.=" AND ( USER_ID LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR Num_SIM LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR Nom LIKE '".$requestData['search']['value']."%' )";
}
$query=mysqli_query($conn, $sql) or die("Affectation.php: get employees");
$totalFiltered = mysqli_num_rows($query);
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
$query=mysqli_query($conn, $sql) or die("Affectation.php: get employees");
$data = array();
$i=1+$requestData['start'];
while( $row=mysqli_fetch_array($query) ) {
$nestedData=array();
$nestedData[] = "<input type='checkbox' class='updateRow' value='".$row['Or_Affectation']."' /> N°".$i ;
$nestedData[] = $row["USER_ID"];
$nestedData[] = $row["Nom"];
$nestedData[] = $row["Prenom"];
$nestedData[] = $row["Num_SIM"];
$nestedData[] = $row["PIN_Terminal"];
$nestedData[] = $row["PIN_SIM"];
$nestedData[] = $row["Num_IMEI"];
$nestedData[] = $row["Date_Debut"];
$nestedData[] = $row["Date_Fin"];
$nestedData[] = $row["Vitre"];
$nestedData[] = $row["Coque"];
$nestedData[] = $row["Support_Vehicule"];
$nestedData[] = $row["Actif"];
$nestedData[] = $row["Statut"];
$data[] = $nestedData;
$i++;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ),
"recordsTotal" => intval( $totalData ),
"recordsFiltered" => intval( $totalFiltered ),
"data" => $data
);
echo json_encode($json_data);
?>
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>
In this matter, I have a problem when site is online(live), it works very good locally but when online (live) does not show events
<script type="text/JavaScript" language="JavaScript">
events = new Array(
<? php
$get_event = $db - > Execute("SELECT * FROM events WHERE fromdate>= date(now()) and removed='N'");
// $get_event=$db->Execute("SELECT * FROM events WHERE fromdate>='".$_SESSION['session_start_date_s_front']."' and removed='N'");
$ttl_event = $get_event - > RecordCount();
$gp = 1;
while (!$get_event - > EOF) {
$xx = dates_range($get_event - > fields['fromdate'], $get_event - > fields['todate']);
$ttl_dte = count($xx) - 1;
for ($i = 0; $i < count($xx); $i++) {
$d_e = explode('-', $xx[$i]);
if ($gp == $ttl_event && $i == $ttl_dte) { ?> ["D", "<?php echo $d_e[1]?>", "<?php echo $d_e[2]?>", "<?php echo $d_e[0]?>", "1:00 AM", "12:59 PM", "<?php echo addslashes($get_event->fields['event'])?>", ""] <? php
} else { ?> ["D", "<?php echo $d_e[1]?>", "<?php echo $d_e[2]?>", "<?php echo $d_e[0]?>", "1:00 AM", "12:59 PM", "<?php echo addslashes($get_event->fields['event'])?>", ""], <? php
}
}
$gp++;
$get_event - > MoveNext();
}
?>
Create a Database Table
CREATE TABLE `events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`date` date NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active, 0=Block',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*
* Function requested by Ajax
*/
if(isset($_POST['func']) && !empty($_POST['func'])){
switch($_POST['func']){
case 'getCalender':
getCalender($_POST['year'],$_POST['month']);
break;
case 'getEvents':
getEvents($_POST['date']);
break;
default:
break;
}
}
/*
* Get calendar full HTML
*/
function getCalender($year = '',$month = '')
{
$dateYear = ($year != '')?$year:date("Y");
$dateMonth = ($month != '')?$month:date("m");
$date = $dateYear.'-'.$dateMonth.'-01';
$currentMonthFirstDay = date("N",strtotime($date));
$totalDaysOfMonth = cal_days_in_month(CAL_GREGORIAN,$dateMonth,$dateYear);
$totalDaysOfMonthDisplay = ($currentMonthFirstDay == 7)?($totalDaysOfMonth):($totalDaysOfMonth + $currentMonthFirstDay);
$boxDisplay = ($totalDaysOfMonthDisplay <= 35)?35:42;
?>
<div id="calender_section">
<h2>
<<
<select name="month_dropdown" class="month_dropdown dropdown"><?php echo getAllMonths($dateMonth); ?></select>
<select name="year_dropdown" class="year_dropdown dropdown"><?php echo getYearList($dateYear); ?></select>
>>
</h2>
<div id="event_list" class="none"></div>
<div id="calender_section_top">
<ul>
<li>Sun</li>
<li>Mon</li>
<li>Tue</li>
<li>Wed</li>
<li>Thu</li>
<li>Fri</li>
<li>Sat</li>
</ul>
</div>
<div id="calender_section_bot">
<ul>
<?php
$dayCount = 1;
for($cb=1;$cb<=$boxDisplay;$cb++){
if(($cb >= $currentMonthFirstDay+1 || $currentMonthFirstDay == 7) && $cb <= ($totalDaysOfMonthDisplay)){
//Current date
$currentDate = $dateYear.'-'.$dateMonth.'-'.$dayCount;
$eventNum = 0;
//Include db configuration file
include 'dbConfig.php';
//Get number of events based on the current date
$result = $db->query("SELECT title FROM events WHERE date = '".$currentDate."' AND status = 1");
$eventNum = $result->num_rows;
//Define date cell color
if(strtotime($currentDate) == strtotime(date("Y-m-d"))){
echo '<li date="'.$currentDate.'" class="grey date_cell">';
}elseif($eventNum > 0){
echo '<li date="'.$currentDate.'" class="light_sky date_cell">';
}else{
echo '<li date="'.$currentDate.'" class="date_cell">';
}
//Date cell
echo '<span>';
echo $dayCount;
echo '</span>';
//Hover event popup
echo '<div id="date_popup_'.$currentDate.'" class="date_popup_wrap none">';
echo '<div class="date_window">';
echo '<div class="popup_event">Events ('.$eventNum.')</div>';
echo ($eventNum > 0)?'view events':'';
echo '</div></div>';
echo '</li>';
$dayCount++;
?>
<?php }else{ ?>
<li><span> </span></li>
<?php } } ?>
</ul>
</div>
</div>
<script type="text/javascript">
function getCalendar(target_div,year,month){
$.ajax({
type:'POST',
url:'functions.php',
data:'func=getCalender&year='+year+'&month='+month,
success:function(html){
$('#'+target_div).html(html);
}
});
}
function getEvents(date){
$.ajax({
type:'POST',
url:'functions.php',
data:'func=getEvents&date='+date,
success:function(html){
$('#event_list').html(html);
$('#event_list').slideDown('slow');
}
});
}
function addEvent(date){
$.ajax({
type:'POST',
url:'functions.php',
data:'func=addEvent&date='+date,
success:function(html){
$('#event_list').html(html);
$('#event_list').slideDown('slow');
}
});
}
$(document).ready(function(){
$('.date_cell').mouseenter(function(){
date = $(this).attr('date');
$(".date_popup_wrap").fadeOut();
$("#date_popup_"+date).fadeIn();
});
$('.date_cell').mouseleave(function(){
$(".date_popup_wrap").fadeOut();
});
$('.month_dropdown').on('change',function(){
getCalendar('calendar_div',$('.year_dropdown').val(),$('.month_dropdown').val());
});
$('.year_dropdown').on('change',function(){
getCalendar('calendar_div',$('.year_dropdown').val(),$('.month_dropdown').val());
});
$(document).click(function(){
$('#event_list').slideUp('slow');
});
});
</script>
<?php
}
/*
* Get months options list.
*/
function getAllMonths($selected = ''){
$options = '';
for($i=1;$i<=12;$i++)
{
$value = ($i < 10)?'0'.$i:$i;
$selectedOpt = ($value == $selected)?'selected':'';
$options .= '<option value="'.$value.'" '.$selectedOpt.' >'.date("F", mktime(0, 0, 0, $i+1, 0, 0)).'</option>';
}
return $options;
}
/*
* Get years options list.
*/
function getYearList($selected = ''){
$options = '';
for($i=2015;$i<=2025;$i++)
{
$selectedOpt = ($i == $selected)?'selected':'';
$options .= '<option value="'.$i.'" '.$selectedOpt.' >'.$i.'</option>';
}
return $options;
}
/*
* Get events by date
*/
function getEvents($date = ''){
//Include db configuration file
include 'dbConfig.php';
$eventListHTML = '';
$date = $date?$date:date("Y-m-d");
//Get events based on the current date
$result = $db->query("SELECT title FROM events WHERE date = '".$date."' AND status = 1");
if($result->num_rows > 0){
$eventListHTML = '<h2>Events on '.date("l, d M Y",strtotime($date)).'</h2>';
$eventListHTML .= '<ul>';
while($row = $result->fetch_assoc()){
$eventListHTML .= '<li>'.$row['title'].'</li>';
}
$eventListHTML .= '</ul>';
}
echo $eventListHTML;
}
?>
//In index.php
<?php
//Include the event calendar functions file
include_once('functions.php');
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Event Calendar by CodexWorld</title>
<!-- Include the stylesheet -->
<link type="text/css" rel="stylesheet" href="style.css"/>
<!-- Include the jQuery library -->
<script src="jquery.min.js"></script>
</head>
<body>
<!-- Display event calendar -->
<div id="calendar_div">
<?php echo getCalender(); ?>
</div>
</body>
</html>
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