Search the Community
Showing results for tags 'while loop'.
-
I've got a lot of questions today, it seems. I can't see where the problem is in this method, it seemed very simple when I started <?php public function recent() { $rule = "ORDER BY RAND()"; $field = "type"; $type = "recent"; $query = $this->_db->get(self::$_table, array($field, "=", $type), $rule); $this->_data = $query->all(); $counter = 0; while($counter <= 7) { foreach($this->data() as $obj) { if(strlen($obj->title) > 25) { $obj->title = substr($obj->title, 0, 25) . "..."; } $data = array("id" => $obj->id, "title" => $obj->title, "content" => $obj->content, "author" => $obj->author, "add_by" => $obj->add_by, "category" => $obj->post_category, "image" => $obj->post_image, "num_likes" => $obj->num_likes, "num_comments" => $obj->num_comments, "num_views" => $obj->num_views, "post_cat_id" => $obj->post_cat_id, "date_added" => $obj->date_added ); echo $this->html($type, $data); $counter ++; } // $counter ++; } } It's pretty self explanatory. retrieve all items within the criteria and display the first 8. Problem is it displays all of the items that fit the criteria. It works fine other than that and I can't see the problem. What am I overlooking?
-
Hello guys! I'm currently writing a bit of an image gallery code which is working pretty well however there seems to be a few issues with the sytling and layout of the gallery. (It's nothing flash just displays the images and caption in category order) Now I am not sure how to go about doing this but is there any way to wrap each category in a div? I have the whole while loop wrapped in a div at present but I would like each category wrapped so I can style it a bit easier. Can someone please point me in the right direction. Currently my code looks like this: function Gallery(){ ini_set('display_errors',1); error_reporting(E_ALL); $conn = mysqli_connect("Why","Hello","There","Friends") or die('Cannot Connect to the database'); $q ="SELECT * FROM gallery_category AS c JOIN gallery_photos AS p ON p.categoryname = c.categoryname ORDER BY c.categoryid"; $result = mysqli_query($conn, $q) or trigger_error("Query Failed! SQL: $conn - Error: ".mysqli_error(), E_USER_ERROR); echo"<div class='gallery'>"; $categoryname=''; while($rows = mysqli_fetch_assoc($result)){ if ($categoryname != $rows['categoryname']) { $categoryname = $rows['categoryname']; echo"<div class='h'><h2>".$rows['categoryname']."</h2></div>"; } echo" <div class='gall'> <div class='gl-img'><img src='pathway/to/gallery/".$rows['photoname']."' alt='".$rows['categoryname']."'/></div> <div class='gl-cap'>".$rows['photocaption']."</div> </div>"; } echo"</div>"; $conn-> close(); } I don't know how to go about updating it so that it is this section that is wrapped whilst the "gall" class repeats (if that makes sense) echo"<div class='h'><h2>".$rows['categoryname']."</h2></div>"; } echo" <div class='gall'> <div class='gl-img'><img src='pathway/to/gallery/".$rows['photoname']."' alt='".$rows['categoryname']."'/></div> <div class='gl-cap'>".$rows['photocaption']."</div> </div>"; So that it looks like this: <div class="category"> <div class="h"><h2>Category Title</h2></div> <div class="gall"> <div class="gl-img"><img src="pathway/to/gallery/polarbear2.jpg"></div> <div class="gl-cap">Polar Bear</div> </div> <div class="gall"> <div class="gl-img"><img src="pathway/to/gallery/polarbear2.jpg"></div> <div class="gl-cap">Polar Bear</div> </div> <div class="gall"> <div class="gl-img"><img src="pathway/to/polarbear2.jpg"></div> <div class="gl-cap">Polar Bear</div> </div> <div class="gall"> <div class="gl-img"><img src="pathway/to/gallery/polarbear2.jpg"></div> <div class="gl-cap">Polar Bear</div> </div> </div> Any and all help on how to achieve this would be appreciated!! thank you
- 2 replies
-
- php
- while loop
-
(and 1 more)
Tagged with:
-
Hope someone can help, I am trying to add up all the values of a variable in a PHP while loop and have tried several approaches but none seem to work. Hopefully someone can point out what the correct method is. I've set up some code to pull the pay rate from a MySQL table, and then calculate that person's earnings based on the amount of time they spend on a particular job. That works fine: while ($row = $getrate->fetch_assoc()) { $staffrate = $row["Rate"]; $earnings = ($staffrate/3600) * $jobeventtimeseconds; $earningsformatted = number_format($earnings, 2); } However there may be a number of jobs for different people with different rates, so I want to add all of these up and output the total. So for example if I had values of 125.00, 35.50 and 22.75 I want to show 183.25 as the total. So I tried a few things I found on forums on the subject: $totalearnings = 0; foreach($earningsformatted as $key => $value) { $totalearnings += $value; } echo $totalearnings; That didn't work so I tried another method that someone suggested: $total=array($earningsformatted); echo array_sum($total); The 2nd method outputted just the last individual value, the 1st method didn't work at all. Does anyone have a working method that can be used to do this? Thanks
-
can some one help me with this code I'm getting a Parse error: syntax error, unexpected T_ENDWHILE error code on the last line of code. source code below <?php while ( have_posts() ) : the_post(); ?> <h1><?php the_title(); ?></h1> <?php get_template_part( 'content', 'page' ); ?> </div> <?php thinkup_input_allowcomments(); ?> <?php endwhile; wp_reset_query(); ?> <?php $mytrails = new WP_Query(array( 'post_type' => '$mytrails' )); ?> <?php endwhile; ?>
- 3 replies
-
- parse error
- while loop
-
(and 1 more)
Tagged with:
-
Ok, so I have a main page that grabs data from a MySQL db and posts it into a dropdown menu see here: $sql = "SELECT * FROM 4000Series"; $result = $con->query($sql); print "Select your GPU: <select name='gpuId'>"; while ($row = $result->fetch_assoc()) { print "<option value='" .$row["id"] . "'>" . $row["gpu"] . "</option>"; } print "</select> </br>\n"; This works fine, from here I'm passing the POST data from the option values to a new page (basically the option values correspond directly to the "id" value in my SQL db). The values are passed onto the new page fine, but when I try to setup an SQL select statement to grab the row with the corresponding "id" value and print it out with a while loop I'm shooting a blank. Here's the code for the second page $id = $_POST['gpuId']; **Connect to sql db here** $sql = "SELECT * FROM 4000Series WHERE $id ='id'"; $result = $con->query($sql); echo "<table>"; while ($row = $result->fetch_assoc()){ echo "<tr><td>" . $row['id'] . "</td><td>" . $row['gpu'] . "</td></tr>"; } echo "</table>"; When I view the source it prints out the table tags but nothing in the while loop, any ideas?
-
Ok, so I created a test database on my server, created 1 table with 1 row in it and the row is populated with values. I can connect to the database without error, but when I try to put in a while loop to print the results I get nothing but a blank screen. I tried placing some debug code in the while loop to see where its getting hung up but the while loop doesn't want to run at all. I placed an echo directly outside of the loop and the debug text is displayed fine but anything I put in the loop doesn't work. Can anyone help me out? Here is my code: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> </head> <body> <?php $dbuser = "webestat_testdb"; $dbpass = "password"; $dbname = "webestat_testdb"; $server = "localhost"; $conn = mysql_connect($server, $dbuser, $dbpass); if (!$conn) { echo "Failed to connect to db" . mysql_error(); } $selectdb = mysql_select_db('webestat_testdb', $conn); $sql = "SELECT * FROM 4000Series"; $results = mysql_query($conn, $sql); while($row = mysql_fetch_assoc($results)) { echo "test"; echo $row['gpu']. " " .$row['khs']. " " .$row['usd']; echo "<br>"; } mysql_close($conn); ?> </body> </html>
-
In this multi-table query, I gave each table a static value (e.g. 'GW' AS Site, 'GZ' AS Site)... $stm = $pdo->prepare("SELECT 'GW' AS Site, CGW.N, CGW.URL, CGW.Date, CGW.Year, CGW.Brief FROM calendar_gw CGW WHERE CGW.URL = :MyURL UNION ALL SELECT 'GZ' AS Site, CGZ.N, CGZ.URL, CGZ.Date, CGZ.Year, CGZ.Brief FROM calendar_gz CGZ WHERE CGZ.URL = :MyURL ORDER BY Year"); $stm->execute(array( 'MyURL'=>$MyURL ));
-
Hello. I am new. I have simple two step process I want to be done. When it does work the webpage keeps going (im guessing it's an endless loop)... I can't seem to get it to work: I know there's something I'm missing about this PDO array stuff. <?php include("database.php"); $time_ago = strtotime("-1 minute"); /*find subscribers over a month old with the thirtydaysubs table*/ $checker = "SELECT emailaddress FROM aa_thirtydaysubs WHERE subscribedate < $time_ago"; $sthandler = $database->prepare($checker); $sthandler->execute(); /*then move it to main list and remove from 30 day list*/ $data = array(); $data = $sthandler->fetch(); if ($sthandler->columnCount()){ while($sthandler->fetchAll(PDO::FETCH_ASSOC) !== 0){ $email2 = $data->fetchColumn(0); $newlist= "2"; $updatelistid = "UPDATE zzemail_list_subscribers set listid = :newlist WHERE emailaddress = :email"; $sthandler3 = $database->prepare($updatelistid); $sthandler3->execute(array(':email' => $email2, ':newlist' => $newlist )); $clearars = "DELETE FROM aa_thirtydaysubs WHERE emailaddress= :email"; $sthandler6 = $database->prepare($clearars); $sthandler6->execute(array(':email' => $email2)); } } ?>
-
I'm a beginner currently going through php loops. I pretty much understand the fundamentals of loops but i can't figure out why this piece of code. <?php $count = 0; while ( true ) { $count++; echo "I ’ ve counted to: $count <br />"; if ( $count == 10 ) break; } ?> results in this output: I ’ ve counted to: 1 I ’ ve counted to: 2 I ’ ve counted to: 3 I ’ ve counted to: 4 I ’ ve counted to: 5 I ’ ve counted to: 6 I ’ ve counted to: 7 I ’ ve counted to: 8 I ’ ve counted to: 9 I ’ ve counted to: 10 If a loop goes back to the starting point after successful completion, why isn't the value of the variable $count equal to 1 each time, thereby outputting "I've counted to: 1 over and over.
-
Can anyone help me? I am a student and I have been working on a PHP project for over two weeks with no luck on one piece of code. The project is a small "Madlib" project, but I'm only having trouble with one piece of code. Any takers? All I'm trying to do is get a sentence like "I bought a NOUN and NOUN." to be replaced with "I bought a cat and a dog." The problem is, I get this: "I bought a cat and a cat." I have tried all the loops I can try. Yes, I'm a newbie, but I'm desperate and can't figure this out. I have my html and php code, also the URL to the website. Any help would greatly be appreciated. Thanks. I have attached my html and my php file to this posting. project1.htmlproject1.php I have posted the small piece of code I am having a problem with down below: $counter=0; $nounCounter=0; while ( $counter < $sentLength and $nounCounter < $nounLength) { if($sentArray[$counter]=="NOUN") { $newSent = str_replace($sentArray[$counter], $nounArray[$nounCounter], $initialSent); } $counter++; echo $newSent . '<br .>';
-
i have been working on minor project this is login script of that page i am facing some problem i want to echo if user name password and category both 3 conditions dont match with error "wrong username/password" in form i have tried everything as per my knowledge please help me in this i am new to php so dont have much experience and knowledge of php <?php $msg=''; $con=mysql_connect('localhost','root',''); if(!$con) { die("Error While connecting......."); } else { mysql_select_db("sms",$con); if(isset($_POST['btnlog'])) { $res=mysql_query("select * from tbl_login where un='".$_POST['username']."' and pw='".$_POST['password']."' and cat='".$_POST['cat']."'"); while($r=mysql_fetch_array($res)) { mail("notification@receiver.com".$_POST['username']."Successfully Logged In"."From:notification@sender.com"); if($r['cat']=="admin") header("Location:admin/admin.php"); elseif($r['cat']=="faculty") header("Location:faculty/faculty.php"); else $msg="Incorrect Username/Password"; } } } ?> <body> <section class="login_container"> <div class="login_box"> <h1>Login</h1> <form method="post"> <center><?php echo $msg; ?></center> <p><input type="text" name="username" value="" placeholder="Username"></p> <p><input type="password" name="password" value="" placeholder="Password"></p> <center><select class="select" name="cat">Category <option selected="selected">Select A Category</option> <option value="admin">Administrator</option> <option value="faculty">Faculty</option> </select></center> <p class="submit"><input type="submit" name="btnlog" value="Login"> <input type="reset" value="Clear" /></p> </form> </div> </section>
- 4 replies
-
- php
- while loop
-
(and 3 more)
Tagged with:
-
hey, this should echo all of the results from the query, right? in the database there is more than 1 fields to echo, but it only echos 1, whats wrong with it? $getid = mysql_query("SELECT * FROM $tbl_name WHERE userid='$id'", $connect); $idresults= mysql_fetch_array($getid); while($idresults= mysql_fetch_array($getid)){ echo $idresults['frienduserid']; }
-
So a friend and I have recently started coding a simple posting webpage. At the moment we are trying to make a like button to like other posts but we are having trouble. We have made this like button and it works kind of right, the only problem is that when we click it, it adds a like to all the posts not just the one we click. Since we are trying to make a very simple page for now, we would like to keep the amount of files to a minimum and so we can not, nor would we like to, use the facebook like button. We are using Wamp, I don't think that would be relevant just like to add it in there. connection.php wall.php
- 1 reply
-
- form
- unique submit
-
(and 3 more)
Tagged with:
-
This is example of my record: year quanitity name 2012 10 john 2012 20 mark 2013 30 david 2013 40 alex 2014 50 stacy while (!$report->EOF){ if(is_null($year) || $year <> $report->fields['year']) { $year = $report->fields['year']; ?> <tr><td align="center" colspan="2" >Year : </td><td><?=$year ?></td></tr> <? } ?> <tr><td align="center" colspan="2" >Quantity : </td><td><?=$report->fields['quanitity'] ?></td></tr> <? $report->MoveNext(); } How to do so the result goes like this 1) group by years 2) total quantity for each year year : 2012 name : john quantity : 10 name : mark quantity : 20 Total : 30 year : 2013 name : david quantity : 30 name : alex quantity : 40 Total : 70
-
I have a simple category table in which 5 or 6 names are there. Now I want to retrieve them. When I connect to mysql database in procedural way, the while loop is working great, giving nice output. But when I go through a class and trying to retrieve the data, it stops after giving the first table name. My procedural code is here: mysql_connect("localhost", "root", ""); mysql_selectdb("12reach"); $cat = mysql_query("SELECT * FROM `category` LIMIT 0 , 30"); if (!$cat){ die ('Error'); } while ($row = mysql_fetch_array($cat)) { extract($row); echo $row['name'].'<br>'; } It works fine. Giving six category name. But problem begins with the following code: I have two classes and a php file where I created an instance of category class and trying to get the category table names one by one. class ConnectClass { private $_connection; public function getConnect() { $this->_connection = mysql_connect("localhost", "root", ""); if (mysql_errno()) { throw new RuntimeException('Cannot access database: '.mysql_error()); } else { mysql_selectdb("12reach", $this->_connection); } } include 'ConnectClass.php'; class CatClass extends ConnectClass{ public function getcat() { $cat = mysql_query("SELECT * FROM `category` LIMIT 0 , 30"); if (!$cat){ die ('Error'); } while ($row = mysql_fetch_array($cat)) { extract($row); return $row['name'].'<br>'; } } } include 'CatClass.php'; $obj=new CatClass(); $obj->getConnect(); echo $obj->getcat(); Probably while loop is working inside the class. As I want to return the last name of the category table, I can get it placing it outside the loop. But if I want the full name list, it does not work in object oriented format. Any idea, where is my fault?
- 8 replies
-
- while loop
- class
-
(and 1 more)
Tagged with:
-
Hello, I am trying to do a while loop and the loop does fine because I tested it using an echo statement. However, Every time I remove the echo statement and place a MySQL Alter in there, it does not work. $d = 1; while ($d <= $depth) { $w = 1; while ($w <= $width) { mysql_query("ALTER TABLE `$b` ADD `test$b$w$d` int unsigned not null"); $w++; } $d++; } But.... When I use the same Alter Phrase outside the loop it works fine. What am I missing here? I do not understand why this will not work in the loop but does outside of it! Thanks for your help!
- 4 replies
-
- mysql alter
- while loop
-
(and 1 more)
Tagged with:
-
I'm trying to make an If Else Statement in my while loop which that statement can read the value from what the user inserted. Each numbers have their own link which process different type of letter. Is that possible to insert 'If ... Else Statement' in my While Loop ?? because I keep getting an error message when I combine If Else inside my While Loop. But without If Else , there's no error message appear. Hope from this code you can see what I'm trying to do . <?php $host_name = "localhost"; $user_name = "root"; $password = ""; $db_name = "finalproject"; $StudentID1=$_POST['Field0']; $StudentID2=$_POST['Field1']; $StudentID3=$_POST['Field2']; $term =$StudentID1.-$StudentID2.-$StudentID3; mysql_connect("$host_name" , "$user_name" , "$password"); mysql_select_db("$db_name"); $sql = "SELECT * FROM student,surat WHERE student.student_id like '%$term%' AND student.student_id=surat.student_id"; $query = mysql_query($sql) or die("Error: " . mysql_error() . "<br />In Query: " . $sql); while ($row = mysql_fetch_array($query)){ echo 'Student ID: '.$row['student_id']; echo '<br/> Fullname: '.$row['fullname']; echo '<br/> IC No.: '.$row['ic_number']; echo '<br/> Course: '.$row['course']; echo '<br/> Type Of Letter: '.$row['jenissurat']; echo '<br/><br/>'; $jenis=$rows['jenissurat'] if($jenis=='1') { ?> <a href="PHPWord/PengesahanBelajar-code.php">Generate Letter</a> <? } else if($jenis=="2") { ?> <a href="PHPWord/KebenaranProjek-code.php">Generate Letter</a> <? } else if($jenis=="3") { ?> <a href="PHPWord/PelepasanExam-code.php">Generate Letter</a> <? } else if($jenis=="4") ?> <a href="PHPWord/TamatBelajar-code.php">Generate Letter</a><? } } ?> I also need a help to bring data of '.$row['jenissurat']; as my If Else condition.. Many of this code I copy from a website.. I'm new in PHP and Mysql ... but I MUST to complete this code without error. I already download 2 file that have connection with this code. Hope someone can give me an advice,solution or corrections maybee.. Thank You. Search.php searchres.php
- 8 replies
-
- if else
- while loop
-
(and 2 more)
Tagged with:
-
Hello!!!! I have a while loop which outputs variables made from mysql query, but i want to order this output according to one of those php variables created later after the mysql query. I think that i can put all the outputted variables of the loop in an array and than order them in the array and output them. How can i make an array that will look like a matrix where nr.rows=nr.loops and nr.columns=nr.variables THAN order these rows by one column....like in excel: you create a table and than you sort them according to a column . After i output the array with a "for" loop for each row . PLS HEEELP. I know what i want but i don't know how can it be done EDIT: If your answers will be you can do it in mysql query.....than i say simply it's impossible......because the variable which i want to order the results from is generated AFTER the query and it's a mix of mysql variables($row[''])+form input variables ($_POST['']). So simply i cannot do it in mysql unless you suggest s.m.th else
- 24 replies
-
Hey guys, I am trying to grab and loop data from my DB with a while loop and extract() function. right now i have something like this: echo '<div>'; // CONTAINER DIV echo '<h2>News about '. $db_name. '</h2>'; $query = 'SELECT * FROM `news_to_people` WHERE `people_db_id` = '.$db_id; $r_query = mysql_query($query); while($rows=mysql_fetch_assoc($r_query)){ extract($rows); $new_q = 'SELECT * FROM `news` WHERE `id` = '.$news_id; $run_q = mysql_query($new_q); $rows = mysql_fetch_assoc($run_q); extract($rows); echo '<ul>'; echo '<l1><a href="article?articleid='.$id.'&name='.$db_name.'">'.$title.'<br></l1>'; echo '</ul>'; } echo '</div>'; // END TO CONTAINER Now here i get the loop to fire correctly and execute. It then loops all 170+ links except in the middle of the loop , there is an error: so this means that i have a failed 2nd query somewhere in that it is skipping inside the while loop. i need to debug and find which query is bringing this error. my question is what is the best way i can write an if statement to see which query is failing or which query is not returning a proper array. also my if the query was failing wouldn't the error be asking for a proper resource ? this means the query is firing correctly and the extract() function is failing to receive all the rows. meaning that one of the rows must be returning empty or zero ? any help is much appreciated.
- 3 replies
-
- while loop
- php
-
(and 3 more)
Tagged with: