I have been trying to figure out how to create a treeview which is populated from a database using various examples I have come across but have not been successful so far.
My database is structured like:
id | parent_id | title | Urgency (Urgency is not implemented yet)
The end result should generate a treeview where the value of urgency dictates the image used for each item.
The code I have been trying to utilise lately is:
<hmtl>
<body>
<?php
function get_children($parent, $level = 1)
{
$result = mysql_query('SELECT * FROM treeview_items WHERE parent_id = '.$parent);
$result2 = mysql_fetch_array($result, MYSQL_ASSOC);
#for avoiding some errors
if(mysql_num_rows($result) > 0)
#start the list
echo '<ul>';
foreach($result2 as $row) {
#print the item, you can also make links out of these
echo '<li>'.$row['title'].'</li>';
#this is similar to our last code
#this function calls it self, so its recursive
get_children($row['id'], $level+1);
}
#close the list
echo '</ul>';
}
mysql_connect('localhost', 'root');
mysql_select_db('test');
$result = mysql_query('SELECT * FROM treeview_items');
$result2 = mysql_fetch_array($result, MYSQL_ASSOC);
#for avoiding some errors
if(mysql_num_rows($result) > 0) {
#start the list
echo '<ul>';
foreach($result2 as $row) {
#print the item, you can also make links out of these
echo '<li>'.$row['title'].'</li>';
#recursive function(made in next step) for getting all the subs by passing
id of main item
get_children($row['id']);
}
#end the list
echo '</ul>';
#some message if the database is empty
}
else echo 'No Items';
#clear the memory
mysql_free_result($result);
?>
</body>
<html>
Basically the code I have doesn't work. What can I try to fix it?
Edit
I altered some of the code to fix a couple of errors
So now what I see is:
1
2
5
Warning: Invalid argument supplied for foreach() in C:\Program Files\EasyPHP-5.3.9\www\test.php on line 13
repeated 100 times until it aborts. Not sure why, because both foreach() in the code are the same, but the one inside the function doesn't work.
The reason the function call is failing is because you have not wrapped that code in PHP tags, but instead you've wrapped them in JS tags.
replace the <script... line with <?php and the </script> line with ?>
you have server side code in php, not client side javascript (judging by the syntax)
Thank you for all the help but Jey managed to solve my problem by basically giving me entirely new code lol
Here is the link to his code on another question:
Categories with sub PHP / MYSQL
Thank you Jey, and everyone else! :)
Related
I wanna build a presence check for our choir in the style of tinder but not as complex.
The database contains names and file paths of pictures of the members. When you click on the "present" or "not present" button, the next picture and name should be shown. In the background, the database table should be updated with true/false for presence. (this will be done later)
My problem is that it almost works, but instead of showing one member, it shows all members with their pictures in one single page.
I understand that I could fire with Javascript to continue and paused php-function but I don't get the clue how.
I tried "break" in the php and call the function again but that didn't work.
<?php
$conn = new mysqli(myServer, myUser, myPass, myDbName);
$sql = "SELECT * FROM mitglieder";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<img class='pic' src='" .$row["folder"]. "/" .$row["img"]. "'><br>" ;
echo "<div id='name'>" .$row["vorname"]. " " .$row["name"]. "</div> <br>";
echo "<img src=''img.png' id='present' onclick='isPresent()'>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<script>
$( document ).ready(function() {
console.log("Ready");
);
</html>`
You can use php function
mysqli_fetch_all()
assign it on the variable outside the while loop and loop or access the indexes in your code.
For Example:
$data = mysqli_fetch_all();
echo $data[0]['name'];
foreach($data as $item)
{
echo $item['name'];
}
You need a way to establish a "state" between your web page and the PHP backend so that you can step through the data. I suggest something like this:
Use an auto-increment integer primary key for the database. That way you can access the data in index order. Let's name the column id
Have your JS code send a form variable - named something like LAST_ID to the PHP in your get. i.e http://someurl.com/script.php?LAST_ID=0
On your first call to the server, send LAST_ID = 0
In your PHP code, fetch the value like this: $id = $_GET('LAST_ID');
Change your SQL query to use the value to fetch the next member like this:
$sql = sprintf("SELECT * FROM mitglieder where id > %d limit 1", $id); That will get the next member from the DB and return only 1 row (or nothing at the end of data).
Make sure to return the id as part of the form data back to the page and then set LAST_ID to that value on the next call.
You can use a HTTP POST with a form variable to the server call that sets that member id to present (maybe a different script or added to your same PHP script with a test for POST vs GET). I suggest a child table for that indexed on id and date.
I hope that puts you in a good direction. Good luck
I've written a PHP script that can populate a table in a particular way so that multiple events (or no events) can be put in one square in an HTML - similar to the layout a calendar would have. But, there's a problem, the while statement I created to fill in squares in the table when there is no data doesn't detect when there is data, and fills the entire table with empty squares. This is what the output looks like (The page is styled using Bootstrap 3). From the mysql data I have provided, these events should be in the square at {Period 1, Monday}.
Here is my data in a mysql database; mysql data
Here is a snippet of the part of the page related to this table;
<?php
$query = "SELECT * FROM configtimetabletwo WHERE term = ".$term." AND week = ".$week." ORDER BY period, day LIMIT 100;";
$results = mysqli_query($conn, $query);
$pp=1; //The current y value of the table
$pd=0; //The current x value of the table
echo '<tr><td>';
while($row = mysqli_fetch_row($results)) {
while((pd!=$row[3] or $pp!=$row[4]) and $pp<6){ //This while statement fills in empty squares and numbers each row.
if($pd==0) {
echo $pp."</td><td>";
$pd++;
}
elseif($pd<5){
echo "</td><td>";
$pd++;
}
else {
echo "</td></tr><tr><td>";
$pd=0;
$pp++;
}
}
echo '<a href="?edit='.$row[0].'" class="label label-default">';
echo $row[5].' '.$row[6].' - '.$row[7]."</a><br>";
}
echo "</td></tr></table>"
?>
I haven't been able to figure out why this happens so far, thanks in advance to anyone who has any idea what's going on.
In the comments below my question, pavlovich pointed out the error. In this case, it was simply an issue of forgetting to use a $ to reference a variable. It would seem that this doesn't throw an error in a while statement like it would elsewhere.
I've searched hard to find a way to print the query of the code above into a HTML part, but i don't find anything. I saw that is possible to present the result by a HTML table using the fetch_assoc() of php. Below is the code, and on a global view the code is fine, because i test it on a full php page. But i need a solution to put it in HTML. Am i trying an impossible thing?
<?php
require_once('connconf.php');
$conn = mysqli_connect($server, $user, $pw, $bdname) or die ('Connection Error');
$sqlquery = "select ID_Vote from Votes where ID_Player = '1'";
if($result = mysqli_query($conn, $sqlquery)) {
$rowcount = mysqli_num_rows($result);
echo $rowcount; //this is the value i want to publish on a HTML <label>
}
?>
If you want to output the results in a table you could do like this:
print "<table>";
while($row = mysqli_fetch_assoc($result)) {
print "<tr><td>".$row['ID_Vote']."</td></tr>";
}
print "</table>";
The same goes if you just want to print the amount of rows:
print "<table>";
print "<tr><td>".$rowcount."</td></tr>";
print "</table>";
Another way of doing it could be to end php:
<?
// Some code
?>
<table>
<tr>
<td><?=$rowcount;?></td>
</tr>
</table>
<?
// More php
?>
You can have a read here
Guys i found the solution to my problem, all the query was ok like i said. But the extension of my webpage was .HTML and when i change it to .php it worked. Now i got the website running with HTML and php code using a .php extension instead .html
Thanks for your attention.
I'm attempting to extract some data from a database and echo each result. The code below is code that I took from a textbook and then tried to modify to fit my own website that is hosted locally. I cannot see where I'm going wrong, no error messages are shown, just a blank screen when I run the scrip.
<?php #script 9.4 view top 5 recipients
// This script exctracts data from db and then displays each record in a table
DEFINE('SYSPATH','FOO');
require '../application/config/database.php';
require 'mysqli_connect.php';
$q = "SELECT alert_recipient as NAME
FROM alert
LIMIT 5;
";
$r = mysqli_query($dbc,$q);
// $dbc database connection comes from required mysqli_connect.php
if($r)
{
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo $row['name'];
}
}
else {
echo "<p>ERROR</p>".mysqli_error($dbc);
}
?>
The code looks okay except for your echo $row['name'];, note that you are selecting NAME, uppercase.
Change your echo statement to be:
echo $row['NAME'];
because field names quoted within $row array are case sensitive.
(Can't comment yet)
Maybe the script works but there is no results to display. Check your database.
I have a submit form that displays into a list format and I'm wondering what I can do to make it so that the list only displays a certain number of the most current submitted info. I'm testing it and currently the list is on a page and just displays 50+ submissions stretching out the page very long.
<?php
$query='select * from article order by `article`.`time` DESC';
$result=mysql_query($query);
echo '<table width="600px">';
while($row = mysql_fetch_array($result))
{
echo "<td><a href='".$row['url']."'>".$row['title']."</a></td> <td>".$row['description']."</td><td>".$row['type']."</td></tr>";
}
echo '<table>';
?>
Welcome to SO! Modify your sql statement as follows:
$query='SELECT * FROM article ORDER BY `article`.`time` DESC LIMIT 10';
Change 10 to however many entries should be displayed.
Even though you only should select the data you need, you might want to take a look at a for-loop, which is useful if you know how many times you want to run something. You might end up with a loop which looks like this:
for($i = 0; $i < 10 && $row = mysql_fetch_array($result); $i++) {
echo "<td><a href='".$row['url']."'>".$row['title']."</a></td> <td>".$row['description']."</td><td>".$row['type']."</td></tr>";
}
This code runs 10 times IF you have enough data.