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>
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 just don't seem to get it right, i have tried all the methods and yet i can't get the form to submit after confirmation
It's basically a quiz system, am outputting the response whether the answer is correct or not before submitting, its showing the response but when i click on ok, its not submitting the form to take me to another question
<form id="form" method="post" action="javascript:void(0)">
<ul class="choices">
<?php while($row=$choices->fetch_assoc()): ?>
<li><input name="choice" type="radio" value="<?php echo $row['id']; ?>"/>
<?php echo $row['choice']; ?>
</li>
<?php endwhile; ?>
<input type="submit" id="submit" name="submit1" value="Gönder"/>
<input type="hidden" name="number" value="<?php echo $number; ?>"/>
</form>
and the Bootbox.js code
<script src="../../css/bootbox.min.js"></script>
<script src="../../css/bootbox.locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/bootbox/4.4.0/bootbox.min.js"></script>
<script src="https://cdn.jsdelivr.net/bootbox/4.4.0/bootbox.min.js"></script>
<script>
<?php
$lesson = (int) $_GET['l'];
$number = (int) $_GET['n'];
$q = "select * from `choices_tr` where question_number = $number and is_correct=1 and lesson_number=$lesson";
$result = $mysqli->query($q) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$correct_choice=$row['id'];
$ChoiceFull=$row['choice'];
?>
$('form').on('click', "input[type='submit']", function(e){
var radioValue = $("input[name='choice']:checked").val();
if(radioValue){
if(radioValue==<?php echo $correct_choice;?> ){
e.preventDefault();
var currentTarget = event.target;
bootbox.alert({
closeButton: false,
message: '<center><i class="fa fa-check" style="font-size:48px;color:green"></i></center>',
callback: function (result) {
if (result === null) {
} else {
$.ajax({ url: "process3.php?l=<?php echo $lesson; ?>",
type: "post",
data: [$("input[name='choice']:checked").serialize()],
success: function(data){ alert('success'); } });
}
},
});
setTimeout(function(){
box.modal('hide');
}, 3000);
}
else {
e.preventDefault();
bootbox.alert({
closeButton: false,
message: '<center><i class="fa fa-times" style="font-size:48px;color:red"></i></center><br /> Maalesef yanlış. Doğru cevap: <?php echo $ChoiceFull; ?> <br /> <?php echo $questionac['explanation'] ?>',
callback: function (result) {
}
});
}
}
});
</script>
process.php
<?php include 'database.php'; ?>
<?php session_start();
$_SESSION["login_redirect"] = $_SERVER["PHP_SELF"];?>
<?php
//Check to see if score is set_error_handler
if (!isset($_SESSION['score'])){
$_SESSION['score'] = 0;
$_SESSION['question']=array();
$_SESSION['answer']=array();
}
//Check if form was submitted
if($_POST){
$number = $_POST['number'];
$selected_choice = $_POST['choice'];
$next=$number+1;
$lesson = (int) $_GET['l'];
//Get total number of questions
$query = "select * from questions_tr where lesson_number = $lesson";
$results = $mysqli->query($query) or die($mysqli->error.__LINE__);
$total=$results->num_rows;
//Get correct choice
$q = "select * from `choices_tr` where question_number = $number and is_correct=1 and lesson_number=$lesson";
$result = $mysqli->query($q) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$correct_choice=$row['id'];
$ChoiceFull=$row['choice'];
$fullquestionq = "select * from `questions_tr` where question_number = $number and lesson_number=$lesson";
$resultful = $mysqli->query($fullquestionq) or die($mysqli->error.__LINE__);
$resultrow = $resultful->fetch_assoc();
$QuestionFull=$resultrow['question'];
//compare answer with result
if($correct_choice == $selected_choice){
$_SESSION['score']++;
}else{
$_SESSION['question'][$next-1] = $QuestionFull;
$_SESSION['answer'][$next-1] = $ChoiceFull;
}
if($number == $total){
header("Location: final3.php");
exit();
} else {
header("Location: Bolum3.php?n=".$next."&l=$lesson&score=".$_SESSION['score']);
}
}
?>
firstly do this copy this script
<script>
<?php
$lesson = (int) $_GET['l'];
$number = (int) $_GET['n'];
$q = "select * from `choices_tr` where question_number = $number and is_correct=1 and lesson_number=$lesson";
$result = $mysqli->query($q) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$correct_choice=$row['id'];
$ChoiceFull=$row['choice'];
?>
$('form').on('click', "input[type='submit']", function(e){
var radioValue = $("input[name='choice']:checked").val();
var number = $("input[name='number']");
var lesson = <?=$lesson; ?>
if(radioValue){
if(radioValue==<?php echo $correct_choice;?> ){
e.preventDefault();
var currentTarget = event.target;
bootbox.alert({
closeButton: false,
message: '<center><i class="fa fa-check" style="font-size:48px;color:green"></i></center>',
callback: function (result) {
if (result === null) {
} else {
$.ajax({
url: "process3.php?l=<?php echo $lesson; ?>",
type: "post",
data: 'choice='+radioValue+'&number='+number+'&lesson='+lesson,
success: function(data){ alert('success'); } });
}
},
});
setTimeout(function(){
box.modal('hide');
}, 3000);
}
else {
e.preventDefault();
bootbox.alert({
closeButton: false,
message: '<center><i class="fa fa-times" style="font-size:48px;color:red"></i></center><br /> Maalesef yanlış. Doğru cevap: <?php echo $ChoiceFull; ?> <br /> <?php echo $questionac['explanation'] ?>',
callback: function (result) {
}
});
}
}
});
</script>
then now time is your php
if($_POST){
$number = $_POST['number'];
$selected_choice = $_POST['choice'];
$next=$number+1;
// you didn't send any get request remove this
//$lesson = (int) $_GET['l'];
$lesson = $_POST['lesson'];
// I found mistake till here and other code it depends on your code
//Get total number of questions
$query = "select * from questions_tr where lesson_number = $lesson";
$results = $mysqli->query($query) or die($mysqli->error.__LINE__);
$total=$results->num_rows;
//Get correct choice
$q = "select * from `choices_tr` where question_number = $number and is_correct=1 and lesson_number=$lesson";
$result = $mysqli->query($q) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$correct_choice=$row['id'];
$ChoiceFull=$row['choice'];
$fullquestionq = "select * from `questions_tr` where question_number = $number and lesson_number=$lesson";
$resultful = $mysqli->query($fullquestionq) or die($mysqli->error.__LINE__);
$resultrow = $resultful->fetch_assoc();
$QuestionFull=$resultrow['question'];
//compare answer with result
if($correct_choice == $selected_choice){
$_SESSION['score']++;
}else{
$_SESSION['question'][$next-1] = $QuestionFull;
$_SESSION['answer'][$next-1] = $ChoiceFull;
}
if($number == $total){
header("Location: final3.php");
exit();
} else {
header("Location: Bolum3.php?n=".$next."&l=$lesson&score=".$_SESSION['score']);
}
I need fa fa-star class's mouseenter, mouseout, and onclick function work for each specific 'list' class/li tag(like list class[0, 1, 2, etc]). What I have now is working for every 'list' class. When I mouseenter on a star from different list class the 1st list class's star is changing.
If I mouseenter on a star from 1st list class/li tag the mouseenter function should work for that list class/li tag not for other 'list' class/li tag. if 2nd 'list' class then it should work for that 'list' class/li tag not for others. and for 3rd, 4th etc.
in rateclick function I can send the rating to server but can't fetch it. Can you look into it also?
Here is the code:
index.php and style.css
.fa{
font-size:25px;
}
li{
list-style:none;
padding-left:40px;
padding-bottom:40px;
border-bottom:2px solid #ccc;
width:800px;
}
li:last-child{
border-bottom:none;
}
<?php
require "conx.php";
$sql = "SELECT * FROM customers ORDER BY id ASC";
$query = $conx -> query($sql);
$numrows = $query -> num_rows;
?>
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="css/font-awesome.min.css">
<link rel="stylesheet" href="style.css">
<script src="jquery.min.js"></script>
<body>
<div class="Insert-Into">
<ul>
<?php if($numrows > 0): ?>
<?php while($row = $query -> fetch_assoc()): ?>
<?php $rating = $row["rating"]; ?>
<?php $customerid = $row["id"]; ?>
<li data-rating=<?php echo "$rating"; ?> data-customerid=<?php echo $customerid; ?> class="list">
<br/>
<br/>
<span class="username"><?php echo $row["username"]; ?></span>
<br/>
<br/>
<?php
$i;
$color;
for($i = 1; $i <= 5; $i++){
if($i <= $rating){
$color = "color:orange";
}
else{
$color = "color:#ccc";
}
echo "<i class='fa fa-star' style='$color;' data-rating='$i' onmouseenter='mouseenterrating($i)' onmouseout='clearstar($rating)' onclick='rateclick($customerid, $i)'></i>";
}
?>
<br/>
<br/>
<b>Description</b>
<br/>
<br/>
<div class="desc"><?php echo $row["description"]; ?></div>
</li>
<?php endwhile; ?>
<?php endif; ?>
</ul>
</div>
<script>
function mouseenterrating(count){
var j;
var fa = document.getElementsByClassName("fa");
for(j = 0; j < fa.length; j++){
if(j < count){
fa[j].style.color = "orange";
}
else{
fa[j].style.color = "#ccc";
}
}
}
function clearstar(rating){
var fa = document.getElementsByClassName("fa");
var k;
for(k = 0; k < fa.length; k++){
if(k < rating){
fa[k].style.color = "orange";
}
else{
fa[k].style.color = "#ccc";
}
}
}
function rateclick(customerid, count){
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "rating.php?id="+customerid+"&rate="+count);
xhttp.send();
fetch(customerid);
}
function fetch(e){
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "fetch.php");
xhttp.send();
}
</script>
</body>
</html>
rating.php
<?php
require "conx.php";
if(isset($_GET['id']) && isset($_GET['rate'])){
$customerid = $_GET['id'];
$rate = $_GET['rate'];
$sql = "UPDATE customers SET rating = '$rate' WHERE id = '$customerid'";
$result = $conx -> query($sql);
}
?>
fetch.php
<?php
require "conx.php";
$sql = "SELECT * FROM customers WHERE id = '".customerid."'";
$result = $conx -> query($sql);
$fetch = $result -> fetch_assoc();
?>
conx.php
<?php
$conx = mysqli_connect("localhost", "root", "");
if(!$conx){
echo "Not connected with localhost";
}
$sql = "CREATE DATABASE rating";
$query = $conx -> query($sql);
$dbselect = $conx -> select_db("rating");
if(!$dbselect){
echo "No database selected";
}
$sql = "CREATE TABLE customers(id INT(255) NOT NULL AUTO_INCREMENT UNIQUE KEY, username VARCHAR(200) NOT NULL, description VARCHAR(1000) NOT NULL, email VARCHAR(200) NOT NULL PRIMARY KEY, rating INT(5) NOT NULL)";
$query = $conx -> query($sql);
?>
Building on your initial attempt I have this solution for you:
function onMouseEnter(index){
var fa = document.getElementsByClassName("fa");
var j;
for(j = 0; j < fa.length; j++){
if(j < index){
fa[j].style.color = "orange";
}
else{
fa[j].style.color = "#ccc";
}
}
}
function onMouseOut(){
var fa = document.getElementsByClassName("fa");
var k;
for(k = 0; k < fa.length; k++){
fa[k].style.color = "#ccc";
}
}
Demo
I mixed an "ajax select" and "while scrolling load data" script, and this is working, but I don't know how to print "not found data" in div.status when the output variable (on animals.php) is empty.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Animals</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="search">
<div class="filter category">
<select name="category" id="category">
<option value="">All</option>
<option value="free">Free</option>
<option value="lost">Lost</option>
<option value="found">Found</option>
</select>
</div>
<div class="filter chipnumber">
<input type="text" name="chipnumber" id="chipnumber"></div>
</div>
<div class="send">
<button type="submit" id="submit">Search</button>
</div>
</div>
<script>
$(document).ready(function() {
var animal_limit = 6;
var animal_start = 0;
var animal_action = 'inactive';
function load_animal_data() {
var category = $('#category').val();
var chipnumber = $('#chipnumber').val();
$.ajax({
url: "animals.php",
method: "POST",
data: {animal_limit:animal_limit, animal_start:animal_start, animal_action:animal_action, category:category, chipnumber:chipnumber},
success:function(data) {
$('div.animals').append(data);
if (data == '') {
animal_action = 'active';
} else {
animal_action = 'inactive';
}
}
});
}
load_animal_data();
function search() {
var category = $('#category').val();
var chipnumber = $('#chipnumber').val();
animal_start = 0;
load_animal_data();
}
$('#search').on('click', function() {
search();
});
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() > $('div.animals').height() && animal_action == 'inactive') {
animal_action = 'active';
animal_start = animal_start + animal_limit;
setTimeout(function() {
load_animal_data();
}, 1000);
}
});
});
</script>
<div class="animals"></div>
<div class="status"></div>
</body>
</html>
animals.php
<?php
$connect = mysqli_connect("localhost", "root", "", "petsdata");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($connect,"utf8");
$output = '';
$animal_start = $connect->real_escape_string($_POST["animal_start"]);
$animal_limit = $connect->real_escape_string($_POST["animal_limit"]);
$category = $connect->real_escape_string($_POST["category"]);
$chipnumber = $connect->real_escape_string($_POST["chipnumber"]);
if (isset($animal_start, $animal_limit, $category, $chipnumber)) {
if (!empty($category) && !empty($chipnumber)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE chipnumber LIKE '%".$chipnumber."%' AND category = '".$category."' ORDER BY id LIMIT ".$animal_start.", ".$animal_limit."");
}
else if (!empty($category)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE category = '".$category."' ORDER BY id LIMIT ".$animal_start.", ".$animal_limit."");
}
else if (!empty($chipnumber)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE chipnumber LIKE '%".$chipnumber."%' AND status = '1' ORDER BY id DESC LIMIT ".$animal_start.", ".$animal_limit."");
}
else {
$query = mysqli_query($connect, "SELECT * FROM animals ORDER BY id DESC LIMIT ".$animal_start.", ".$animal_limit."");
}
while ($row = mysqli_fetch_array($query)) {
$output .= '<div class="animal">';
$output .= '<span>Category: ' . $row["category"] . '</span>';
$output .= '<span>Chipnumber: ' . $row["chipnumber"] . '</span>';
$output .= '</div>';
}
}
echo $output;
?>
if($query->num_rows > 0){
//Proceed as normally
}else{
$output = 'No data Found';
}
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