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?
Related
i m dealing with 2 tables.I just want to know whether there is something code that helps me fetching rows for multiple times without writing same query for that many times:
Example:
while($row1=mysqli_fetch_array($result1)) {
while($row2=mysqli_fetch_array($result2)){
//checking for some condition
}
}
In above code unlike array we cant reset a variable outside the inner loop as follows
while($row1=mysqli_fetch_array($result1)) {
$number=0;//so that v can start from first row
while($row2=mysqli_fetch_array($result2)){
//checking for some condition
}
}
I m totally aware that rows and array are different,So i m asking if there is FOR loop we can use on rows?? like:
while($row1=mysqli_fetch_array($result1)) {
for(...){
//so dat it will xecute no.of whileloops*no.of for loops.
}
}
if not clear ask for more.
Your suggestions are much obliged.
Edit:
table: Year
1999
2000
2002
2004
2000
$result=mysqli_query($con,"select distinct Year from table_name");
dataset=mysqli_fetch_array($result)..
If I got it right, you want to match all the results of the first query against all the results of the second query.
In that case, you should first gather all the results of both queries in two PHP arrays (of arrays) and then work with these variables, like so:
$list1=array();
while ($row=mysqli_fetch_array($result1)) $list1[] = $row;
$list2=array();
while ($row=mysqli_fetch_array($result2)) $list2[] = $row;
foreach ($list1 as $row1)
foreach ($list2 as $row2)
{
match_against ($row1, $row2);
}
Note that it looks very much like an SQL JOIN done in PHP.
Why not, as long as the number of results stay within reasonable bounds.
But if it's not the case (i.e. $list1 or $list2 could contain hundreds of elements), be aware that your code will very likely be a lot less efficient than what a DB engine can do.
That's why you might want to consider replacing this code with an SQL query.
Try this (if i understood ):
while( list($row1,$row2) = array(mysqli_fetch_array($result1),mysqli_fetch_array($result2)) ){
// check condition
}
$dataSet1 = mysqli_fetch_all($result1);
$dataSet2 = mysqli_fetch_all($result2);
foreach($dataSet1 AS $row1){
foreach($dataSet2 AS $row2){
}
}
Something like this might work?
I am making a pricing table to upgrade membership.
In mySQL I have a table with limits on what each membership can allow see picture
I grab the info from the table and try to iterate through it and append some text to it from another array. I have tried thoroughly looking online for an answer but I'm probably not even searching for the right terms. For the purpose of this question i'm using 2 fields but in reality i will be iterating and appending many columns.
Here's my code:
$sql = "SELECT maxProducts,maxImages FROM memproducts_membership_settings WHERE useThis='1'";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs,MYSQL_ASSOC))
{
foreach($row as $field)
{
$append = array('Product Slots','Images per product');
print $field.' '.$append.'<br>';
}
}
All i get is:
5 Array
2 Array
and not what i need which would be:
5 Product Slots
2 Images per product
I'm sure there is a way to do this but i just cannot figure it out, please anyone give me some pointers? Many regards :)
This is pretty basic stuff...
while($row = mysql_fetch_array($rs,MYSQL_ASSOC))
{
echo $row['maxProducts'] . ' Product Slots<br>';
echo $row['maxImages'] . ' Images per product<br>';
}
Or if you are needing to do this with dynamic fields in whatever order you return from database like your question suggests, perhaps you might consider providing a mapping of database column names to the appropriate label content like this:
$labels = array(
'maxProducts' => 'Product Slots',
'maxImages' => 'Images per product',
...
);
...
while($row = mysql_fetch_array($rs,MYSQL_ASSOC)) {
foreach ($row as $key => $value) {
echo $value . ' ' . $labels[$key] . '<br>';
}
}
Note if you are just learning PHP, you REALLY should NOT learn mysql_* functions. They are deprecated and need to die. Please learn to use PDO or mysqli.
To append values to the end of an array use array_push()
http://php.net/manual/en/function.array-push.php
There's plenty about your code and your approach that I don't like at all, but the most immediate solution to your current problem would be to iterate the array of strings from within the foreach loop, using each():
$strings = array('Product Slots','Images per product');
while($row = mysql_fetch_array($rs,MYSQL_ASSOC))
{
reset($strings);
foreach($row as $field)
{
$append = each($strings);
print $field.' '.$append[1].'<br>';
}
}
You should at very least make yourself aware of:
the deprecation of ext/mysql (use either mysqli or PDO); and
the risk of XSS attacks (escape any HTML in values from your database before returning them to the browser).
It's doing what it should... You have created an array and asked it to print its name. As print can't automatically iterate an array it just tells you what the variable type is.
well, i wanna pull out some data from a mysql view, but the wuery dos not seem to retrieve anything ( even though the view has data in it).
here is the code i've been "playing" with ( i'm using adodb for php)
$get_teachers=$db->Execute("select * from lecturer ");
//$array=array();
//fill array with teacher for each lesson
for($j=0;$j<$get_teachers->fetchrow();++$j){
/*$row2 = $get_lessons->fetchrow();
$row3=$row2[0];
$teach=array(array());
//array_push($teach, $row3);
$teach[$j]=mysql_fetch_array( $get_teachers, TYPE );
//echo $row3;*/
$row = $get_teachers->fetchrow();
//$name=$row[0]+" "+$row[0]+"/n";
//array_push($teach, $row1);
echo $row[0]; echo " ";echo $row[1]." ";
//$db->debug = true;
}
if i try something like "select name,surname from users", the query partially works . By partially i mean , while there are 2 users in the database, the loop only prints the last user.
the original query i wanted to execute was this
$get_teachers=$db->Execute("select surname,name from users,assigned_to,lessons
where users.UID=assigned_to.UID and lessons.LID=assigned_to.LID and
lessons.term='".$_GET['term']."'");
but because it didnt seem to do anything i tried with a view ( when you execute this in the phpmyadmin it works fine(by replacing the GET part with a number from 1 to 7 )
the tables in case you wonder are: users,assigned_to and lessons. ( assigned_to is a table connecting each user to a lesson he teaches by containing UID=userid and LID=lessonid ). What i wanted to do here is get the name+surname of the users who teach a lesson. Imagine a list tha displays each lesson+who teaches it based on the term that lesson is available.
Looking at http://adodb.sourceforge.net/ I can see an example on the first page on how to use the library:
$rs = $DB->Execute("select * from table where key=123");
while ($array = $rs->FetchRow()) {
print_r($array);
}
So, you should use:
while ($row = $get_teachers->fetchrow()) {
instead of:
for ($j = 0; $j < $get_teachers->fetchrow(); ++$j) {
The idea with FetchRow() is that it returns the next row in the sequence. It does not return the number of the last row, so you shouldn't use it as a condition in a for loop. You should call it every time you need the next row in the sequence, and, when there are no more rows, it will return false.
Also, take a look at the documentation for FetchRow().
for($j=0;$j<$get_teachers->fetchrow();++$j){
... a few lines later ...
$row = $get_teachers->fetchrow();
See how you call fetchrow() twice before actually printing anything? You remove two rows from the result set for every 1 you actually use.
while ($row = $get_teachers->fetchrow()) {
instead and don't call fetchrow() again within the loop.
Because you're fetching twice first in the loop
for($j=0;$j<$get_teachers->fetchrow();++$j){
... some code ...
// And here you fetch again
$row = $get_teachers->fetchrow();
You should use it like this
while ($row = $get_teachers->fetchrow()) {
I have a SQL database that contains a field. I can get all of the elements in that field by:
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
$ftype =$row['ftype']; //name of field is 'ftype'
print $ftype} //do something
I want a random element to be printed out each time the page is opened/refreshed.
Knowing that the result is an array containing the information i want, I want to randomly choose an element of the array. Also, if there are N elements in the array, I want to choose all N elements exactly once before I show any element again for second time. The process repeats itself. I know how to code something like this in java or python, but I don't think that's the way I should go.
I think I need to use javascript, but I'm just not sure what technology to use.
UPDATE:
Patrick's idea seems to be exactly what i was looking for. I thought I would share what I have now and maybe you can suggest optimization. I hope the intent in the code is obvious.
<?
session_start();
if (!isset($_SESSION['count']) || !isset($_SESSION['randomArray'])) {
$count = 0;
$randomArray = array();
$sql="SELECT youtubeurl FROM Foodlist";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
array_push($randomArray,$row['youtubeurl']);
}
shuffle($randomArray);
$_SESSION['randomArray'] = $randomArray;
$_SESSION['count'] = $count;
} elseif ($_SESSION['count'] >= sizeof($_SESSION['randomArray'])){
$_SESSION['count'] = 0;
$randomArray = $_SESSION['randomArray'];
shuffle($randomArray);
$_SESSION['randomArray'] = $randomArray;
} else{
$randomArray = $_SESSION['randomArray'];
$count = $_SESSION['count'];
echo $randomArray[$count];
$_SESSION['count']++;
}
?>
You can do this without Javascript, however you'll need to open/maintain a session.
Pseudocode:
data = data_from_mysql()
choice = random.choice(data, exclude = SESSION['choices'])
SESSION['choices'].append(choice)
print choice
if len(SESSION['choices']) == len(data):
SESSION['choices'] = []
If you want a random result let the dbms take care of it. Add this to the bottom of your sql query.
ORDER BY RAND()
LIMIT 1
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.