The below answer suggested works using mysql_ however I have decided to switch to PDO for the increased security if offers. However When I apply the same code, I am struggling to get it to work.I had to switch the while to foreach for PDO.
UPDATE: Using PHP PDO
$sql = "SELECT * FROM userrecords";
$stmt = $conn->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row)
{
$dateArray = explode('-', $row['eventdate']);
$year = $dateArray[0];
$month= $dateArray[1] - 1;
$day= $dateArray[2];
$dataArray[] = "[new Date ($year, $month, $day), {$row['scientificname']}, {$row['category_of_taxom']}]";
}
echo $dataArray;
Building on the solution from your other question, you have to parse your dates into javascript's Date object format:
$dataArray = array();
while($row = mysqli_fetch_array($result)) {
$dateArray = explode('-', $row['Date']);
$year = $dateArray[0];
$month = $dateArray[1] - 1; // subtract 1 since javascript months are zero-indexed
$day = $dateArray[2];
$dataArray[] = "[new Date($year, $month, $day), {$row['SpeciesA']}, {$row['Speciesb']}]";
}
Because the json_encode function will break the dates here, we have to parse it into the DataTable constructor a bit differently:
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Species A');
data.addColumn('number', 'Species B');
data.addRows(<?php echo '[' . implode(',', $dataArray) . ']'; ?>);
Related
How do I avoid this axis overlap in google charts? I am working with a large data set and not sure what to do to solve this issue. I am using a large number of dates for the x axis. The options I use for my chart are
var options = {
tooltip: {
trigger: 'both',
},
width: 1900,
height: 400,
vAxis: { 'title': 'Volume' },
crosshair: { trigger: 'both'}
};
EDIT::
PHP creation of the containers
if( isset($db_graph_query)){
while($row = mysqli_fetch_array($db_graph_query)) {
$rowcount2++;
// removed the hard coded column set and made it driven off of the array below
// could have pulled it from the $cols array above, but there might be columns that we don't wish to show
echo " <tr>";
$colindex = 0;
foreach( $cols as $column_name ) {
$style = "";
$val = $row[$column_name];
if ( isset($column_callback)) {
$style=$column_callback($colindex, $val);
}
if ($colindex == 0) {
echo "<td style='text-align: left; width: 1pt;'><a href='#' class='toggle' onClick='drawChart(\"$val\");'>$val</a></td>";
$tempval = $val;
} else {
echo "<td $style>$val</td>";
}
$colindex++;
}
echo "</tr>";
echo "<tr class='tablesorter-childRow'>";
echo "<td colspan='12'>";
echo "<div id='$tempval' style='height: 400px;'></div>";
echo "</td>";
echo "</tr>";
}
}
EDIT::
Draw Chart Script, creates the chart options, grabs data from SQL DB and adds into the data:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
function drawChart(inputname) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'RunDate');
data.addColumn('number', 'Runs');
data.addColumn('number', 'Fails');
data.addRows([
<?php
$dbName = "mydb";
$config = parse_ini_file("configfile.ini",true);
$dbUser = $config["DB"]["db_user"];
$dbServer = $config["DB"]["db_ip"];
$dbPassword = $config["DB"]["db_pass"];
$con = mysql_connect($dbServer, $dbUser, $dbPassword);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbName, $con);
$sql = mysql_query("SELECT * From MyTestTable");
$output = array();
while($row = mysql_fetch_array($sql)) {
// create a temp array to hold the data
$temp = array();
// add the data
$temp[] = '"' . $row['Name'] . '"';
$temp[] = '"' . $row['RunDate'] . '"';
$temp[] = (int) $row['Runs'];
$temp[] = (int) $row['FailCount'];
// implode the temp array into a comma-separated list and add to the output array
$output[] = '[' . implode(', ', $temp) . ']';
}
// implode the output into a comma-newline separated list and echo
echo implode(",\n", $output);
mysql_close($con);
?>
]);
var view = new google.visualization.DataView(data);
view.setRows(data.getFilteredRows([
{column: 0, value: inputname}
]));
view.setColumns([1,2,3]);
var options = {
tooltip: {
trigger: 'both',
},
vAxis: { 'title': 'Volume' },
crosshair: { trigger: 'both'},
width: 1900,
height: 400
};
var chart = new google.visualization.LineChart(document.getElementById(inputname));
chart.draw(view, options);
}
</script>
try using option for slanted text...
hAxis: {slantedText: true}
The horizontal axis ticks should not be overlapping at all, and I believe the only way this could be happening is if your chart is not visible at the time you draw it, in which case the chart thinks the ticks don't take up any space and can be packed in as dense as possible. Slanting or alternating would not necessarily help until you get down to the minimum spacing constraint.
So the only real solution, at this time, is to make sure your chart is visible when you draw it.
I would like to query a column name's inputdate, type : date. When I query:
where (inputdate>='$VEStart' AND inputdate<='$VEEnd')
I got:
error : warning pg_query() query failed error invalid input syntax for date where (inputdate>='' AND inputdate<='').
But when I try to replace it:
where (inputdate>='2015-12-01' AND inputdate<='2015-12-31')
It works. I thought it was a problem with variables. so I tried to echo both variables, but they display the right values. Anything wrong here?
Just to give you an example beyond the comment, use something like this and ensure that you add improvements to the below code before putting it into production use; also test it well.
<?php
$VEStart = '2015-01-01';
$VEEnd = '2015-2-28';
// validate the dates
if (!isDateValid($VEStart)) {
print "Invalid start date\n";
return;
}
if (!isDateValid($VEEnd)) {
print "Invalid end date\n";
return;
}
// format the dates
$VEStart = formattedDate($VEStart);
$VEEnd = formattedDate($VEEnd);
echo sprintf ("all good - %s and %s\n", $VEStart, $VEEnd);
// see http://php.net/manual/en/function.pg-query-params.php
$sql = 'select ... where inputdate between $1 and $2';
$connection = pg_connect('...');
$result = pg_query_params($connection, $sql, array($VEStart, $VEEnd));
...more code...
// ----
// add good phpdoc
// see how others add doc - http://stackoverflow.com/questions/1904214/what-is-the-proper-php-function-documentation-format
function formattedDate($date) {
list($year, $month, $day) = explode('-', $date);
return date('Y-m-d', mktime(0, 0, 0, $month, $day, $year));
}
// add good phpdoc
function isDateValid($date) {
list($year, $month, $day) = explode('-', $date);
return checkdate($month, $day, $year);
}
?>
I have a problem and don't know how to solve it. After i run the code i didn't receive corectly a period of time. I put the code here.
I think something is wrong with table from database (i use PhpMyAdmin 4.2.0 module from EasyPhp). I put an image too to see what happens. The dates marked with red need to be at the end of table.
<?php
function data_range($first, $last, $step = '+1 day', $output - format = 'd-m-Y')
{
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while ($current <= $last)
{
$dates[] = date($output_format, $current);
$current = strtotime($step, $current);
}
foreach($dates as $zile)
{
$krr = explode('-', $zile);
var_dump($krr);
$result2 = implode('/', $krr);
echo $result2 . "<br/>";
$sql4 = "INSERT INTO studenti3 (data) VALUES ('$result2')";
$rez4 = mysql_query($sql4);
}
var_dump($dates);
}
$first = "06-04-2015";
$last = "07-05-2015";
$step = "+1day";
$output_format = 'd-m-Y';
date_range($first, $last, $step, $output_format); ?>
I want to display data from moodle database in HTML table, but for every record separate table is being displayed:
Code:
$rec=$DB->get_records_sql('SELECT * FROM `mdl_schedules`');
$table = new html_table();
$table->head = array('Date','Time', 'A' , 'B', 'C','D', 'E', 'F');
foreach ($rec as $records) {
$id = $records->id;
$scheduledatet = $records->scheduledate;
$scheduletime = $records->scheduletime;
$session = $records->s;
$venue = $records->v;
$trainer = $records->t;
$category = $records->c;
$course = $records->course;
$link = $records->link;
$table->data = array(array($scheduledatet, $scheduletime, $a,$b,$c,$d,$e,'View'));
echo html_writer::table($table);
}
Any reference or help will be much appreciated.
The echo should be outside the loop :)
}
echo html_writer::table($table);
But you will probably want to use flexible_table instead so you can use pagination.
Have a look in /admin/localplugins.php for an example.
I know this is old, but the reason you're only getting one record is you're not adding to the $table->data array. This is the code you want:
$rec=$DB->get_records('schedules');
$table = new html_table();
$table->head = array('Date','Time', 'A' , 'B', 'C','D', 'E', 'F');
foreach ($rec as $records) {
$id = $records->id;
$scheduledatet = $records->scheduledate;
$scheduletime = $records->scheduletime;
$session = $records->s;
$venue = $records->v;
$trainer = $records->t;
$category = $records->c;
$course = $records->course;
$link = $records->link;
$table->data[] = array($scheduledatet, $scheduletime, $a,$b,$c,$d,$e,'View');
}
echo html_writer::table($table);
I also changed up your query a bit. If you're just getting all of the records from a table, $DB->get_records('TABLE_NAME_WITHOUT_PREFIX'); is the way to go.
I want to print 7 days span for a particular date.. I have tried reading php manual and tried several things..nothing is working out.
<?php
function add_date($givendate,$day=0,$mth=0,$yr=0) {
$cd = strtotime($givendate);
$newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
date('i',$cd),
date('s',$cd),
date('m',$cd)+$mth,
date('d',$cd)+$day,
date('Y',$cd)+$yr));
return $newdate;
}
?>
but this is not giving me any date.except today's date.
you can use DateTime class:
For example:
$today = new DateTime("now");
$yesterday = $today->modify('-1 day');
$yesterday = get_object_vars($yesterday);
echo $yesterday['date']."<br>";
$twoDaysAgo = $today->modify('-1 day');
$twoDaysAgo = get_object_vars($twoDaysAgo);
echo $twoDaysAgo['date'];