I'm trying to display the new dynamic list by clicking dynamic list. Why do i call them dynamic list? Because the data is from database.
My idea is generating a list of companies, when i click one company, a list of all sites in the company is displayed; And then when i click the one site of one company, a list of all employees in the site is displayed.
Now i have met a problem. When i click any item in list of companies, a list of sites in the last item of company list shows. And when i click any item in the list of sites, a list of employees of last item in sites is showed.
Do you know why?
Here is the code and result image:
<script language="JavaScript">
function toggle(id,id2,id3) {
var state = document.getElementById(id).style.display;
if (state == 'block') {
document.getElementById(id).style.display = 'none';
if (id2 != undefined)document.getElementById(id2).style.display = 'none';
if (id3 != undefined)document.getElementById(id3).style.display = 'none';
} else {
document.getElementById(id).style.display = 'block';
}
}
</script>
<style type="text/css">
#main{
position:relative;
top:20px;
left:20px;
width:200px;
background: lightblue;
}
#hidden {
position:relative;
top:5px;
left:280px;
width:200px;
background: lightgrey;
display: none;
}
#hidden2 {
position:relative;
top:-12px;
left:580px;
width:200px;
background: lightgreen;
display: none;
}
#hidden3 {
position:relative;
top:100px;
left:20px;
width:200px;
background: lightpink;
display: none;
}
</style>
<?php
error_reporting(E_ALL ^ E_NOTICE);
include("./conn/connect.php");
$query = "SELECT * FROM entreprise ORDER BY id";
$result = mysql_query($query) or die("result failed: ".mysql_error());
?>
<div id="main" >
<?php
echo "<ul>";
while($row = mysql_fetch_assoc($result)){
echo "<li onclick=\"toggle('hidden','hidden2','hidden3');\">".$row['name'].'<li>';
$query2 = "SELECT * FROM site WHERE eid = '".$row['id']."'";
//$query2 = "SELECT * FROM site WHERE eid = ".$row['id'];
//$result2 = mysql_query($query2) or die("query2 result error".mysql_error());
$result2 = mysql_query($query2) or die("query2 result error".mysql_error());
}
echo "</ul>";
?>
</div>
<div id="hidden" >
<?php
echo "<ul>";
while($row2 = mysql_fetch_assoc($result2)){
echo "<li onclick=\"toggle('hidden2','hidden3')\">".$row2['name'].'< >';
$query3 = "SELECT * FROM salarie WHERE siteid =".$row2['id'];
//echo $query3;
$result3 = mysql_query($query3) or die("query3 result error".mysql_error());
}
echo "</ul>";
?>
</div>
<div id="hidden2" >
<?php
echo "<ul>";
while($row3 = mysql_fetch_assoc($result3)){
echo "<li onclick=\"toggle('hidden3')\">".$row3['prenom'].'< >';
$query4 = "SELECT * FROM salarie WHERE id =".$row3['id'];
$result4 = mysql_query($query4) or die("query4 result error".mysql_error());
}
echo "</ul>";
?>
</div>
<div id="hidden3">
<?php
echo "<table>";
while($row4 = mysql_fetch_assoc($result4)){
echo "<tr><td>".$row4['prenom'].'</td>';
echo "<td>".$row4['nom'].'</td></tr>';
}
echo "</table>";
?>
</div>
Result image:
Pretty simple: Your PHP code is executed ONCE when you access the site.
So for example the result of this block
while($row = mysql_fetch_assoc($result)){
echo "<li onclick=\"toggle('hidden','hidden2','hidden3');\">".$row['name'].'<li>';
$query2 = "SELECT * FROM site WHERE eid = '".$row['id']."'";
//$query2 = "SELECT * FROM site WHERE eid = ".$row['id'];
//$result2 = mysql_query($query2) or die("query2 result error".mysql_error());
$result2 = mysql_query($query2) or die("query2 result error".mysql_error());
}
is that $result2 holds all the sites of the last company in your list. This is then used in the next loop to generate the corresponding list of sites. Look at the source of the generated HTML file.
PHP is a server side language, the code is executed at the server and it is not re-executed by your Javascript functions (i.e. not executed in the browser).
What you are after is dynamically loading the data from your server with AJAX and pass into the generated HTML.
Edit:
You could also do it without Ajax: Rewrite your PHP like this:
$sitequeries = array()
while($row = mysql_fetch_assoc($result)){
echo "<li onclick=\"showSites('sites_$row['id']');\">".$row['name'].'<li>';
$query = "SELECT * FROM site WHERE eid = '".$row['id']."'";
$sitequeries[$row['id']] = mysql_query($query2 or die("query2 result error".mysql_error());
}
and
<?php
foreach($sitequeries as $id => $query) {
echo "<ul class='sites' id='sites_$id'>";
while($row2 = mysql_fetch_assoc($query)){
//...
}
echo "</ul>";
}
?>
This is not a working example but should give you the right idea. You have to adjust your JS accordingly to show only the corresponding lists, e.g.:
function showSites(id) {
// Hide all lists with class 'site' here and only display the list with id 'id' e.g. 'sites_5'
}
But note that this is not a good solution if you have a lot of companies, site, employes, etc. as the generation of the HTML may take a while. Then Ajax is a better choice.
Your toggle() Function needs 3 Parameters
You set on some places just 2 parameters
echo "<li onclick=\"toggle('hidden2','hidden3')\">".$row2['name'].'< >';
Shoud be
echo "<li onclick=\"toggle('hidden1','hidden2','hidden3')\">".$row2['name'].'< >';
I would do some things about your code:
Split the data acquiring stuff from the rest. At the beginning, get the data from the required tables and keep it in PHP variables. Then, do something with them using a JS framework... something according to your requirements
The problem with your approach is that you are NEVER telling anyone which row's ID should be sent... hence, it sends the id from the row selected by default, which happens to be the last one parsed by HTML parser on the browser. It means, the last one...
Your PHP code does not match your goal. $result2 will always be the last ID found in $result1, and so on.
If you need to generate result2 based on what the user selects in result1, then you need to either create rows for every possible selection then use javascript to show or hide, or utilize Ajax calls (much better).
Might wanna look into JQuery instead of doing it the way you currently are. But streetparade is correct.
Your approach to this task is a bit wrong, I think.
What do you do in the first loop? You setting $result2 variable and you want to access it in the next loop. And in next loop $result2 is set to the last record of first loop.
Have you heard about AJAX? jQuery may be?
Related
I have a problem that is giving me a headache. I'm fairly new to PHP and MySQL interacting, and coding in general (about 3 months since I first dived into it), so I'm still learning the ropes, so to speak.
The thing is, I have a page that receives data through $_POST from another. All is fine for well. The page receives the data, which is an ID number, and echoes the item's characteristics available in the database corresponding to that ID.
This part of the code works just fine.
$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "Nome: "."<span style='color: red;'>".$row["nome"].
"</span>".
"<br>"."Preço: "."<span style='color: red;'>".
"R$".$row["preco"]."</span>"."<br><br>".$row["status"];
}
}
What I want, is to turn the values echoed into variables, so that I can set them as default value in another form and send that one to another page. Apparently, $row['nome'], for example, isn't available for re-use outside of the instance above.
<form method="post" action="?p=venda">
<input type="text" name="nome" value="<?php echo $row["nome"]; ?>">
<input type="text" name="preco" value="<?php echo $row["preco"]; ?>">
<input type="submit" name="change" value="Efetuar">
</form>
I know this code is prone to SQL injection, but I'm not looking into it right now. This will be a sort of offline program to help me with organizing some of my stuff, so, for now, I don't have to worry about security (not that I'll keep ignoring these issues).
Thanks in advance.
Assign $row to a variable and treat it as an array() outside the while loop.
$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$array = $row; // assign $row a variable.
echo "Nome: "."<span style='color: red;'>".$row["nome"].
"</span>".
"<br>"."Preço: "."<span style='color: red;'>".
"R$".$row["preco"]."</span>"."<br><br>".$row["status"];
}
}
// example
echo($array['nome']);
OK I'll tell you this, its actually unnecessary to sanitize every post. Its only necessary if your authenticated users are web users and there is a blank that they type code in.
In closed production environments, where your users are, you can safe guard the environment in several ways, but this is off topic here.
anyways, you have a DB chart that has a an Id column, the item name, and I am guessing stock or production status.
your display, I don't use spans, but I'll show you how I do it with tables.
So lets make your query for your colums: nome, preco, status
Here are the two methods, the first one is called looped result method which is mostly used for more than one row in the db table:
<?php
//load it in a variable and trim the outside spaces away if you are entering this from a blank form
$id=trim($_POST[id]);
///this should look familiar to you
$sql = "SELECT nome, preco, status FROM produtos WHERE id ='".$id."'";
///but I use the shorthand method here to get my results.
$result = $conn->query($sql);
///Now we loop and shift colum information into variables
/// in a incremental loop, the colums are numbered starting with 0
echo "<table align=center bgcolor=fff2e2 border=1>\n";
while ($data = $result->fetch_row()) {
////I print my table header, and start the data row, if I want it as several ids I will reset here too (which I will do here if you want to play with this)
echo '<tr><th>Nome</th><th>Preco</th><th>Status</th></tr>';
echo '<tr>';
for ($m=0; $m<$result->field_count; $m++) {
if ($m==0){
$nome='';
$nome=$data[$m];
echo '<td bgcolor="#ff0000">'.$nome.'</td>';
} else if ($m==1){
$preco='';
$preco=$data[$m];
echo '<td bgcolor="#ff0000">'.$preco.'</td>';
}else if ($m==2){
$status='';
$status=$data[$m];
echo '<td bgcolor="#ffffff">'.$status.'</td>';
}
}
//////now if I was building a query chart with submit to another I would put my form and my hidden inputs here before i close the table row with /tr, and my submit button would be my first cell value
echo "</tr>";
}
echo "</table>";
You could do the regular colum /row method since it is one ID, which would look like this I used the span format here so you can get the idea of how html is typically expressed in php:
$id=trim($_POST[id]);
$sql = "SELECT nome, preco, status FROM produtos WHERE id ='".$id."'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$nome=stripslashes($row['nome']);
$preco=stripslashes($row['preco']);
$status=stripslashes($row['status']);
echo 'Nome: <span style="color: red;">'.$nome.'</span><br>Preço: <span style="color: red;">'.$preco.'</span><br><br>'.$status;
///notice my quote usage above
here is my table example if I was going to list the whole db table in a scrollable list, and submit it to a file called detail.php
<?php
$sql = "SELECT nome, preco, status FROM produtos";
$result = $conn->query($sql);
echo "<table align=center bgcolor=e3fab5 ><td>";
echo '<div style="width: 500px; height: 450px; overflow: auto; border 5px dashed black; background color: #ccc;">';
echo "<table align=center bgcolor=fff2e2 border=1>\n";
while ($data = $result->fetch_row()) {
echo '<tr><th>Nome</th><th>Preco</th><th>Status</th></tr>';
echo '<tr>';
for ($m=0; $m<$result->field_count; $m++) {
if ($m==0){
$nome='';
$nome=$data[$m];
echo '<td bgcolor="#ff0000"><form action="detail.php" method="post"><input type="submit" name="id" value="'.$nome.'"></td>';
} else if ($m==1){
$preco='';
$preco=$data[$m];
echo '<td bgcolor="#ff0000">'.$preco.'<input type="hidden" name="preco" value="'.$preco.'"></td>';
}else if ($m==2){
$status='';
$status=$data[$m];
echo '<td bgcolor="#ffffff">'.$status.'<input type="hidden" name="status" value="'.$status.'"></td>';
}
}
echo "</form></tr>";
}
echo "</table>";
echo "</div></table>";
?>
How would I make a hyperlink from my product table visible for a session user that is subscribed in my user table while a non-subscribed user can not see the link from the product table?
This is the current code I have.
<?php
$db = mysql_connect("localhost", "", "");
mysql_select_db("",$db);
$result = mysql_query("SELECT * FROM inventoryTable",$db);
$query="select * from users where sub = 'yes'";
$id=mysql_query($query);
echo "<TABLE style=\"background-color: #FFFFFF; border: 10px solid A4A4A4;\">";
echo"<TR><TD><B>Title</B>
<TD><B>Authors First Name</B>
<TD><B>Authors Last Name</B>
<TD><B>ISBN</B><TD>
<B>Publisher</B>
<TD><B>Course Number</B>
<TD><B>Source</B></TR>";
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["title"].
"<TD>".$myrow["authorsFirst"].
"<TD>".$myrow["authorsLast"].
"<TD>".$myrow["ISBN"].
"<TD>".$myrow["publisher"].
"<TD>".$myrow["courseNum"];
If($_SESSION['username']== '$id')
{"<td>".$myrow["source"];
} else {
echo "<TD>"."Please subscribe to View";
}
echo "</TABLE>";
}
?>
My if statement is always returning false. I am wanting the users from my user table that have a 'yes' in their sub field to be able to view the source field from my inventoryTable.
If($_SESSION[username]== subscribed Id or name){ $myrow["link"]}else{blank }
I am trying to combine two things which are already know how to do, but can't figure out how to combine them. Here is what I want to achieve:
I have a database with locations and events. There are several events in each location. I will be using PHP to query the database and output the code needed to display search results. I want something similar to the below:
<div id="location">
<p>Location1</p>
<div id="event">Event1</div>
<div id="event">Event2</div>
<div id="event">Event3</div>
</div>
<div id="location">
<p>Location2</p>
<div id="event">Event4</div>
<div id="event">Event5</div>
<div id="event">Event6</div>
</div>
I know that I can use select distinct to get the unique value of each location, and know that I can use a normal select statement to get all the events, however how do add all the events inside the location div?
My current PHP looks like this:
$sql ="SELECT location, event from events";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
$location = $row['location'];
$event = $row['event'];
echo "<div id="location">
<p>$location</p>
<div id="event">$event</div>
</div>";
}
My current code adds duplicates of the same location with 1 unique event in each. Even if I use select distinct I get the same results. How do I group the events have have the same location?
I think you should write something like:
$sql ="SELECT location, event from events";
$res = mysql_query($sql) or die(mysql_error());
$prevlocation = "";
while($row = mysql_fetch_assoc($res))
{
$location = $row['location'];
$event = $row['event'];
if ( $prevlocation != "" ) // Close previous div if needed
{
echo "</div>";
}
if ( $location != $prevlocation )
{
echo "<div id='location'><p>$location</p>";
$prevlocation = $location;
}
else
{
echo "<div id='event'>$event</div>";
}
}
echo "</div>"; // Close last div
If you have join of two tables, let's assume that your query looks like this:
$sql ="SELECT * FROM events
JOIN locations ON
locations.id=events.loc_id";
And then, within one loop, get events and location arrays:
$res = mysql_query($sql) or die(mysql_error());
$locations = array();
$events= array();
while($row = mysql_fetch_assoc($res))
{
$location = $row['location'];
$event = $row['event'];
$loc_id=$row['loc_id'];
$id=$row['id'];
$events[]=$loc_id.'%'.$event;
if(!in_array($id.'%'.$location,$locations)) { // avoid duplicate entries
$locations[]=$id.'%'.$location;
}
}
And, another loop (+loop inside loop):
for($i=0;$i<count($locations);$i++) {
$location=explode('%',$locations[$i]);
echo "<div class='location'>\n
<p>$location[1]</p>\n";
for($j=0;$j<count($events);$j++) {
$event=explode('%',$events[$j]);
if($event[0]==$locations[$i][0]) {
echo "<div class='event'>".$event[1]."</div>";
}
}
echo "</div>";
}
Not so elegant, but it is working, and produces valid HTML. :)
First, i wanted to make two associative arrays, and to compare keys, but i couldn't, because i couldn't convert ID keys to strings, so i made it with explode (% is separator between key and value).
I'm working on a project to further learn php and how it can be used to interface with a mysql database. The project is a forum, with the page in question displaying all the topics in a category. I'd like to know if I am handling my calls efficiently, and if not, how can I structure my queries so they are more efficient? I know its a small point with a website that isn't used outside of testing, but I'd like to get a handle on this early.
<?php
$cid = $_GET['cid'];
$tid = $_GET['tid'];
// starting breadcrumb stuff
$catname = mysql_query("SELECT cat_name FROM categories WHERE id = '".$cid."'");
$rcatname = mysql_fetch_array( $catname );
$topicname = mysql_query("SELECT topic_title FROM topics WHERE id = '".$tid."'");
$rtopicname = mysql_fetch_array( $topicname );
echo "<p style='padding-left:15px;'><a href='/'> Home </a> » <a href='index.php'> Categories </a> » <a href='categories.php?cid=".$cid."'> ".$rcatname['cat_name']."</a> » <a href='#'> ".$rtopicname['topic_title']. "</a></p>";
//end breadcrumb
$sql = "SELECT * FROM topics WHERE cat_id='".$cid."' AND id='".$tid."' LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) == 1) {
echo "<input type='submit' value='Reply' onClick=\"window.location = 'reply.php?cid=".$cid."&tid=".$tid."'\" />";
echo "<table>";
if ($_SESSION['user_id']) { echo "<thead><tr><th>Author</th><th>Topic » ".$rtopicname['topic_title']."</th></thead><hr />";
} else {
echo "<tr><td colspan='2'><p>Please log in to add your reply.</p><hr /></td></tr>";
}
echo "<tbody>";
while ($row = mysql_fetch_assoc($res)) {
$sql2 = "SELECT * FROM posts WHERE cat_id='".$cid."' AND topic_id='".$tid."'";
$res2 = mysql_query($sql2) or die(mysql_error());
while ($row2 = mysql_fetch_assoc($res2)) {
echo "<tr><td width='200' valign='top'>by ".$row2['post_creator']." <hr /> Posted on:<br />".$row2['post_date']."<hr /></td><td valign='top'>".$row2['post_content']."</td></tr>";
}
$old_views = $row['topic_views'];
$new_views = $old_views + 1;
$sql3 = "UPDATE topics SET topic_views='".$new_views."' WHERE cat_id='".$cid."' AND id='".$tid."' LIMIT 1";
$res3 = mysql_query($sql3) or die(mysql_error());
echo "</tbody></table>";
}
} else {
echo "<p>This topic does not exist.</p>";
}
?>
Thanks guys!
Looks like a classic (n+1) query mistake that could die a latent death. You get a key using one round trip, then you loop over the results to get n values based on it. If the first result set is large you'll have a lot of network round trips.
You could bring it all back in one go with a JOIN and save yourself a lot of network latency.
The statements themselves are fairly simple so there's not much you can do to optimize them further that I know of. However, if you create some business objects and cache the data into them on a single call and then access data from the business objects then it could be faster.
In other words, 1 SQL call for 1,000 rows is going to be much faster than 1,000 calls for a single row.
Here are some of extra things I would do when I write a code like above:
Never use * in SELECT statement when you know the columns you are going to use.
Always use or die(mysql_error()) when executing the query.
Unset the result sets once the result sets has served its purpose.
Use mysql_real_escape_string() to escape the injections when using some substitutions in your queries.
i have a question in regards to displaying a visual bar comparing mysql values.
i have the following two scripts :
<?php
require_once("inc/common.inc.php");
session_start();
$SQL = "SELECT * FROM db WHERE id = $user[id] LIMIT 1";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['actual value'] . "<BR>";
}
?>
and
<?php
require_once("inc/common.inc.php");
session_start();
$SQL = "SELECT * FROM db WHERE id = $user[id] LIMIT 1";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['max value'] . "<BR>";
}
?>
these two queries show me the actual value and the max value of my user's health.
as of now im printing both values next to each other like 95/100.
i would like to display the above in form of a progress bar according to max and actual.
Any ideas or sugestions would be greatly appreciated.
Thank you.
the below answer doesnt seem to work.
For e.g.
<?php
$percent = intval($actual_value*100/$max_value);
?>
<div style="width: 200px; background-color: green;">
<span style="width: <?php echo $percent;?>%; background-color: red;"></span>
</div>
$max_value should be greater than zero of course :)
you could go with a JS progress bar. Assign one value to each progress bar, animate and this should do the trick