mysql_fetch_array and while loop lost first result - php

I have problem with mysql_fetch_array() and while loop. I have the query:
$tagsquery = mysql_query("SELECT `url` FROM `tags`, `mapa-tagow`, `statusy` WHERE `tags`.`id` = `mapa-tagow`.`tag-id` AND `statusy`.`id` = `mapa-tagow`.`article-id` AND `tags`.`tag` ='$tag' ORDER BY `url` ASC ") or die("ERROR: Tags doesn't exist.");
And results in while loop:
while($tags = mysql_fetch_array($tagsquery)) {
echo "<a href='tags.php?url=$url'>$url</a>, ";
}
When testing this query in PHPMyAdmin I have one more result than I get in PHP. I dont know why PHP always missing first result.

A few possibilities:
You're looking at a different copy of the same database
You've already started fetching your result set earlier than your while loop
On a side note, you should build an array of your tag links, and then output them using implode... while(){ $tag_links[] = '<a href...';} print implode(', ', $tag_links);

You need to change your code to:
while($tags = mysql_fetch_array($tagsquery)) {
echo ''.$tags['url'].', ';
}
Note that i took the opportunity to correct your tag output, there are many other ways to output HTML but this is easier to read in most cases.
If you can't spot the problem, i changed your $url to $tags['url'], so i output the URL from the $tags that you got from mysql_fetch_array()
Cheers

Related

PHP link only passing part of a mysql result

OK i have a php link which is made up of several variables
<a href=\year.php? manufacturer='.$manufacturer.'&fuel_type='.$fuel_type.'&model_type='.$model_type.'>'.$model_type.'</a>
The whole code is really long as it has a lot of pagination, so i will just include the basic query and the loop part.
$query1 = "SELECT Distinct model_type from $tableName where manufacturer='$manufacturer' AND fuel='$fuel_type' LIMIT $start, $limit";
$result = mysql_query($query1);
And then the bottom part where i get and show the results.
$count = 0;
$max = 2;
while($row = mysql_fetch_array($result))
{
$model_type = $row['model_type'];
$count++;
echo '<td class="manu"><div align="center">'.'<a href=\year.php? manufacturer='.$manufacturer.'&fuel_type='.$fuel_type.'&model_type='.$model_type.'>'.$model_type.'</a>'.'</div></td>';
if($count >= $max){
//reset counter
$count = 0;
//end and restart
echo '</tr><tr>';
}
}
now this works fine except when i take the mode type variable from the database it shows as 1 series, however when it is passed in this link it only gets the 1 and doesn't pick up the series.
Thanks
try to pass it like:
'.urlencode($model_type).'
Try To access it on next page with urldecode($_REQUEST['$model_type'])
I am not shure but you probably have a missing encoding Problem.
try this:
'.$model_type.'
Its url_encoding the values so your url doesnt get broken by ',",spaces and so on.
additional Hint:
Enclose your URL with " or ' so you do not get problems at the end.

External looping of the variable

How could I best loop the data through a variable that's nested inside a 'while' loop but it's called outside of it ? Like in this example:
PHP:
$fr_q2 = mysqli_query($connect,"SELECT * FROM friends WHERE username ='".$_SESSION['user']."'
ORDER BY id DESC");
while ($rowsPicFr2 = mysqli_fetch_array($fr_q2)) {
$friends_q2[] = $rowsPicFr2['added_friend'];
$frn[] = $rowsPicFr2['added_friend'];
$frn2 = $rowsPicFr2['added_friend'];
}
$rowscheck = mysqli_num_rows($fr_q2);
for ($i=0; $i<$rowscheck; $i++)
HTML:
YES
So I need to pass $frn[$i] into a remdata() function - but the $frn[$i] needs to loop....All I get is a string of all ids from 'friend_added' in $frn[$i]....Thanks.
Once this HTML is sent to the browser, it won't loop anymore. It will just be HTML. So what you need to do, is either have it loop in JavaScript or simply echo each remdata():
YES
This solution is only really an option if you have very few elements in $frn.
Your question is confusing; I think you need the loop for the HTML output
<?php foreach ($frn as $i => $friend_id){ ?>
YES
<?php } ?>
Based on your comment in toon81's answer, it seems like you're having a problem dealing with several loops in your output that deal with the same result set in your database query. I'm not sure. I'd suggest in the future that you try to make your question easier to follow. For instance, do we need to know it's a social networking app? Your variable names aren't inherently easy to understand; what's the difference between $frn and $frn2? Presumably that's 'friend', but I keep reading it as 'fern'. You also only provided one line of your output, but your problem seems related to it's interaction with other output. Your code is cut off -- the rowscheck loop doesn't have a definition.
That said, this is a high level suggestion of how I'd handle your work differently. Data preparation:
$connection = ...;
$user = $_SESSION['user'];
$sql = "
SELECT added_friend
FROM friends
WHERE username = '$user'
ORDER BY id DESC
";
$response = mysql_query($sql, $connection);
$added_friends = array();
while ($row = mysql_fetch_object($response)){
$added_friends[] = $row->added_friend;
}
Ouput handling:
// With one loop if the markup can be ouput all at once.
foreach ($added_friends as $friend){
// Your 'friends_q2', whatever that is.
echo "Friends_q2: $friend";
// Your 'frn2' output, whatever that is.
echo "Frn2: $friend";
// Your 'frn' output.
echo "YES";
}
// ...or multiple loops if it can't.
foreach ($added_friends as $friend){
// Your 'friends_q2', whatever that is.
echo "Friends_q2: $friend";
}
foreach ($added_friends as $friend){
// Your 'frn2' output, whatever that is.
echo "Frn2: $friend";
}
foreach ($added_friends as $friend){
// Your 'frn' output.
echo "YES";
}
In any case, you're handling the same ID three times in different lists and in different ways. I'm not at all sure why. Is this what you're asking for help with?

How do you count and format user tags

I have user entered tags that go under the table field tags.
$sql="SELECT tags from table";
$stmt16 = $conn->prepare($sql);
$result=$stmt16->execute();
while($row = $stmt16->fetch(PDO::FETCH_ASSOC)){
echo $tags=$row['tags'];
}
This produces
cool,yes,okcool,yes,ok
because there are 2 entries with the same 3 tags under that field. I want to be able to count how many duplicates there are of each tag such that the result should be cool(2) yes(2) ok(2). Anyone know the proper way to approach this? Should I fetch the results as an array or explode them?
With your current data structure, the answer I'd give is yes: as you said, explode them, and put them into an array.
$tags = array();
while($row = $stmt16->fetch(PDO::FETCH_ASSOC)){
foreach(explode(',',$row['tags']) as $tag) {
if(isset($tags[$tag]) {$tags[$tag]++;} else {$tags[$tag]=1;}
}
}
//now you can see how many times each tag occurred...
foreach($tags as $tag=>$count) {
print "Tag {$tag} occurred {$count} times<br />";
}
However, if you can change the database structure, you'll find it a lot easier to manage your tags if you only have one per DB record. It will make it a lot easier to query them that way.
I would alter the statement to
SELECT COUNT(*) as cnt, tags
FROM table
GROUP BY tags
and there you are.
Edit:
Don't forget to alter your echo to echo $row['tags'] ."(". $row['count'] .")";
Simply with this query:
SELECT tag, COUNT(*)
FROM table
GROUP BY tag
HAVING COUNT(*) >1;

problem with MySQL queries in PHP

I have the following queries that work perfectly in MySql:
SELECT * FROM rapoarte WHERE nrtel LIKE '0256%' OR nrtel LIKE '0356%
SELECT * FROM rapoarte WHERE nrtel NOT LIKE '07%' AND nrtel NOT LIKE '0256%' AND nrtel NOT LIKE '0356%'
SELECT * FROM rapoarte WHERE nrtel LIKE '07%'
in PHP they will result the following:
results just for LIKE '0256%'
no results
inclomplete results. i have phone numbers that start with 076, 075 and it only shows the numbers that start with 076.
Anyone know why?
thanks,
Sebastian
EDIT
here is the code:
$select_int= mysql_query("SELECT * FROM rapoarte WHERE nrtel LIKE '0256%' OR nrtel LIKE '0356%'");
$local = mysql_fetch_array($select_int);
echo "<table align='center' border='0' width='600'><tr><td><b>Ziua</b></td><td><b>Ora</b></td><td><b>Trunchi</b></td><td><b>interior</b></td><td><b>Durata</b></td><td><b>Numar Format</b></td></tr>";
while($int = mysql_fetch_array($select_int)) {
echo "<tr>
<td>".$local['ziua']."</td>
<td>".$local['ora']."</td>
<td>".$local['linie']."</td>
<td>".$local['interior']."</td>
<td>".$local['durata2']."</td>
<td>".$local['nrtel']."</td></tr>";
}
echo "</table>";
Again...
Here $local = mysql_fetch_array($select_int); you discard your first line. You fetch it and you don't use it.
The second problem is here $int = mysql_fetch_array($select_int). You actually want $local = mysql_fetch_array($select_int) because that's what you use in the while block.
You seem to be discarding the first result on the 2nd line with
$int = mysql_fetch_array($select_int);
...not to mention the query in the code snippet you edited in doesn't actually match any of the three you claim work correctly.
You're not iterating over the results, rather, you're just getting the first one.
while(($local = mysql_fetch_array($select_int)) != null){
// $local contains 1 result row
}
The query you're using in your PHP script doesn't use "LIKE"

When listing information from a database using php and mysql how would you make the first row look different to the rest?

Basically I have articles in my database and I want to alter the way the first record displays. I want the lastest (Posted) article to be the focus and the older article just to list, (see F1.com). I need to know how to get the first of my values in the array and get it to display differently but I am not sure how to do this, I can do it so all rows display the same just not how to alter the first row. I also need to know how to tell the rest of the rows to display the same afterwards im guessing you use an if statement there and before that some kind of count for the rows.
Current code:
$result = mysql_query("SELECT * FROM dbArticle WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC");
while($row = mysql_fetch_array($result))
{
echo "<h2 class=\"heading1\">". $row['title'] ."</h2>";
echo "By: ".$row['username']." Type: ".$row['type']." Posted: ".$row['timestamp']."
$body = $row['body'];
echo "<br/><p>";
echo substr("$body",0,260);
echo "...<span class=\"tool\"><a class=\"blue\" href=\"index.php?pageContent=readArticle&id=".$row['id']."\">Read More</a></span></p><hr/>";
}
mysql_close($con);
Ok I have taken Luke Dennis's code and tried to test it, but I am getting this error: Warning: Invalid argument supplied for foreach() this is the line of the foreach statment. Something that has just come to mind is that I will only want 5 or so of the older articles to display. This is what I have thats creating the error:
<? $con = mysql_connect("localhost","****","***");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("******", $con);
$result = mysql_query("SELECT * FROM dbArticle ORDER BY timestamp DESC");
$first = true;
foreach($result as $row){
if($first)
{
echo"".$row['title']."";
echo"this is the headline";
$first = false;
}
else
{
echo"".$row['title']."";
}
}
?>
Do I need to add mysql_fetch_array somewhere to set the array up?
I would just iterate through the results and apply a css class to the first entry:
$first = true;
while ($row = mysql_fetch_assoc($result)) {
$cssClass = '';
if ($first) {
$cssClass = 'highlight';
}
echo '<p class="' . $cssClass . '">' . $row['text'] . '</p>';
$first = false;
}
It's a bit crude, but I often hard-code a variable to designate the first run through a loop. So something like:
$first = true;
foreach($list_of_items as $item)
{
if($first)
{
// Do some stuff
$first = false;
}
else
{
// Do some other stuff
}
}
A simple if statement when looping through your results will usually do the trick. You can use a boolean to indicate if you've output the first row of results or now. If you haven't then give it a particular style and then set the boolean to true. Then all subsequent rows get a different style.
All of the above are correct. Luke Dennis' post is of course fleshed-out a bit more.
As Brian Fisher said, add some CSS styling to the first link when you encounter it per Luke's post.
I took a look at the article list on the F1 website. Pretty well constructed site - "One would expect that." :-)
Anyway, the article listings are contained within a two row table (summary="Latest Headlines") in descending order (newest first).
Just place a class in the second column (<td class="first-news-article">). Then add the class name and appropriate styling values in the css file - probably your' modules.css. There's already quite a few class values associated with articles in that file, so you may be able to just use an existing value.
That should be about it - other than actually doing it!
By the way, judging by the quality of the underlying html, I'm assuming there's already an "article list emitter." Just find that emitter and place the appropriate conditional to test for the first record.
Darrell
I just noted your code addition. I assume that you were showing the F1 site as an example. Anyway, I think you're on your way.
I presume you have some code that loops through your resultset and prints them into the page? Could you paste this code in, and that might give us a starting point to help you.
I don't know PHP, so I'll pseudocode it in Perl. I wouldn't do it like this:
my $row_num = 0;
for my $row ($query->next) {
$row_num++;
if( $row_num == 1 ) {
...format the first row...
}
else {
...format everything else...
}
}
The if statement inside the loop unnecessarily clutters the loop logic. It's not a performance issue, it's a code readability and maintainability issue. That sort of thing just BEGS for a bug. Take advantage of the fact that it's the first thing in the array. It's two different things, do them in two different pieces of code.
my $first = $query->next;
...format $first...
for my $row ($query->next) {
...format the row...
}
Of course, you must make the first row stand out by using tags.
I'd use array_shift():
$result = mysql_fetch_assoc($resultFromSql); // <- edit
$first = array_shift($result);
echo '<h1>'.$first['title'].'</h1>';
foreach ($result as $row) {
echo '<h2>'.$row['title'].'</h2>';
}
The best way to do this is to put a fetch statement prior to the while loop.
Putting a test inside the while loop that is only true for one iteration can be a waste of time for a result of millions of rows.

Categories