The question might not really be clear because I could not think of something that could suit my problem, anyway, I am importing some mysql values using php and creating a html table using javascript, however I am having problems with the PHP as well as Javascript part, Also if anyone could tell me how I could just import values from MYSQL database and make a html table with it (That's basically what I am trying to do)
1.) PHP is not importing values from MYSQL correctly
2.) On console it says: "Uncaught SyntaxError: Unexpected token ILLEGAL"
The following is my code,
<?php
$con = mysqli_connect("localhost","root","","human_information");
$result = mysqli_query($con,"SELECT * FROM basic_human_info");
$rows = mysqli_num_rows($result);
$columns = mysqli_num_fields($result);
?>
<body>
<script type="text/javascript">
function createTable(){
var tBody = document.getElementsByTagName("body")[0];
var table = document.createElement("table");
table.style.border=1;
table.style.width='50%';
table.setAttribute('border',1);
var rows = "<?php echo $rows; ?>";
var columns = "<?php echo $columns ?>";
for(var i=0;i<columns;i++){
var tr = document.createElement("tr");
for(var j=0;j<rows;j++){
var td = document.createElement("td");
td.appendChild(document.createTextNode("
<?php
$sql = mysqli_query($con,"SELECT 'First Name' FROM basic_human_info");
echo mysqli_fetch_assoc($sql);
?>
"));
tr.appendChild(td);
}
table.appendChild(tr);
}
tBody.appendChild(table);
}
createTable();
</script>
</body>
You are outputting an array with echo (echo mysqli_fetch_assoc($sql);) which will just print Array in the middle of the Javascript. That leads to the Uncaught SyntaxError.
But the question rather is: Why use Javascript? Try it with HTML first until you get the PHP right, then do what ever you are planning to do with Javascript.
Like this you can try in php directly
while ($row = mysqli_fetch_array($stmt)) {
echo "<tr>";
echo "<td>" . $row["aid"] . "</td>";
echo "<td>" . $row["aname"] . "</td>";
echo "</tr>";
}
Related
Let me try and say this in a way that doesnt get anyone angry or confused.
I have a value that I am outputting into a table.
The value is populated by mysql and php.
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table>";
echo "<tr>";
echo "<td id='countryDbId'>".$row['country']."</td>";
echo "</tr>";
echo "</table>";
}
$conn->close();
}
?>
Then I try to read all the values that were output with javascript.
<script>
var country = document.getElementById("pp").innerHTML;
console.log(country);
</script>
The output is only the first value even though there are over 100 values in that column.
Any help would be appreciated.
I am trying to make a SQL server table display pivoted in HTML using PHP.
The columns of the HTML table would be the content of the "CONCEPT" column of the SQL table and the content of the HTML columns would be the result of the "DATA" column of the SQL.
Not all records have the same number of "columns" that is, for example the serial number 12345 has the RAM column but the serial number 67890 does not, so the HTML table cell should appear as blank.
This is the tab delimited file: https://pastebin.com/sFJEHJLm
All the concepts of each article have a record with the same value as "LINE", but I don't know how to take advantage of this data to make the painting of the table.
I have tried to load each of the SQL columns in different PHP arrays and then cycle through the array by painting the HTML table but, at the moment a serial number that has a column arrives, the relationship of the results in the HTML table is lost With the correct column.
if ($_REQUEST['accion'] == "abrir_auditoria") {
$array_titulos = array();
$Total = 0;
$Actual = 0;
try
{
$sql = "SELECT * FROM AUDITORIAS_LIN WHERE AUDITORIA = '" . $_REQUEST['id'] . "'";
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()):
if (!in_array(htmlspecialchars($r['CONCEPTO']), $array_titulos))
{
array_push($array_titulos, htmlspecialchars($r['CONCEPTO']));
}
endwhile;
echo "<table border=1>";
echo "<tr>";
foreach ($array_titulos as $titulo)
{
echo "<th>$titulo</th>";
}
echo "</tr>";
echo "<tr>";
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$Total = key(array_slice($array_titulos, -1, 1, true));
while ($r = $q->fetch()):
if ($Total != $Actual)
{
echo "<td>" . htmlspecialchars($r['DATO']) . "</td>";
$Actual++;
} else {
echo "</tr><tr>";
echo "<td>" . htmlspecialchars($r['DATO']) . "</td>";
$Actual = 0;
}
endwhile;
echo "</tr>";
echo "</table>";
}
catch(PDOException $pe)
{
die("database connect error:". $pe->getMessage());
}
}
I would like put my code to javascript var like that :
function myFunction(){
var switch = document..(etc..)....style.backgroundcolour;
var somethink2 = 'red'; <----- I tell about it
switch = somethink2;
}
and after that my background colour will be switch after using function.
I can"t do that with PHP code (my code connection with sql database) becouse i have not got a " and '.
"dane" (in getElementByID()) in my code below is and i want put this PHP code inside this div.
Guys please help me :)
Regards!
function swap(){
var zawartosc =
<?php $a4="SELECT silnik FROM marki WHERE model = 'A4'";
$result2 = mysqli_query($connection,$a4);
echo "<br>";
echo "<table border='1'>"; // I WANT PUT THIS LIKE A TEXT
while ($row = mysqli_fetch_assoc($result2)) {
echo "<tr>";
foreach ($row as $field => $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
document.getElementById("dane").innerHTML = zawartosc;
}
Something like this:
$a4="SELECT silnik FROM marki WHERE model = 'A4'";
$result2 = mysqli_query($connection,$a4);
$html = [];
$html[] = "<br>";
$html[] = "<table border='1'>"; // I WANT PUT THIS LIKE A TEXT
while ($row = mysqli_fetch_assoc($result2)) {
$html[] = "<tr>";
foreach ($row as $field => $value) {
$html[] = "<td>" . $value . "</td>";
}
$html[] = "</tr>";
}
$html[] = "</table>";
$html = json_encode($html); //'["<br>","<table border='1'>", ...]'
?>
document.getElementById("dane").innerHTML = <?php echo $html;?>.join("\n"); //no quotes needed
//document.getElementById("dane").innerHTML = ["<br>","<table border='1'>", ...].join("\n");
Or you can just handle it like a normal string, but it's not what I would prefer to do.
$html = implode($html);
?>
document.getElementById("dane").innerHTML = "<?php echo $html;?>"; //careful with quotes here
In other words, don't output from PHP directly, instead build an array. It's much cleaner as you can consolidate that into a single variable and then use it.
For example:
//timeout for demonstration purposes
setTimeout(function(){
document.getElementById("dane").innerHTML = [
"<br>",
"<table border='1'>",
"<tr>",
"<td>foo</td>",
"<td>bar</td>",
"</tr>",
"<tr>",
"<td>biz</td>",
"<td>baz</td>",
"</tr>",
"</table>"
].join("\n");
},500);
table{width:100px;}
<div id="dane"></div>
I like using join (it's like implode) for multi line strings in JS (even in my plugins). In this case it works well with json_encode.
Basically we convert that array of HTML into a JSON string, which becomes a real Array in JS, then we let JS do the imploding with join. Mainly because arrays don't require the use of a quote, so this avoids any issues if we have quotes in our html.
Consider this (using just strings):
<?php
//HEREDOC
$html = <<<HTML
<table border='1' style="color:red;" >
HTML;
?>
document.getElementById("dane").innerHTML = '<?php echo $html;?>';
document.getElementById("dane").innerHTML = "<?php echo $html;?>";
Which becomes this:
document.getElementById("dane").innerHTML = '<table border='1' style="color:red;">'; //syntax error
document.getElementById("dane").innerHTML = "<table border='1' style="color:red;">"; //syntax error
From what I see you can get away with " at the moment, but if you put them in your HTML, you'll probably be in trouble (if your just using strings). Using join avoids this
document.getElementById("dane").innerHTML = ["<table border='1' style=\"color:red;\">"].join("\n"); //json_encode knows how to escape " for json.
Hope it helps!
I want to create a search box, that only displays matched entries as search phrases are typed; the same in function as described here:
How to perform a real time search and filter on a HTML table
The difference is, the table I have is created from a PHP loop - and SQL data. But, I am unsure how to adopt the code to work for me.
Personally, I think it could be related to the "// printing table rows" section.
Here is the code:
var $search_rows = $('#table tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$search_rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
<html>
<script src="./jquery-1.6.4.js"></script>
<script src="./sorttable.js"></script>
<script src="./searchbox.js"></script>
<link rel="stylesheet" href="styles.css">
<head>
<title>Tau Empire Cadre Census</title>
</head>
<body>
<?php
//// //// //// ////
// DATABASE
//// //// //// ////
//database credentials
$db_host="localhost";
$db_user="tau";
$db_pwd="kuhohNg3";
$db="tau_census";
$db_table="cadres";
//make the connection
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($db))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$db_table}");
if (!$result) {
die("Query to show fields from table failed");
}
//assign a variable the number of returned table fields
$fields_num = mysql_num_fields($result);
//// //// //// ////
// HEADING
//// //// //// ////
echo "<h1>Tau Empire Cadre Census</h1>";
// Search box
echo '<input type="text" id="search" placeholder="Type to search">';
//// //// //// ////
// TABLE
//// //// //// ////
//create the table, and use the JS sortable script
echo '<table id="table" class="sortable"><tr>';
// printing table headers
echo "<td class=headings>Designation</td>";
echo "<td class=headings>Location</td>";
echo "<td class=headings>Founding</td>";
echo "<td class=headings>Commanding Officer</td>";
echo "<td class=headings>Current Status</td>";
echo "<td class=headings>Current Location</td>";
echo "<td class=headings>Mission</td>";
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// For each field print the content
for($i=1; $i<$fields_num; $i++) {
echo "<td>" . $row[$i] . "</td>";
}
echo "</tr>";
}
echo "</table>";
mysql_free_result($result);
?>
</body>
</html>
Running this does not throw up any errors, but nor does it work either. This requires brains greater than mine to work out, please.
I have this working now, thanks for all the assistance. It was a possible combination of the following:
i) Having the following script lines inserted correctly:
<script src="./jquery.min.js"></script>
<script src="./jquery-1.6.4.js"></script>
ii) Wrapping the external JS in $(function(){...});
iii) Incorrectly constructing my table rows and data fields.
Since you think the problem lies in the "printing table rows" section, I will point out that indeed you have formatting issues in that section, fix them like this and it might solve some of the problems:
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// For each field print the content
for($i=1; $i<$fields_num; $i++) {
echo "<td>" . $row[$i] . "</td>";
}
echo "</tr>";
}
I have a php function which displays all the data in my mysql table and allows the user to delete data not needed. I managed to get the data to show in a table, get the delete button to ask for confirmation using javascript, but when i try to get the value in the 2nd cell of the table with the query result (the name) and display it on the confirmation tab, it says undefined. Why is that happening? From what i understand, document.getElementById("myText").value where myText is the id of the cell, should return the value in the cell, correct? Also, how would i call and send that value to another php file that has the delete query?
<?php
$row = mysqli_fetch_array($result);
echo "<table>";
echo "<tr class='header'><td class='header'>Delete</td>";
echo "<td class='header'>Added</td>";
echo "<td class='header'>Name</td>";
echo "<td class='header'>Genre</td>";
echo "<td class='header'>Developer</td>";
echo "<td class='header'>Rating</td></tr>";
?>
<script type="text/javascript">
function ConfirmDelete(){
var name = document.getElementById("name").value;
if (confirm("Delete" +name+"?")){
//send the value and call the php
}
}
</script>
<?php
for ($x=0; $row; $x++) {
echo "<tr><td><input type='button' onclick='ConfirmDelete()' name='deleteGame' value='DELETE'></td><td>$row[Added]</td><td id='name'>$row[Name]</td><td>$row[Genre]</td><td>$row[Developer]</td><td align='right'>$row[Rating]</td></tr>";
$row = mysqli_fetch_array($result);
}
?>
</table>