PHP - Problem With Loop Using Php And Mysql
Similar TutorialsAnyone know why I get this from my mysql query?It adds an extra key for some reason. $types = array(); while ($row = mysql_fetch_array($query_name,MYSQL_NUM)) { $types[] = $row; } print_r ($types); Array ( => Array ( => Matt ) [1] => Array ( => Larissa ) [2] => Array ( => Braden ) [3] => Array ( => Tom ) ) Hi, I'm in need of making some loops within each other, in order to retrieve the info which i need. First part of my code: Code: [Select] <div class="hastable"> <table id="sort-table"> <thead> <tr> <?PHP //echo '<th style="width:128px">Options</th>'; echo ' <th> Identifier </th> '; $fieldresult = mysql_query("SELECT * FROM fields ORDER BY `order`"); while($fieldrow = mysql_fetch_array($fieldresult)) { echo ' <th> ' . $fieldrow["name"] . ' </th> '; So you see, here i create all the table headers required, as long as it can still fetch some data. My problem is, that I need to execute a echo '</tr>'; when it's done fetching the data, meaning as soon as it cannot retrieve any more data, i need to close this row, as the next data coming, should be placed in a second row.. Is there any way to do this - Without exiting the loop? I am a noob at php, looking to become great. My php loop only seems to draw 1 row from the database when listing it out. Here is the loop <?php require('header.php'); mysql_select_db('center'); $sql = "select username, password from users"; $result = mysql_query($sql); $row = mysql_fetch_array($result); $user = $row['username']; $pass = $row['password']; echo "<table border='1'>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>$user</td>"; echo "<td>$pass</td>"; echo "</tr>"; } echo "</table>"; ?> Need some feedback on this loop Tables: Table A Table B Loop Select all from A based on criteria a. Insert into table B using row data from table A b. Update record in table A to say that it has gone through loop to prevent future loop Thats three MySQL queries running over and over at the same time, how bad is that for performance, is there another way? Maybe instead of running b each time build an array with the record ids from Table A and after the loop runs to insert into Table B run another query with the IN command to loop through all of the IDs in the array and update? Hey guys, I am trying to input data into a mysql database from data thats been added by a jquery form with cloned fields. It is working however it adds the first row correctly then a blank row and then the rest of the rows correctly The code is this $x=0; do { $fga=$_POST['ID'.$x.'fga']; $fgm=$_POST['ID'.$x.'fgm']; $fta=$_POST['ID'.$x.'fta']; $ftm=$_POST['ID'.$x.'ftm']; $tpa=$_POST['ID'.$x.'tpa']; $tpm=$_POST['ID'.$x.'tpm']; $fta=$_POST['ID'.$x.'fta']; $ftm=$_POST['ID'.$x.'ftm']; $stl=$_POST['ID'.$x.'stl']; $trb=$_POST['ID'.$x.'trb']; $ast=$_POST['ID'.$x.'ast']; $blka=$_POST['ID'.$x.'blka']; $blkf=$_POST['ID'.$x.'blkf']; $tovr=$_POST['ID'.$x.'tovr']; mysql_query("INSERT INTO stats (gameId, fga, fgm, tpa, tpm, fta, ftm, ast, stl, trb, blka, blkf, tovr) VALUES ('$gameId', '$fga', '$fgm', '$tpa', '$tpm', '$fta', '$ftm', '$ast', '$stl', '$trb', '$blka', '$blkf', '$tovr')")or die("<div class='errmsg'>Insert Error: ".mysql_error()."</div><br /> \n"); $x++; Can anyone see what ive done wrong? Thanks I've got Code: [Select] for ($i=1; $i<=5; $i++) { if(isset($_POST['partsusedqty'.$i]) && $_POST['partsusedqty'.$i] != "" && $_POST['partsusedqty'.$i] != "0.00") { mysql_query("INSERT INTO partsused (ptnumber, partqty, partdesc, partprice) VALUES ($ticket, '$partsusedqty'.$i, '$partsuseddesc'.$i, '$partsusedprice'.$i)") or die(mysql_error()); } } I need to know the correct formatting to put these variable variables as values in the mysql query. With this particular code, I get the error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.1, ''.1, ''.1)' at line 2" I've tried formatting this an endless number of ways, but I used this particular example because its the one I really thought should work. Everything I've tried that doesn't throw an error put the $partsusedqty in the partqty, partdesc, and partprice fields. Thanks for any help! I have a while loop that is making a table 5 times for me. The issue that i am having is i need to run 5 different mysql query's for the 5 different tables that the loop is making for me. How would i go about doing this? Here is my code <? $i=1; while ( $i <= 5 ) { ?> <table width="600" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="414" height="35" colspan="5"><strong>Level <?=$i?></strong></td> </tr> <tr> <td height="25"><div align="center">Join Date</div></td> <td><div align="center">Member Name</div></td> <td><div align="center">Username</div></td> <td><div align="center">Free/Pro</div></td> <td><div align="center"></div></td> </tr> <? $level_one = mysql_query("select * from users where ref_by = '$username'"); while ($level_one_do = mysql_fetch_array($level_one)) { $status = $level_one_do['status']; if($status == 1) { $status_type = "Free"; } else { $status_type = "Pro"; } ?> <tr> <td height="35"><div align="center"></div></td> <td height="35"><div align="center"></div></td> <td height="35"><div align="center"> <?=$level_one_do['Username']?> </div></td> <td height="35"><div align="center"></div></td> <td height="35"><div align="center"><img src="images/email_forward-32.png" width="25" height="25"></div></td> </tr> <? } ?> </table> <? $i++; } ?> I am trying to place a unique number into a mysql table. Currently, my code generates a random number, then is supposed to scan through the table for that number. If the code finds that number already in the table, it generates a new random number and repeats the process. I have commented my code for the purpose of this help forum: Code: [Select] $result = mysqli_query($link,"SELECT * FROM testTable"); do { $end = true; //prepares end of loop $idNum = rand(1,10); //rand(1,999999); <-- for testing purposes I have reduced the number generated $idNumTx = (string)$idNum; //loop through the rows while ($row = mysqli_fetch_assoc($result)) { if ($row['idNum'] = $idNum) //check if the random number equal to this row { $end = false; //prep end of loop repeat echo $idNumTx; //display rand number that failed for testing purposes echo " NO! "; //display error for testing purposes } } } while(!$end); I know I must be doing something wrong, as when I run this, it runs the if statement within the while loop always executes, and I get an output like: Code: [Select] 1 NO! 1 NO! 1 NO! 1 NO! 1 NO! 1 NO! 5 Win Win is when it places the value before it, in this case 5, into the table. However, the value of 5 might already be in the table and it doesn't seem to matter. I execute the code multiple times, and it seems to increase the number of "# NO!" almost (but not every) time. However, each time ALL of the "# NO!" are the same #, and the "# Win" just seems to be random (as it should be, but not unique). Checking the table after shows me random numbers between 1 and 10 (as it should) in the correct field, but the are not unique. (Ex/ Both row 1 and 5 could have the same value, say 6) I'm hopefully doing something simple wrong, so someone please point it out to me Apparently, this is bad. Wish someone would have told me. Sadly, it is too simple. I had Code: [Select] <? $company=mysql_query("select this and that") while($company=mysql_fetch_array($company)) { a bit of output; $properties=mysql_query("Select this and that from properties where company_id=$company['id']") while(properties=mysql_fetch_array()) { what I want to output } } I seem to be missing some understanding of what the heck to do now. Please, please any suggestions. I suck at object orientation, and arrays of arrays of arrays confuse the crap out of me. Am I missing something simple. Am I over-reacting? I have 15 companies, and about 100 properties total. I have a script that displays a certain result set, the row I am concerned about is called 'endonum'. Some rows will have the same number in this field. Is there a way to only show 1 result with the same number in this field. The array will be like '1, 2, 3, 3, 4, 4, 4, 4, 5, 5, 5' and so on, but I just want to display 1 of them, not all. Kinda confusing but maybe someone gets it. Here is the code. <?php $selectendo = mysql_query("SELECT * FROM endorse WHERE agency = '$agency' AND finalized = 'No'")or die(mysql_error()); while($showendo = mysql_fetch_array($selectendo)) { $endonumber = $showendo['endonum']; ?> <li><a href="viewendo.php?endonum=<?php echo $endonumber;?>">Endorsement Number:<?php echo $endonumber . " Date: " . $showendo['date'];?></a></li> <?php } ?> Hi, Here is an extract of my while loop while ($personquery = mysql_fetch_array($personfetch, MYSQL_ASSOC)) { echo "$personfetch[first_name]"; } This will list each person now I want to do an INSERT to the database on every single member that is being listed I can only get it to INSERT for the one. Thanks mysql_query("update pupils set record='running' where pid !='$testing[0]' Hey everyone ... This should be a pretty easy question for someone who is used to using fgetcsv: I have a script that needs to import a csv file into a mysql table ... I keep getting stuck in a loop that only ends when the script hits the 30 second timeout I have set on the server ... It never actually inserts a record, and it never spits out a message indicating and error ... Can someone help figure out why I get caught in this loop? Here's the code: Code: [Select] function import_csv() { if(isset($_POST['submit_csv'])) { $filename=$_POST['filename']; $handle = fopen("$filename", "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $import="INSERT INTO `{mydatabase}`.`{my table}` (`name`, `qrl`, `begin`) VALUES ('$data[0]','$data[1]','$data[2]')"; mysql_query($import) or die(mysql_error()); } fclose($handle); print "Import done"; } else { print "<form action='results.php' method='post'><input type='file' name='filename'><br /><input type='submit' value='submit' name='submit_csv' /></form>"; } } I am having a little bit of trouble with this piece of code. I'm sure it's something simple, but I have been working on this thing all day and want to get it finally finished. Here's the troublesome code: function rrmdir($dir) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object); } } reset($objects); rmdir($dir); } } $sql_clean = "SELECT * complete WHERE createdate < date_sub(current_date, interval 1 minute)"; $sql_list = mysql_query($sql_clean); while($row = mysql_fetch_assoc($sql_list)) { $directory = "complete/" . $row['fileurl']; rrmdir($directory); } The purpose of this particular bit is to run on a cron every few days. It gets "createdate" and other info from the "complete" table in order to know how old the record is. If the record is older than (in the example, 1 minute; it will be set to several days on public) the defined max age, it removes that directory and everything within it to keep the directory clean and the disk usage down. The error returned is Quote Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home1/latenit2/public_html/kindleprocessor/process/garbagecleaner.php on line 46 Line 46 is Quote while($row = mysql_fetch_assoc($sql_list)) { I may be doing the look-up on the MySQL database incorrectly, too. I haven't discounted that, and I'd be thankful if someone could help me out with this issue. Im turning a static slider revolution in a dynamic. Images are uploading and fetching perfect from Mysql DB but the texts (top-text) is showing only in the first slide. The rest is empty. Here is the Code
Any help would be great.
UPLOAD.php
<?php // Include the database configuration file include 'database/dbConfig.php'; $statusMsg = ''; // File upload path $targetDir = "uploads/"; $fileName = basename($_FILES["file"]["name"]); $top_text = filter_input(INPUT_POST, 'top_text'); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){ // Allow certain file formats $allowTypes = array('jpg','png','jpeg','gif','pdf'); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ // Insert image file name into database $insert = $db->query("INSERT into images (file_name, top_text, uploaded_on) VALUES ('".$fileName."', '".$top_text."', NOW())"); if($insert){ $statusMsg = "The file ".$fileName. " has been uploaded successfully."; }else{ $statusMsg = "File upload failed, please try again."; } }else{ $statusMsg = "Sorry, there was an error uploading your file."; } }else{ $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.'; } }else{ $statusMsg = 'Please select a file to upload.'; } // Display status message echo $statusMsg; ?>
SLIDER <!-- Revolution slider --> <section id="slider"> <div class="tp-banner-container "> <div class="tp-banner rev-banner-fullscreen"> <ul> <!-- SLIDE --> <?php // Include the database configuration file include 'database/dbConfig.php'; // Get images from the database $query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC"); if($query->num_rows > 0){ while($row = $query->fetch_assoc()){ $imageURL = 'uploads/'.$row["file_name"]; $top_text = $row['top_text']; ?> <!-- DYNAMIC SLIDE --> <li data-index="rs-140" data-transition="slideup" data-slotamount="default" data-easein="default" data-easeout="default" data-masterspeed="default" data-thumb="" data-rotate="0" data-saveperformance="off" data-title="1/2" data-description=""> <!-- MAIN IMAGE --> <img src="<?php echo $imageURL; ?>" alt="" style='background-color:#f4f4f4' alt="" width="482" height="800" data-bgposition="center center" data-bgfit="cover" data-bgrepeat="no-repeat" class="rev-slidebg" data-no-retina> <!-- LAYERS --> <!-- LAYERS 1.2 --> <div class="tp-caption tp-resizeme" id="slide-1-layer-2" data-x="['left','left','left','left']" data-hoffset="['102','102','67','40']" data-y="['top','top','top','top']" data-voffset="['150','150','60','60']" data-fontsize="['18','18','14','14']" data-width="['345','345','345','259']" data-height="none" data-whitespace="normal" data-transform_idle="o:1;" data-transform_in="y:50%;z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;opacity:0;s:900;e:Power4.easeInOut;" data-transform_out="x:-50%;opacity:0;s:800;e:Power2.easeInOut;s:300;e:Power2.easeInOut;" data-start="500" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 6; min-width: 345px; max-width: 345px; white-space: normal; color: #3e3e3e; font-family: 'Montserrat'; letter-spacing: 7px;"> <?php echo $top_text; ?> </div> <!-- /END DYNAMIC SLIDE --> </li> <?php } }else{?> <!-- DEFAULT SLIDE --> <li data-index="rs-140" data-transition="slideup" data-slotamount="default" data-easein="default" data-easeout="default" data-masterspeed="default" data-thumb="" data-rotate="0" data-saveperformance="off" data-title="1/2" data-description=""> <!-- MAIN IMAGE --> <img src="images/slide/slide-5-bg.jpg" style='background-color:#f4f4f4' alt="" width="482" height="800" data-bgposition="center center" data-bgfit="cover" data-bgrepeat="no-repeat" class="rev-slidebg" data-no-retina> <!-- LAYERS --> <!-- LAYERS 1.2 --> <div class="tp-caption tp-resizeme" id="slide-1-layer-2" data-x="['left','left','left','left']" data-hoffset="['102','102','67','40']" data-y="['top','top','top','top']" data-voffset="['150','150','60','60']" data-fontsize="['18','18','14','14']" data-width="['345','345','345','259']" data-height="none" data-whitespace="normal" data-transform_idle="o:1;" data-transform_in="y:50%;z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;opacity:0;s:900;e:Power4.easeInOut;" data-transform_out="x:-50%;opacity:0;s:800;e:Power2.easeInOut;s:300;e:Power2.easeInOut;" data-start="500" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 6; min-width: 345px; max-width: 345px; white-space: normal; color: #3e3e3e; font-family: 'Montserrat'; letter-spacing: 7px;"> New Arrival </div> <!-- /END DEFAULT SLIDE --> <?php } ?> </li> <!-- /SLIDE 1 --> </ul> </div> <!-- /tp-banner --> </div> <!-- /tp-banner-container --> </section> <!-- /#Revolution slider -->
So i have this php as shown below. It should make a list of comments with comment replies below their comment respectively. The problem is that it only goes through and shows 1 comment and all the comment replies for that one comment. It should be showing all comments i have in the db for that article. If i remove the second while then it shows all the comments correctly but no comment replies then... How do i get this script to loop through the db for every comment but also loop through every comment reply for that $row[id]? If anyone has a better / more efficient way of what I am trying to do, please explain or show example (i am open to anything)... Code: [Select] // what article are we showing? $article_to_show_id = $_GET['article_id']; $active_is_set_text = "1"; // Active Column text that makes it okay to show // Finding the article $search_for_article = mysql_query("SELECT * FROM articles WHERE id = '$article_to_show_id' AND active = '$active_is_set_text'"); while($row = mysql_fetch_array($search_for_article)) { // format the last updated date right $update_date_edit = $row[update_date]; $update_date_edit = date('F j, Y \a\t h:ia', $update_date_edit); $row[update_date] = $update_date_edit; // format the submit updat date right $submit_date_edit = $row[submit_date]; $submit_date_edit = date('F j, Y \a\t h:ia', $submit_date_edit); $row[submit_date] = $submit_date_edit; echo ' <div> ', $row[title] ,' </div> <div> by: ', $row[author] ,' on ', $row[submit_date] ,' </div> <div> ', $row[content] ,' </div> <div> Last Updated: ', $row[update_date] ,' </div> <form action="article_reply.php" method="post"> <input type="hidden" name="article_id" value="', $row[id] ,'" /> <button name="article_reply" type="submit" value="submit">Reply</button> </form> '; } $comment_count = 0; $comment_reply_count = 0; // Finding all of the comments $search_for_article = mysql_query("SELECT * FROM article_comments WHERE article_id = '$article_to_show_id' AND reply_id = '0'"); while($row_comment = mysql_fetch_array($search_for_article)) { // format the submit updat date right $comment_date_edit = $row_comment[comment_date]; $comment_date_edit = date('F j, Y \a\t h:ia', $comment_date_edit); $row_comment[comment_date] = $comment_date_edit; echo ' <br> <br> COMMENT:<br> <div> By: ', $row_comment[username] ,' on ', $row_comment[comment_date] ,' </div> <div> ', $row_comment[comment] ,' </div> '; $comment_count++; // Finding all of the comment replies if any $search_for_article = mysql_query("SELECT * FROM article_comments WHERE article_id = '$article_to_show_id' AND reply_id = '$row_comment[id]'"); while($row_two = mysql_fetch_array($search_for_article)) { // format the submit updat date right $comment_date_edit = $row_two[comment_date]; $comment_date_edit = date('F j, Y \a\t h:ia', $comment_date_edit); $row_two[comment_date] = $comment_date_edit; echo ' <br> <br> COMMENT REPLY:<br> <div> By: ', $row_two[username] ,' on ', $row_two[comment_date] ,' </div> <div> ', $row_two[comment] ,' </div> '; $comment_reply_count++; } } Hi there, I hope somebody can help me creating a loop for the following code: What it currently does is, showing only 1 image, while in fact there are 3 of them. I've combined a loginsystem with slideviewer. When i use the original php code (or a part of it) it only shows one listing. I need it to list all of them. <div id="mygalone" class="svw"> <ul> <li> <?php $result = mysql_query("SELECT reference FROM user_photos WHERE`profile_id`='".$row['id']."'"); while ($row2 = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "<a href=\"".$_GET['username']."/pics/".$row2['reference']."\"> <img src=\"".$_GET['username']."/pics/thumbs/".$row2['reference']."\"></a><br/><br/>"; } } ?> </li> </div> What can be stripped down to this: <?php { $result = mysql_query("SELECT reference FROM user_photos WHERE`profile_id`='".$row['id']."'"); while ($row2 = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "<img src=\"".$_GET['username']."/pics/".$row2['reference']."\">"; } } ?> You would asume that this is allready a loop, but it does not act like it. Best regards, Martijn (the netherlands) Is it possible to have a loop inside a mysql select statement? If yes, can someone please give me an idea. I am really just a beginner in PHP but I've got a task to create a simple hotel booking system by using PHP and MySQL. It works in several steps, described in separate .php files. All of them seem to work fine, except the last one. In this last file I want to add all the data into a MySQL database table. I would like to do this by creating a record for each date, a guest is spending in a hotel (so that when booking, another loop checks whether the room is not occupied yet for that date). I decided to use a for-loop for that, but it doesn't seem to be working (the records just don't get inserted into the table). I checked all the variables by echo-ing them and they are all right. I also tried the query without the loop and it works as well. So I guess there is some other problem. This particular .php file looks as follow: <?php session_start(); include('db_config.php'); $name=($_POST['name']); $telephone=addslashes($_POST['telephone']); $email=addslashes($_POST['email']); $code=md5($email.time()); $checkout_date=$_SESSION['checkout']; $checkin_unix=$_SESSION['checkin_unix']; $checkout_unix=$_SESSION['checkout_unix']; $roomtype=$_SESSION['roomtype']; $checkin_date=$_SESSION['checkin']; for ($stay_date=$checkin_unix; ; $stay_date=$stay_date+24*60*60) { if ($stay_date=$checkout_unix){ break; } mysql_query("INSERT INTO reservations VALUES( '', '$roomtype', 'pending', 'date ('d/m/Y', $stay_date)', '$stay_date', '$checkout_date', '$name', '$telephone', '$email', '$code' )"); } ?> I would appreciate any kind of help, any idea. This way seems not good. <?php $username ="MANCENT"; $user_input_x = _xmouse.movement ;//FLASH $user_input_y = _ymouse.movement ;//FLASH while(true) { $updatepos = mysql_query("UPDATE users_float SET user_input_x = '$user_input_x' , user_input_y = '$user_input_y' WHERE username = '$username'"); } This way works but whats a better way? ?> |