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?
Related
i want that against each numbers, its call_count and duration are saved in single array.. this is my table:
Number Call_count duration
03455919448 4 14
03215350700 2 35
i want somethng like this:
foreach($number as $number1)
{
$data=array($row['call_count']<3,$row['duration']<20,1)
}
basically i want against each number its count and duration are checked for some values and if they meet the condition, display output 1... actually i can do it with simple if-else but as i have to train my dataset for neural network implementaion so all rows must be in one array? can anyone please help me out?
Maybe I don't understand quite well your code, but:
foreach($number as $number1)
$number1 is never used in your foreach :
$data=array($row['call_count']<3,$row['duration']<20,1)
So I guess $number1 is $row.
Second, it would help me if you provide the SQL Statement you are using now.
You could do a query like:
select Number, if(Call_count<3, if(duration<20, 1, 0), 0) as checked from tablename;
This gives you only the number, and 1 if both conditions are met, and 0 otherwise.
After that, in php do a loop (presented in plain mysql* funcions)
$data = array();
while ($row = mysql_fetch_assoc($result)) { // row will be an array with Number and checked as items
$data[] = $row;
}
// at this point you will have all rows in one array, with number and corresponding 1/0 in each item
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?
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()) {
Problem with writing an if-else statement for a sports website. The key is to display $game as W, L, or Tie depending on the scores which are parsed from a MySQL table from a variable called $row["result"]. The type of the column in table is VARCHAR and format the data saved in is $row["result"] = "A:B" where A is the home team's score and B is the opponents score. I am running into a problem where I write the if statement I can only echo Wins (W) and Ties (Tie) correctly!
For example the code:
<?php
$wl = $row["result"];
if ($wl[1] > $wl[3]) {
$game = "W";
}
if ($wl[1] < $wl[3]) {
$game = "L";
}
if ($wl[1] == $wl[3]) {
$game = "Tie";
}
?>
$game will output correctly when $wl= A>B and A==B but not A<B. I have a feeling this has something to do with PHP interpreting the data from $wl as not numbers, but some other format...
Try using "else if" instead of "if" on the last two "if" conditions. Also are you explode()'ing the result?
$wl = explode(':', $row['result']);
$wl[0] = Score for team A
$wl[1] = Score for team B
I'd also recommend using explode(), but for what you're using I think you should be referencing $wl[0] and $wl[2], since the array $wl starts at zero index.
Or here, if you want it in a cryptic way
$wl = explode(":",$row["result"]);
$game = ($wl[0]>$wl[1])?"W":(($wl[0]<$wl[1])?"L":"TIE");
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.