I am having difficulty with getting the JavaScript portion of this code to work the way I would like.
I have managed to pull the array from a MySQL table and convert it using JSON.
However, when I try to get the data into a HTML table, I get individual characters in each cell.
For example, my database has a table with a keyword labels. Inside this are 4 colors Blue, Green, Brown, Hazel exactly as I have entered it here.
When I output via JavaScript, I get one character in each cell instead of 4 cells.
I am "almost" there on my own:
<?php
include 'conn.php';
$sql = "SELECT * FROM variables WHERE id= '1' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$labels = $row["labels"];
}
foreach (explode(',', $labels) as $newLabel) {
echo "{$newLabel} ";
}
}
?>
<script>
<?php $newLabel = $labels ?>
var n = <?php print (json_encode($newLabel)); ?>;
var index;
var myTable= "<table class='hover'>";
myTable+= "<tr><td class='smalltd'style='width: 20px; font-weight:bold;'></td>";
for (index = 0; index < newLabel.length; index++) {
myTable+= "<td class='no' style='width: 100px; font-weight:bold;'>"
+ newLabel[index] + "</td>";
}
myTable+="</table>";
document.write(myTable);
</script>
I suspect the culprit lies in the newLabel.length but I am not certain
First of all, you need to collect your labels into an array, not a string:
$labels[] = $row["labels"];
Second, you've never defined the newLabel javascript variable.
Change
for (index = 0; index < newLabel.length; index++) {
to
for (index = 0; index < n.length; index++) {
and use n or rename n to newLabel
Related
I've been working on a function in a PHP system where I can filter the records and then export it to Excel that has a template using PHPSpreadSheet. My problem is that I don't know how to retrieve the filtered records as said in the title above. I think I'm missing something here in my code. This is my code in fetching the records from database into table.
<?php
$conn = mysqli_connect("localhost", "root", "", "db_ims");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM tbl_par";
$result = mysqli_query($conn, $sql);
echo "<table id='myTable'>";
echo "<thead><tr><th>Article</th>
<th>Description</th>
<th>Property Number</th>
</tr></thead>";
echo "<tbody>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['article'] . "</td>";
echo "<td>" . $row['description'] . "</td>";
echo "<td>" . $row['propertyNumber'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Close the database connection
mysqli_close($conn);
?>
<form action="" method="POST">
<input type="text" id="myInput" onkeyup="filterTable()" placeholder="Search...">
<input type="submit" id="generate" name="generate" value="Submit">
</form>
This is my code in filtering the records:
<script>
function filterTable() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (var j = 0; j < td.length; j++) {
txtValue = td[j].textContent || td[j].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
break;
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
Lastly, this is the code in exporting the filtered table into excel using PHPSpreadSheet:
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
if (isset($_POST['generate'])) {
$spreadsheet = IOFactory::load('Template.xls');
//This is the part where I don't know what to put.
$data = array();
$worksheet = $spreadsheet->getActiveSheet();
$row = 10; // Start inserting data from row 10
foreach ($data as $item) {
$worksheet->setCellValue('A'.$row, $item['article']);
$worksheet->setCellValue('B'.$row, $item['description']);
$worksheet->setCellValue('C'.$row, $item['propertyNumber']);
// ...
$row++;
}
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('exported_file.xlsx');
}
?>
I tried every possible way that I know but still didn't got my expected result.
If you want to submit the values you need to echo the table inside the form and have something to submit - a hidden field for example - then you can add disabled to the fields you do not want to submit
const hide = txtValue.toUpperCase().indexOf(filter) === -1 : true : false;
tr[i].style.display = hide ? "none" : "";
tr[i].querySelector("[type=hidden]").disabled = hide;
I strongly suggest you use AJAX here instead.
I am trying to get some strings from a csv file, to put under a graph from chartjs.
I wrote this php function:
function getTitle($id) {
$stations = fopen("stations.csv", 'r');
//$csv_data = fopen(date("G") . '.csv', 'r');
$csv_data = fopen('16.csv', 'r'); //fopen("/mnt/weather-data/" .
date("Y/m/d/G") . ".csv", 'r');
$data = array();
$DAY_LENGTH = 60 * 60;
$currentDate = date('U');
while (($line = fgetcsv($csv_data)) !== FALSE) {
$date = date('U', strtotime($line[1]));
if ($date >= ($currentDate-$DAY_LENGTH) && $line[2] == $id) {
array_push($data, $line[0]);
}
}
for ($i = 0; $i < count($data); $i++) {
echo $data[$i] . ",";
}
fclose($stations);
fclose($csv_data);
}
which is working fine, everywhere I call this function, it prints the necesarry strings, which is a date, so 2018-02-08 for example.
When I try to call this function in the label part where i need them in ChartJS. it returns this date as a sum, so like 2018-02-08 will return as 2008.
labels: [<?php getTitle(($_GET['id']))?>],
What is it what I'm doing wrong?
Another problem when I try to change $line[0] to $line[1] which is a time with the following format: 20:17:36, my whole application stops working..
Hope anyone can help me!!
The Problem with your code is that the echo will just output the content of the variable but as you are parsing it's value into a javascript array you need to surround your value with quotation marks. So if you change
for ($i = 0; $i < count($data); $i++) {
echo $data[$i] . ",";
}
into
for ($i = 0; $i < count($data); $i++) {
echo "'" . $data[$i] . "',";
}
it should work. This will also solve your other problem. So with this change you should also be able to use the time.
I need a table where the user enters how many rows and columns needed, they enter the numbers and the next page creates the table.
They will enter the info which will be saved into a database. The only way I can think to do this is with dynamic tables, is there a better way? Here is some super basic code, I haven't worked out the full table, wanted to get feedback before I continue in case there is a better way and I need to change course.
Simple form:
How many rows <input type="number" id="rowNumber"/><br>
How many columns <input type="number" id="colNumber"/><br>
<button onclick="myFunction()">Checkout</button>
function myFunction() {
var rowNumber = document.getElementById('rowNumber').value;
var colNumber = document.getElementById('colNumber').value;
window.location.href = "website/test.php?rowNumber="+rowNumber+"&colNumber="+colNumber;
}
test.php
<?php
$rowNumber=$_GET['rowNumber'];
$colNumber=$_GET['colNumber'];
?>
<script>
var numRows = "<? echo $rowNumber ?>";
var numCols = "<? echo $colNumber ?>";
var tableString = "<table>",
body = document.getElementsByTagName('body')[0],
div = document.createElement('div');
for (row = 1; row < numRows; row += 1) {
tableString += "<tr onclick=\"fnselect(this)\"<? if($rowID == "A") { echo "class ='selected'";} ?>>";
for (col = 1; col < numCols; col += 1) {
tableString += "<td>" + "R" + row + "C" + col + "" + "<input type='text' />" + "</td>";
}
tableString += "</tr>";
}
tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);
</script>
Looking into jQuery DataTables. A lot of nice functionality in there.
You can either bind to a JSON data source, or create your own rows manually like this URL:
https://datatables.net/examples/api/add_row.html
So, to use this, you have to reference jquery AND the data tables script. You'll have to either reference them from their given URLs, or download the scripts (I recommend the latter otherwise you create references to outside servers).
I have a select list that is dynamically filled with data from my database. But I don't want the users to see the real column names, so I created a extra column in my database called column_alias. What I want, is to show the column_alias names in the dropdown but keep the real values of column names.
This is how I'm filling the select list with the real column names at the moment:
function loadTables() {
$.getJSON("dropdown_code/get_tables.php", success = function(data)
{
console.log('inside callback');
var optionsTables = "";
for(var i = 0; i < data.length; i++)
{
optionsTables += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#slctTable").append(optionsTables);
$("#slctTable").change();
});
}
And this is the code that get's the data outof my database:
<?PHP
require "opendb.php";
$query = "select table_name
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
while ($row = pg_fetch_array($data))
{
array_push($table_names, $row["table_name"]);
}
echo json_encode($table_names);
require "closedb.php";
?>
Update
This is what my database table looks like:
So I want the table_alias to be visible in my select list, but I want the value to be table_name so it can interact with my database.
Firstly you will need to fetch the alias as well from the database.Change your server side code to the following.
<?PHP
require "opendb.php";
$query = "select table_name,table_alias
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
while ($row = pg_fetch_array($data))
{
array_push($table_names, $row);
}
echo json_encode($table_names);
require "closedb.php";
?>
Then in your client side code simply output the table_alias as option name and table_name as option value.
function loadTables() {
$.getJSON("dropdown_code/get_tables.php", success = function(data)
{
console.log('inside callback');
var optionsTables = "";
for(var i = 0; i < data.length; i++)
{
optionsTables += "<option value='" + data[i]['table_name'] + "'>" + data[i]['table_alias'] + "</option>";
}
$("#slctTable").append(optionsTables);
$("#slctTable").change();
});
}
html
<select id="xoxo_select">
<option value="foo_value">foo</option>
<option value="xoxo_value">xoxo</option>
</select>
js
$('#xoxo_select option[value="xoxo_value"]').text('bar'); // change name of option
$('#xoxo_select option[value="xoxo_value"]').attr('value', 'bar_value'); // change value of option
jsfiddle https://jsfiddle.net/tg126u7g/
Change in fetch data from DB:
<?PHP
require "opendb.php";
$query = "select table_name,table_alis
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
$i=0;
while ($row = pg_fetch_array($data))
{
array_push($table_names[$i], $row["table_name"]);
$i++;
}
echo json_encode($table_names);
require "closedb.php";
?>
Then Change in javascript code:
optionsTables += "<option value='" + data[i][0] + "'>" + data[i][1] + "</option>";
i make a sql query asking for data(its a text question), i output the (question) with a checkbox to the left of it and an input field underneath it to give point worth to it(like a teacher making an exam) . All in a loop w arrays. It outputs the correctly checked questions but only will assign point values to first three questions if there checked. so if i check q1 q2 and q4 it will output q1 q2 q4 and q1 points q2points. Thats my problem, I only want to be able to select three total questions and assign those questions their points.
php in the html
$sql = " SELECT Question FROM examQuestions";
$result = mysqli_query($dbCon, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<input type="checkbox" name="checkboxvar[]" value="'.$row["Question"].'">'.$row["Question"].'<input placeholder="10" class="form-control" type="number" name="points[]">'."<br />";
}
}
im trying to output the data using this:
$checkboxvar = $_POST['checkboxvar'];
$examName = $_POST['examName'];
$questionWorth = $_POST['points'];
$i=1;
$total = 0;
while ($i < 4) {
$x = $i - 1;
echo $checkboxvar[$x];
echo $questionWorth[$x]."<br />";
$total = $total + $questionWorth[$x];
$i = $i +1;
}
echo $total;
As I told you in the comments try modifying your code like this:
$sql = " SELECT Question FROM examQuestions";
$result = mysqli_query($dbCon, $sql);
$i = 0;
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<input type="checkbox" name="checkboxvar[]" value="'.$i++.'-'.$row["Question"].'">'.$row["Question"].'<input placeholder="10" class="form-control" type="number" name="points[]">'."<br />";
}
}
And then, to have the right points for the correspondig question something like this:
$checkboxvar = $_POST['checkboxvar'];
$examName = $_POST['examName'];
$questionWorth = $_POST['points'];
$i = 0;
$total = 0;
while ($i < 3) {
$question = explode("-", $checkboxvar[$i]);
echo $question[1];
echo $questionWorth[$question[0]]."<br />";
$total += $questionWorth[$question[0]];
$i++;
}
echo $total;
This should do the work.
If i understand your implied question correctly, you will need some client side (javascript) code that keeps track of the number of checked checkboxes. As soon as one checks three boxes all remaining ones and corresponding text boxes are disabled.
for naive vanilla js solution your php could look like this:
$index = 0;
while($row = mysqli_fetch_assoc($result)) {
echo "<label><input class='questions' type='checkbox' name='question_{$index}' value='{$row["Question"]}' on_change='limit_to_three(this);'>{$row["Question"]}<label><br>";
echo "<input class='scores' name='score_{$index}'><br>";
$index++;
}
For modern browsers you would need the following in your javascript :
var selected_count = 0;
function limit_to_three(selected_checkbox) {
if (selected_checkbox.checked) {
selected_count++;
} else {
selected_count--;
}
var limit_reached = (selected_count == 3);
var checkboxes = document.getElementsByClassName('questions');
var scores = document.getElementsByClassName('scores');
for (var i=0; i<checkboxes.length; i++) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = scores[i].disabled = limit_reached;
}
}
}
Now, upon submit, you can assume that only checked question checkboxes will be submitted, so your php code could be like this:
$total = 0;
$length = strlen('questions_');
foreach ($_POST as $name => $value) {
if (substr($name, 0, $length) == 'questions_') {
$index = substr($name, $length - strlen($name));
echo $_POST[$name];
echo "<br>";
echo $_POST["scores_{$index}"];
$total += $_POST["scores_{$index}"];
}
}
As i said, this is a naive implementation, that sends question texts back and forth. If i were you i would add ID column to your questions table and use it instead of dynamically generated indexes
Then your html could be generated like this:
while($row = mysqli_fetch_assoc($result)) {
echo "<label><input class='questions' type='checkbox' name='question_{$index}' value='{$row["ID"]}' on_change='limit_to_three(this);'>{$row["Question"]}<label><br>";
echo "<input class='scores' name='score_{$row["ID"]}'><br>";
}
and your receiving php could be like this:
$checked = explode(',', $_POST['questions']);
for ($checked as $id) {
$total += $_POST["scores_{$id}"];
}
Also you could retrieve the checked questions by
$sql = "SELECT * FROM Questions WHERE ID IN ({$_POST['questions']})";