Ok, so I'm given a list of parts like so:
PartID CatID PartName
0 1 Part 1
1 2 Part 2
2 1 Part 3
3 3 Part 4
4 2 Part 5
5 2 Part 6
I'm using PHP to pull. How can I inject a blurb of text at each change in CatID, without having to run multiple loops?
So on page, I can display it like:
"BLURB OF TEXT"
Part 1
Part 3
"BLURB OF TEXT"
Part 2
Part 5
Part 6
"BLURB OF TEXT"
Part 4
Here's the code so far. I thought about putting in an assignment to = $row["CatID"], and checking to see if the variable == CatID, but it was always ==...
while($row = sqlsrv_fetch_array($qry, SQLSRV_FETCH_ASSOC)) {
echo $row["PartName"]
}
Put the ID in a variable that is outside the loop. That way you can check the previous ID and the current one. If the current one is not the same as the last one, echo some text:
$LastID = 0;
while($row = sqlsrv_fetch_array($qry, SQLSRV_FETCH_ASSOC)) {
echo $row["PartName"];
if($row["CatID"] > $LastID)
{
// ID changed!
echo "Insert Text!";
}
$LastID = $row["CatID"];
}
This, ofcourse, is assuming that the data is sorted ascending on CatID as your result that you want is showing.
I had my logic backwards.... grr, figures I get it figured out right after I ask for help...
if($cCat == $row["catID"]){
//echo 'nothing here';
}else{
echo '<a name="' . $row["PartCategory"] . '"></a>';
echo $this->GetPartCategories();
$cCat = $row["catID"];
}
is what works, , and above the while statement is a $cCat = '';
I was trying
if(!$cCat == $row["catID"]){
echo '<a name="' . $row["PartCategory"] . '"></a>';
echo $this->GetPartCategories();
$cCat = $row["catID"];
}
which for some reason did not work.
p.s. Already have an order by in my query. It orders by the catID, partSortOrder, then partName
Related
I got a problem that driving me crazy for last 4 or 5 days.I'm building a facebook style posting system,where users can post on their timeline and friends of that user can comment on every specific post.I'm actually having problem to print that correctly in php.Your help would be greatly appreciated.Thanks a lot in advance for your time.
The 'status' table that I created for all the post contain following values
id osid author type data postdate
1 1 helal a Hi... 2014-08-20
2 1 Abdul b Hey.. 2014-08-20
3 1 helal b Good.. "
4 4 helal a Hello.. "
5 4 Irin b Hi... "
so,basically,all new posts are having type 'a' and all replies are having type 'b'.And also,all separate conversation(post and replies) is having same 'osid',so that user can see separate conversation on separate div with a comment box attached to each post(followed by conversation)
I coded the following code,but it's not giving me expected result.
$sql="SELECT * FROM status WHERE type='a'";
$query=mysqli_query($connect_dude,$sql);
$numrow=mysqli_num_rows($query);
if($numrow>0){
while($row=mysqli_fetch_assoc($query)){
$id=$row["id"];
$osid=$row["osid"];
$name=$row["author"];
$data=$row["data"];
$date=$row["postdate"];
$query_replies = mysqli_query($connect_dude, "SELECT * FROM status WHERE type='b' AND osid='$id' ");
$replynumrows = mysqli_num_rows($query_replies);
if($replynumrows > 0){
while ($row2 = mysqli_fetch_assoc($query_replies) ) {
$statusreplyid = $row2["id"];
$statusreplyosid = $row2["osid"];
$replyauthor = $row2["author"];
$replydata = $row2["data"];
$replydata = nl2br($replydata);
$replypostdate = $row2["postdate"];
$replydata = str_replace("&","&",$replydata);
$replydata = stripslashes($replydata);
$status_replies .= '<div id="reply_'.$statusreplyid.'" class="reply_boxes"><div><b>Reply by '.$replyauthor.' '.$replypostdate.':</b><br />'.$replydata.'</div></div>';
}
}
$statuslist .= '<div id="status_'.$id.'" class="status_boxes"><div><b>Posted by '.$name.' '.$date.':</b> '.$statusDeleteButton.' <br />'.$data.'</div>'.$status_replies.'</div>';
if($logged == $username){
$statuslist .= '<form id="posting1" action="user.php?u='.$logged.'" method="post" enctype="multipart/form-data"><textarea id="replytext" name="replytext" class="replytext" placeholder="write a comment here '.$osid.'"></textarea><input id="hel1" name="hel1" type="hidden" value="'.$osid.'"><input type="submit" id="replyBtn" name="replyBtn" value="reply"></form>';
}
}
$postbox="<form id='posting' action='user.php?u=$logged' method='post' enctype='multipart/form-data'><input id='hid' name='hid' type='hidden' value='<?php echo $iid;?>' ><textarea id='taxi' name='taxi' rows='15' cols='40' placeholder='Say something to your Buddies'></textarea></br><input id='hel' name='hel' type='submit' value='post'></form>";
}
}
and I have used echoed '$statuslist' on html part.
It keeps compounding all replies within all the post.
Desired form of result,let say
For post no 1
helal:Hi...
Abdul:hello...
helal:Good....
"then the comment box(reply text area)"
For post no 2
helal:Hello...
Irin:Hi...
"then the comment box(reply text area)"
so on and so forth within separate divs for separate conversation
I'd say you need to reset $status_replies in the outer loop. Add:
$status_replies = '';
anywhere between the two while lines.
I'm getting three multiple errors when trying to validate my code.
echo '<section id="featured">';
$recipes = mysql_query("
SELECT `id`,`name`, `image`, `description`
FROM `recipe`
ORDER BY RAND() LIMIT 4;
");
while ($recipe = mysql_fetch_assoc($recipes)) {
echo '<section id="recipeslide">';
$recipe_id = $recipe['id'];
echo "<a href='php/recipe.php?id=$recipe_id'><img src=\"{$recipe['image']}\" height=100 width=100 /></a><br />";
echo '</section>';
}
echo '</section>';
This is the only place that I use the id of recipeslide but I think the validator is getting confused somehow and was wondering how I can fix this or do I ignore it?
It points out two other Id's that supposedly are duplicated.
It is also complaining about alt tags but I don't see that they would be effective in this situation.
IDs must be unique. You are using the same ID in a loop. You could do something like:
$count = 1;
while ($recipe = mysql_fetch_assoc($recipes)) {
echo '<section id="recipeslide' . $count++ . '">';
As for the alt attribute for <img>, it's pretty much required even if it's empty.
You are giving an id in a loop
So you get an extra ID each time round the loop
if you have 3 recipes then the while loop runs 3 times with each insertion adding another
<section id="recipeslide">
The answer is to not set a static id on an element inside of a loop, you need to either use a unique id for each run through the loop or if it is just for styling, set a class rather than an id
$sql=mysql_query("SELECT * FROM feedback.subject WHERE branch='cse'");
$row = mysql_fetch_assoc($sql) or die("error : $sql" .mysql_error());
$data =array();
$n=mysql_num_rows($sql);
while($row = mysql_fetch_array($sql))
{
$query_result_array[]=$row;
}
for($i=0;$i<$n;$i++)
{
$subid=$query_result_array[$i]['subid'];
$bt =$query_result_array[$i]['batch'];
$y =$query_result_array[$i]['year'];
$s = $query_result_array[$i]['semister'];
$subname=$query_result_array[$i]['subname'];
$tid = $query_result_array[$i]['tid'];
$sql2=mysql_query("SELECT * FROM teacher WHERE teacher.tid='$tid'");
$row2 =mysql_fetch_array($sql2);
$tname= $row2['tname'];
echo "<table id='table'>";
echo "<tr>";
echo "<td>".$bt."</td>";
echo "<td>CSE</td>";
echo "<td>".$y."</td>";
echo "<td>".$s."</td>";
echo "<td style='width:150px'>".$subname."</td>";
echo "<td style='width:150px'>".$row2['tname']."</td>";
echo '<form methode="get">
<input type="hidden" name="report">
<input type="submit" value="report">
</form>';
echo "</tr>";
echo "</table>";
}
function handler($x,$y){
session_regenerate_id();
$_SESSION['SUBID']=$x;
$_SESSION['TID']=$y;
echo 'report';
}
if(isset($_GET["report'$i'"]))
{
handler($query_result_array[$i]['subid'], $query_result_array[$i]['tid']);
unset ($_GET["report"]);
}
}
this results a table like
BATCH | BRANCH | YEAR | SEMISTER | SUBJECT NAME | TEACHER NAME | ACTION |
-------------------------------------------------------------------------------
9 CSE 4 1 DBMS ABC REPORT
9 CSE 4 1 WT XYZ REPORT
-------------------------------------------------------------------------------
when i click the report of a row suppose ('ABC' teacher) i want to carry the details ('ABC' and 'DBMS') to further process. but it always carrying the details of last person in the loop(here 'XYZ' and 'WT'). how to get that? is there any alternate process through i can call the handler function for a particular row which carries that particular row details.
just loop through query result array and inside of it place an if which detects when name is what you are looking for, at that moment, fetch current $query_result_array[$i] into a var that you want to carry the data further and break the loop.
If you are fetching by position in the table, you do not even need loop you just go $specific_person_data = $query_result_array[$i]...
So this now contains all of data about the person at position $i in your data table.
Update for links:
Each persons data can be passed to another page through link like this:
linkadress.php*?var1=X&var2=Y&var3=Z...*
and fetched on the other end with $_POST['var1'], $_POST['var2'] etc.
make sure not to echo or return data directly, but on every post var use strip_tags for security precaution.
Also here is article of mine on the subject of sensitive data handling and soem basic security:
http://metaphorical-lab.com/blog/?p=443
$sql = "SELECT messages.text, users.name FROM messages INNER JOIN users ON messages.user_id=users.id ORDER BY messages.ms_id DESC LIMIT 10";
$result = mysql_query($sql);
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[]=$row;
}
echo $rows[0][1].$rows[0][0];
/* for($i=0;$i<=10;$i++)
{
echo $rows[i][1].$rows[i][0];
}
*/
This script is supposed to show the last 10 messages in a chat.What I'm doing is getting the Name of the user from the users table and the text from the message table and I want to display them in my chat window.Right now I have only 4 messages recorded and don't know how this affects the whole script I should implement a check for this too, but the bigger problem is that when i use echo $rows[0][1].$rows[0][0]; the info is displayed correctly, but when I try to make a loop so I can show tha last 10 (I tried the commented one) then nothing is displayed.I thought at least when I use this loop I'll see the 4 recorded messages but what really happen is a blank window.Obvously I have the info recorded in $rows[] and can echo it, but don't understand why this loop don't work at all.I'll appreciate if someone can help me with this and with the check if the messages are less then 10.
Thanks.
Leron
P.S
Here is the edited script, thanks to all of you, I need the array because otherwise the most recent message is shown at the top which is not an opiton when I use it for diplaying chat masseges.
for($i=10;$i>=0;$i--)
{
if($rows[$i][1]!="" || $rows[$i][0]!="")
{
echo $rows[$i][1].' : '.$rows[$i][0];
echo "</br>";
}
}
Your FOR loop was running 11 times even if only 10 records. The second clause should be a < instead of <=. Plus the $ was missing on the i variable.
For example sake, you don't really need to make an array from the rows, and you can refer to the fields by name:
while($row = mysql_fetch_array($result))
{
echo $row['name'] . ' says: ' . $row['message'] . '<BR>';
}
why not just do
while($row = mysql_fetch_array($result))
{
echo $row[1]." ".$row[0];
}
Your query, auto limits it to the last 10, this will then show anything from 0 to 10 which get returned.
PS I added a space between username and message for readability
You need $ symbols on your i variable:
for($i=0;$i<10;$i++)
{
echo $rows[$i][1].$rows[$i][0];
}
A more robust solution would be like this:
$sql = "SELECT messages.text, users.name FROM messages INNER JOIN users ON messages.user_id=users.id ORDER BY messages.ms_id DESC LIMIT 10";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row[1].$row[0];
}
First off, sorry if the title is confusing! I'm working on a part of a blog that determines how lists of recent posts (sometimes determined by a date) in a category are to be displayed. In the database, each category has a "type" set that determines whether the div it goes in is small or large.
I can get the results to display but each link in the list has its own div, instead of being contained in one "main" category div.
Shorter explanation:
The database pulls results from the categories table and the posts table, as you can see in the query. The loop then runs so that the category boxes and the links in them can be created dynamically.
The problem is that the divs, which are supposed to house a list of links, are instead wrapping around each individual link and not the set that is desired.
While the code below shows only two "types", I had planned on adding more in the future.
Here is the code
<?
require("classes/Database.class.php");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$time = $_REQUEST['time'];
$db->connect();
$sql = "SELECT
cm.id,
cm.title AS cmtitle,
cm.sectionid,
cm.type AS cmtype,
cd.id,
cd.time,
cd.link,
cd.title,
cd.description,
cd.sectionid AS sectionid
FROM c_main AS cm
JOIN c_data AS cd ON cd.sectionid=cm.sectionid
WHERE cd.sectionid=cm.sectionid AND time = '".$time."' ORDER by id ASC";
$rows = $db->query($sql);
while($record = $db->fetch_array($rows)){
//determine what div to use by checking "type"
if ($record['cmtype'] == 'large') {
?>
<div class="large" >
<?
} elseif ($record['cmtype'] == 'small') {
?>
<div class="small">
<?
}
for($x =0; $x <= $db->affected_rows; ++$x)
{
if ($record['cmtype'] == 'small') {
echo $record['title'].'<br/>';
} else {
echo $record['title'].'<br/>'.$record['description'];
}
break;
}
echo '</div>';
}
$db->close();
?>
Basically I am trying to have it like this:
/-------------------\
| Category Title |
| -relevant link |
| -relevant link |
\____________________/
/-------------------\
| Category Title |
| -relevant link |
| -relevant link |
\____________________/
.... and so on for each subsequent category
And not this (which is how it's being outputted)
/-------------\
\relevant link/
-------------
/-------------\
\relevant link/
-------------
etc.
Here is the mysql wrapper I'm currently using, if that's of any significance http://ricocheting.com/scripts/php_mysql_wrapper.php
If you only want 2 divs, one large and one small, you should do ORDER BY cmtype, and then you will only need to create a div when the type changes or it is the first type.
your code will echo a div for every row, that is your problem/question.
my suggestion is to create two queries: one selecting all links of type A and the second query selecting all links of type B (WHERE type = '…')
then you'll have to print the starting tag of your first div:
echo '<div class="large">';
after that, loop your result and output your links:
while(($record = $db->fetch_assoc($rows)) !== FALSE){
echo htmlspecialchars($record['title']),'<br/>';
}
close your div:
echo '</div>';
now you can start your second category, same game, same rules:
open div
loop results
close div
~~~
another way like others said to order your result by type, then by id (ORDER BY type, id) and then check for a change in the row’s type:
$currenttype = '';
while(($record = $db->fetch_assoc($rows)) !== FALSE) {
$currenttype = $record['cmtype'];
echo '<div class="',htmlspecialchars($record['cmtype']),'">';
while($record['cmtype'] == $currenttype
&& ($record = $db->fetch_assoc($rows)) !== FALSE) {
// output link according to your type:
echo htmlspecialchars($record['title']);
}
echo '</div>';
}
i assume this is what you wanted to achieve in the first place
Maybe I get this completely wrong, but if you want to display the elements grouped by their type I think you should order them by type straight away, so that order of elements is correct when you start outputting HTML code?
If you are certain about your table contents you can use:
echo "<div class='" . $record['cmtype'] . "'>";
Maybe i am wrong in understanding your question, but you try to add all relevant link in a single DIV, then check your php result html (browser->view source)