How to display two while loop variables - php

I am trying to display multiple columns with multiple rows from a database. It works to display one row, but when I put in the second one it just displays two of the same. Like an echo. How do I get it to display the two different numbers?
$result = mysql_query("SELECT plea, COUNT(plea) as cee FROM tee WHERE section='d' GROUP BY
plea" , $c) or die("two");
$number=mysql_num_rows($result);
if($number>0)
{
$i=0;
while($row_result = mysql_fetch_array($result))
{
$plea.$i = $row_result['plea'];
$cee.$i = $row_result['cee'];
echo $plea.$i." ".$cee.$i."<br><br>";
$i++;
}
}

This is VERY strange code:
$plea.$i = $row_result['plea'];
and NOT doing what you want. It's parsed as:
$plea . ($i = $row_result['plea']);
and boils down to $i getting your value from the query, and then being further executed down to just
TRUE
without EVER modifying the value in $plea. You probably want an array:
$plea[$i] = $row_result['plea'];

Related

Sum mysql array in PHP

I need sum up quantity items. I have a database query, I print values:
while ($row = mysqli_fetch_array($lista)) {
echo $row['przedmiot'].":".$row['ilosc'].'<br>';
}
then I get this result:
item1:1
item1:3
item2:1
item1:3
item2:5
I need to add these values, I would like to get this result:
item1:7
item2:6
#Sascha's answer will work, but I'd suggest a different approach - instead of querying all these rows, transferring them from the database to your application and then having to loop over them in the code, let the database do the heavy lifting for you:
SELECT przedmiot, SUM(ilosc) AS ilosc
FROM mytable
GROUP BY przedmiot
This should help:
$result=[];
while ($row = mysqli_fetch_array($lista)) {
echo $row['przedmiot'].":".$row['ilosc'].'<br>';
if (!array_key_exists ($result, $row['przedmiot'])) {
$result[$row['przedmiot']] = $row['ilosc'];
} else {
$result[$row['przedmiot']] += $row['ilosc'];
}
}

PHP while loop to fetch post data from database

I am creating my own blog from scratch with a homepage that loads the latest posts in order of time published. I call the posts using a front controller and store the data on a MySQL database. The website itself is great and the posts all load perfectly with no issue. The issue is getting the homepage to work.
I created a few PHP functions for the homepage. They generally order the posts (database rows) by ID in descending order, since it's an autoincrement field, and call their data. And then to show the latest post as a sort of 'featured post' right at the top, by fetching the data from the very top row in the database, which is the latest post.
And that works fine - when I echo the result it shows the latest post just as I want it.
Below that I want two boxes, side by side, for the two posts before the first one. So I made this function to call them:
function fetch_rest_posts_1($conn) {
$stuff = $conn->query("SELECT * FROM table WHERE is_post = 1 ORDER BY id DESC LIMIT 1,2");
while ($row = $stuff->fetch_array()) {
$i=1;
return '<div id="post_'.$i.'" style="width:308px;height:215px;padding:5px">
<h2>'.$row['title'].'</h2>
<p>'.date('d/m/Y',strtotime($row['published_date'])).' by '.$row['author'].' | </p>
<p>'.$row['meta_description'].'</p>
</div>';
$i++;
} // style="white-space:nowrap;width:100%;overflow:hidden;text-overflow:ellipsis"
}
And it actually does work great when I echo the result, shows everything I want, but it only shows one div, not two. When I take the SQL query and directly enter it into phpMyAdmin, it gives me two rows. Have I done something wrong?
(I put the auto-increasing $i in there so that I could isolate each box and alter the style later.)
Your problem is caused by the return statement in the loop. You should add $return = '' at the top of your function, replace return by $result .=, and return $result at the end of your function.
In addition, the loop counter $i is reset in every iteration. Move the initial assignment out of the loop.
EDIT: The .= is intentional to append to $result instead of replacing it with another value constructed from the next dataset.
initiate $i outside the loop and use echo() instead of return()
return() breaks the loop
or use
$result .= '<div id="post_'.$i.'" style="width:308px;height:215px;padding:5px">
<h2>'.$row['title'].'</h2>
<p>'.date('d/m/Y',strtotime($row['published_date'])).' by '.$row['author'].' | </p>
<p>'.$row['meta_description'].'</p>
</div>';
and return $result; after the loop
That's because return will stop execution of the function try this approach:
function fetch_rest_posts_1($conn) {
$stuff = $conn->query("SELECT * FROM table WHERE is_post = 1 ORDER BY id DESC LIMIT 1,2");
$post = array();
while ($row = $stuff->fetch_array()) {
$post[] = $row;
}
return $post;
}
So the function purpose is to just get the data, so you can later print it:
$row = fetch_rest_posts_1($conn);
for($i = 0; count(row); $i++){
echo '<div id="post_'.$i.'" style="width:308px;height:215px;padding:5px">
<h2>'.$row[$i]['title'].'</h2>
<p>'.date('d/m/Y',strtotime($row['published_date'])).' by '.$row[$i]['author'].' | </p>
<p>'.$row[$i]['meta_description'].'</p>
</div>';
}

Running a statement based on information from POST variable

I'm in a bit of pickle but the answer is probably pretty simple.
So I have my POST variable:
Array ( [accept] => accept,29 [accept1] => accept,30 [submit] => Save Selections )
That's just a print_r of $_POST.
Basically what I want to do is get the first variable, remove the 'accept,' part and store the number next to it in a variable, run some MySQL queries using that variable (containing that number) then move onto the next one; removing the 'accept,' storing the number next to it and running a query using that stored number. It want to do this for as many times is necessary to go through all the elements containing 'accept,' then a number.
Any help would be appreciated.
I was playing around with some ideas and have this code. It obviously doesn't work but perhaps I could fix and build on it?
while($i <= $elements)
{
while($x == 1)
{
$id = explode(',', next($_POST));
echo $id;
$x = 0;
}
$i++;
}
Im not sure this would fix your problem but I hope this helps and gives you an idea:
$i = 0;
while($i <= count($your_array))
{
$your_var = substr($your_array[$i], 7, 2); //get the number from your accept,29
$query = "SELECT * FROM TABLE WHERE COLUMN = ". $your_var; //use it to run queries as you said
$i+=1;
}
UPDATE - Im not sure if this would work
foreach($your_post_array as $items)
{
$your_var = substr($items, 7, 2);
$query = "SELECT * FROM TABLE WHERE COLUMN = ". $your_var; //use it to run queries as you said
$i+=1;
}
Maybe you should try to echo first the variables to make sure echo $your_var = substr($items, 7, 2);
I would use a foreach loop to loop through $_POST, check if the key starts with accept (stripos?), explode the value if it does and get the second value of the found array and store that somewhere for later use.
By the way, if possible I would change the front-end so that you have just one variable (an array) in $_POST you have to loop through.

Mysql Queries Error Inside a While Loop

I have a while loop from a query called $result.
Inside this while loop I have two other queries $anchors1 and $anchors2
The first one retrieves the first 2 rows;
The second one should retrieve the following ones using an offset.
For some reason the queries seem to interact one another, not displaying the 3 row and pulling a duplicate row which should not be there.
Is there any way this queries would interfere?
If I delete the first one, the second query works. Same vice versa.
The platform is Wordpress.
while($slice = mysql_fetch_assoc($result)){
$i++;
if($enable_position1 == 'y' && $i == $position[0]):
$anchors1 = mysql_query("SELECT * FROM anchors WHERE site_url = '$site_current' LIMIT 3");
while($anc = mysql_fetch_assoc($anchors)){
$site_anchor = $anc['site_anchor'];
$site_current = $anc['site_current'];
echo '<li>'.$site_anchor.'</li>';
}
elseif($enable_position2 == 'y' && $i == $position[1]):
$anchors2 = mysql_query("SELECT * FROM anchors WHERE site_url = '$site_current' LIMIT 999 OFFSET 3");
while($anc2 = mysql_fetch_assoc($anchors2)){
$site_anchor2 = $anc2['site_anchor'];
$site_current2 = $anc2['site_current'];
echo '<li>'.$site_anchor2.'</li>';
}
else:
the_post();
endif;
}
Ty very much!
In the second query, you're using the variable $site_current, which is set in the first query's block. Depending on how your application is designed, that could be causing the interference. I think you meant to put $site_current2 there.

php query does not retrieve any data?

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()) {

Categories