PHP - Pagination While Loop Issue : Getting 2 Records For Same Set Of Files
can anybody tell me what's wrong with my query ?
$filesa = "SELECT id, uid, size, filehash, filename, dwnloads, swidth, sheight, fores, flabel, vpre FROM pf_fmusic WHERE (aid='$albumid' AND vpre='complete') ORDER BY id DESC"; I am using this in while loop with ps_pagination class but getting 2 records for same set of files. in other words its running while loop 2 time complete code is here... $filesa = "SELECT id, uid, size, filehash, filename, dwnloads, swidth, sheight, fores, flabel FROM ibwf_fmusic WHERE (aid='$albumid' AND vpre='complete') ORDER BY id DESC"; $pager = new PS_Pagination($conn, $filesa, 9, 5, $albumid, $sortid, $sub, $selectalbum3[uid], $title, $collective); $results = $pager->paginate(); while($files=mysql_fetch_array($results)) { // Blah Blah } Output is something like this 1. song 1 2. song 2 3. song 3 4. song 4 1. song 1 2. song 2 3. song 3 4. song 4 Thanks is advance Similar TutorialsHi all, I am currently returning candidates from a database initially just by the highest candidate id to the lowest... i.e. newest candidates to oldest. I have introduced a sort feature which works just fine, the problem is I am displaying my results over a few pages using pagination. The problem arises once I sort my results and then try to click onto the next page of results. Basically it is just resetting the sort as the sort relies on a button being pressed, which obviously isn't happening when the user is trying to get the next page of results. I'm not sure exactly which section of code would be relevant to this so I have posted the whole script... additionally if you need to take a look at it in action you can do so he http://www.beta.teachingagencies.co.uk/search_jobseekers.php As I say I know the problem is that when the page is changed the value is lost, but I don't have a clue how to solve the problem! Any help or advice would be appreciated. Many thanks, Greens85 Hi, I was thinking of creating a table for this current code and place only 3 options in a row, however I do not know how to execute a command which will allow me to do so, I have attached 2 pictures to describe what I will like to achieve. Below is my code as well. Any advice? Thanks $query = ("SELECT * FROM tutor_preferred_district ORDER BY district_id ASC"); $sql = mysqli_query($dbc, $query) or die(mysql_error()); while($data = mysqli_fetch_array($sql)) { echo'<table>'; echo '<input name="district" type="checkbox" id="'.$data['district_id'].'" value="'.$data['district_id'].'">'; echo '<label for="'.$data['district_id'].'">'.$data['district_name'].'</label>'; echo'<table>'; }
I have a hopefully small issue on a form submitting data to the mysql database table and email. The email side works fine as does the adding the data to the database table but if I upload two files, it stores the support ticket twice in the database table where as I want to store just once and the files be stored as a array in the database table. I got the code from the link https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/
<?php require_once "registerconfig.php"; if (isset($_POST['submit'])) { // File upload configuration $targetDir = "support-ticket-images/"; $allowTypes = array('pdf','doc','docx','jpg','png','jpeg','gif'); $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = ''; // Escape user inputs for security $ticket_subject = htmlentities($_POST['ticket_subject'], ENT_QUOTES); $ticket_message = strip_tags($_POST['ticket_message'], ENT_QUOTES); $ticket_status ='PENDING SUPPORT'; $username = htmlentities($_SESSION["user_name"], ENT_QUOTES); $user_id = htmlentities($_SESSION["user_id"], ENT_QUOTES); $fileNames = array_filter($_FILES['files']['name']); if(!empty($fileNames)){ foreach($_FILES['files']['name'] as $key=>$val){ // File upload path $fileName = basename($_FILES['files']['name'][$key]); $targetFilePath = $targetDir . $fileName; // Check whether file type is valid $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){ // Image db insert sql $insertValuesSQL .= "('".$ticket_subject."','".$ticket_message."','".$fileName."','".$ticket_status."','".$username."', '".$user_id."'),"; }else{ $errorUpload .= $_FILES['files']['name'][$key].' | '; } }else{ $errorUploadType .= $_FILES['files']['name'][$key].' | '; } } if(!empty($insertValuesSQL)){ $insertValuesSQL = trim($insertValuesSQL, ','); // Insert image file name into database $insert = $link->query("INSERT INTO DB TABLE NAME (ticket_subject, ticket_message, file_name, ticket_status, user_name, user_id) VALUES $insertValuesSQL"); if($insert){ $to = "emailaddress"; $subject = "A new support ticket has been submitted"; $message = " <strong>$username</strong> has just created a support ticket, below is the support ticket <br /><br /> <u>Support Ticket Details</u> <br /><br> <strong>Support Ticket Subject</strong>: $ticket_subject <br/><br><strong>Support Ticket Message</strong>: $ticket_message <p><strong><u>Support Ticket Files</u></strong> <br> <img src='$fileName'> "; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n"; // More headers $headers .= 'From: <noreply@emailaddress>' . "\r\n"; $mail=mail($to,$subject,$message,$headers); $errorUpload = !empty($errorUpload)?'Upload Error: '.trim($errorUpload, ' | '):''; $errorUploadType = !empty($errorUploadType)?'File Type Error: '.trim($errorUploadType, ' | '):''; $errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType; header("location: support-ticket-confirmation?user=$username"); }else{ $statusMsg = "Sorry, there was an error uploading your file."; } } }else{ $statusMsg = 'Please select files to upload.'; } // Display status message echo $statusMsg; } ?> The structure of the db table column is file_name, VARCHAR(255), latin1_swedish_ci, NOT NULL Have a web page that displays a number of update forms depending on the amout of records that get returned from a mysql query, if query returns 4 records then the page will display 4 identical forms, the trouble i'm having is getting the each of the 4 forms to display a different record as at the moment they all show just first record of query. I have played around with loops but not getting anywhere which may be due to my limited knowledge code for page is below Code: [Select] <?php $numberofrow =mysql_num_rows($Recordset1); for($counter = 1;$counter<=$numberofrow;$counter++){ ?> <label for="hometeam2"></label> <form id="form1" name="form1" method="POST" action="<?php echo $editFormAction; ?>"> <label for="hometeam"></label> <input name="fixid" type="text" id="fixid" value="<?php echo $row_Recordset1['FixtureID']; ?>" /> <input name="hometeam" type="text" id="hometeam2" value="<?php echo $row_Recordset1['hometeamname']; ?>" /> <label for="homescore"></label> <input name="homescore" type="text" id="homescore" value="<?php echo $row_Recordset1['homescore']; ?>" /> <label for="awayscore"></label> <label for="fixid"></label> <input name="awayscore" type="text" id="awayscore" value="<?php echo $row_Recordset1['awayscore']; ?>" /> <label for="awayteam"></label> <input name="awayteam" type="text" id="awayteam" value="<?php echo $row_Recordset1['awayteamname']; ?>" /> <input type="submit" name="update" id="update" value="Submit" /> <input type="hidden" name="MM_update" value="form1" /> Hi there, hope have some help. I have a form where a user select time and days of the week (monday, tuesday..) that he is available. The insert script works fine, it insert and the days of week he checked in the table, the only problme is when i try to update each of them.
I used this code above, but is not working, instead of updating/inserting days that is selected is inserting multi-records with the same day of the week value.
here it is:
foreach($weekDay as $DaysofWeek){ $sql_days = "UPDATE available SET day_time = '$day_time', week_day = '$DaysofWeek' WHERE user_id = '$id_user'"; $update_availability = mysql_query($sql_days); } Iam trying to access amazon API and iam receiving XML perfectly but now I dont know how to traverse all records as in the below example Iam having 3 records but can't travers the xml using foreach Loop Please help me out and tell me how to use foreach loop ?? Its urgent $search="9781439181799,9780393334296,9781605298627"; $result = $obj->getItemByUpc($search, "Books"); foreach($result->children() as $key ) { $data = $key->Items->Request->ItemLookupRequest->ItemId."<br/ >"; echo $data; } Moderator Edit: added [php] tags I want to add the result of a query to another table but every time i click on it, it only saves the first record, please help me check out my code
thanks
<?php // hide errors error_reporting(0); /* Include the Pear::Pager file */ include('mysql_connect.php'); //include of db config file include ('paginate.php'); //include of paginat page $per_page = 5; // number of results to show per page $result = mysql_query("SELECT * FROM users"); $total_results = mysql_num_rows($result); $row=mysql_fetch_assoc($result); $total_pages = ceil($total_results / $per_page);//total pages we going to have //while ($row=mysql_fetch_assoc($result)){ //-------------if page is setcheck------------------// if (isset($_GET['page'])) { $show_page = $_GET['page']; //it will telles the current page if ($show_page > 0 && $show_page <= $total_pages) { $start = ($show_page - 1) * $per_page; $end = $start + $per_page; } else { // error - show first set of results $start = 0; $end = $per_page; } } else { // if page isn't set, show first set of results $start = 0; $end = $per_page; } // display pagination $page = intval($_GET['page']); $tpages=$total_pages; if ($page <= 0) $page = 1; ?> <?php // hide errors error_reporting(0); $reload = $_SERVER['PHP_SELF'] . "?tpages=" . $tpages; echo '<div class="pagination"><ul>'; if ($total_pages > 1) { echo paginate($reload, $show_page, $total_pages); } echo "</ul></div>"; // display data in table echo "<table class='table table-bordered'>"; echo "<thead><tr><th>First Name</th> <th>Last Name</th> <th>Department</th> <th>Status</th></tr></thead>"; // loop through results of database query, displaying them in the table for ($i = $start; $i < $end; $i++) { // make sure that PHP doesn't try to show results that don't exist if ($i == $total_results) { break; } // echo out the contents of each row into a table echo "<tr> "; echo '<td>' . mysql_result($result, $i, 'firstname') . '</td>'; echo '<td>' . mysql_result($result, $i, 'lastname') . '</td>'; echo '<td>' . mysql_result($result, $i, 'department') . '</td>'; echo ' <td><a href="add_team.php?id='.$row['id'].'"> Add Team Member </a></td>'; } echo "</tr>"; // } // close table> echo "</table>"; // pagination ?> I have a basic pagination class, I have used on several pages of a site I am working on. It works fine on 3 of the pages, but when I try to use it on any other pages, or even a new blank page I wrote, it does not work. class Pagination { public $current_page; public $per_page; public $total_count; public function __construct($page=1, $per_page=20, $total_count=0) { $this->current_page = (int)$page; $this->per_page = (int)$per_page; $this->total_count = (int)$total_count; } public function offset(){ return ($this->current_page - 1) * $this->per_page; } public function total_pages(){ return ceil($this->total_count/$this->per_page); } public function previous_page(){ return $this->current_page - 1; } public function next_page(){ return $this->current_page + 1; } public function has_prev_page(){ return $this->previous_page() >= 1 ? true : false; } public function has_next_page(){ return $this->next_page() <= $this->total_pages() ? true : false; } That is the pagination class, and this is the code I use to call it, along with some debugging information I am using. if(isset($_GET['order'])){ $order = $_GET['order']; } else { $order = "id"; } if(isset($_GET['orderby'])){ $order_by = $_GET['orderby']; } else { $order_by = "ASC"; } $page = !empty($_GET['page']) ? (int)$_GET['page'] : 1; $per_page = 2; $sql = mysql_query("SELECT * FROM orders WHERE customerid = 4"); $result = mysql_fetch_array($sql); $total_count = mysql_num_rows($sql); //$total_count = Order::count_by_cust(4); $pagination = new Pagination($page, $per_page, $total_count); $sql = "SELECT * FROM orders WHERE customerid = 4 ORDER BY {$order} {$order_by} "; $sql .= "LIMIT {$per_page} "; $sql .= "OFFSET {$pagination->offset()}"; $orders = Order::find_by_sql($sql); echo "Page:" . $page . "<br />PerPage:" . $per_page . "<br />Total:" . $total_count . "<br />Total Pages:" . $pagination->total_pages(); ?> SOME FOREACH INFORMATION HERE <?php echo "Has Prev Page:" . $pagination->has_prev_page() . "<br />"; echo "Total Pages:" . $pagination->total_pages() . "<br />"; echo "Has Next Page:" . $pagination->has_next_page() . "<br />"; ?> <div id="pagination" style="clear: both; text-align: center;"> <?php if ($pagination->total_pages() > 1){ if ($pagination->has_prev_page() == 1){ echo "<a href=\"orders.php?search&uid={$order->customerid}&order={$order}&orderby={$order_by}&page="; echo $pagination->previous_page(); echo "\">« Previous</a>"; } for($i=1; $i<=$pagination->total_pages(); $i++){ if($i == $page){ echo " <span class=\"selected\">{$i}</span> "; } else { echo " <a href=\"orders.php?search&uid={$order->customerid}&order={$order}&orderby={$order_by}&page={$i}\">{$i}</a> "; } } if ($pagination->has_next_page() == 1){ echo "<a href=\"orders.php?search&uid=" . $order->customerid . "&order=" . $order . "&orderby=" . $order_by . "&page="; echo $pagination->next_page(); echo "\">Next »</a>"; } } ?> </div> The customer ID is dynamic, but for debugging sake I am using the customer ID of 4. The output of the page has the following informaton: Page:1 PerPage:2 Total:15 Total Pages:8 Has Prev Page: Total Pages:8 Has Next Page:1 So i know all the variables are right, the problem is, it only prints a bold "1". Thats all, no numbers, or Next Page option. However i use the EXACT same code in another couple pages, and it works fine, but with this current page and a few others. It does not work. I have also tryed extracting just this information into a blank file to just get the page numbers, taking out all the pages other code, and it still only gives me "1". Any ideas? <?php error_reporting(0); $servername = "localhost"; $username = "user"; $password = "pw"; $dbname = "news"; $datatable = "ttrss_user_labels2"; // MySQL table name $datatable2 = "ttrss_entries"; $results_per_page = 10; // number of results per page // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?> <?php if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; }; $start_from = ($page-1) * $results_per_page; $sql = "SELECT * FROM ".$datatable2.", ".$datatable." WHERE article_id = id ORDER BY date_entered DESC LIMIT $start_from, ".$results_per_page; $rs_result = $conn->query($sql); ?> <?php while($row = $rs_result->fetch_assoc()) { ?> <?php $title = preg_replace('/[^(\x20-\x7F)]*/','', $row['title']); $content = preg_replace('/[^(\x20-\x7F)]*/','', $row['content']); ?> <table id="news" border="1" cellpadding="1" class="mx-auto col-xs-12 col-sm-12 col-md-12 col-lg-12"> <tr class="wrap"><td class="rounded-lg shadow curved"> <?php echo '<div charset="UTF-16" class ="text-center" style ="font:14px/18px Arial,tahoma,sans-serif top:5px">', $title, '<hr class=mx-auto></div>'; ?> <?php echo '<div charset="UTF-16" class ="text-center" style ="font:11px/21px Arial,tahoma,sans-serif">', $content, ' ', '<a href= "' . $row['link'] . '" target=_blank>Read More</a>', '</div>'; ?> <div style ="font:9px/15px Arial,tahoma,sans-serif" class="text-right"><? echo date('F j, Y g:i a', strtotime($row["date_entered"])) ?><br></div> <? echo '</td></tr></table><br><br>'; ?> <?php }; ?> <!--Grid row--> <div class="row d-flex justify-content-center"> <!--Grid column--> <div class="top_menu col-xs-12 col-sm-12 col-md-12 col-lg-12"> <div class="container"> <div class="row"><div class="col-md-9"> <ul class="pagination pagination-sm pagination-centered"> <?php $sql = "SELECT COUNT(ID) AS total FROM ".$datatable2; $result = $conn->query($sql); $row = $result->fetch_assoc(); $total_pages = ceil($row["total"] / $results_per_page); // calculate total pages with results $firstPage = 0; // or 1, depending on your implementation $currentPage = (int)$_GET['page']; if ($currentpage != $total_pages) { $nextpage = $currentPage + 1; $prevpage = $currentPage - 1; echo "<li><a href='index.php?page=$prevpage'><<</a></li> "; // for ($i=1; $i<=$total_pages; $i++) { // print links for all pages for($i = $page + 1; $i <= min($page + 4, $total_pages); $i++) { echo "<li><a href='index.php?page=".$i."'"; if ($i==$page) echo " class='curPage'"; echo ">".$i."</a></li> "; }; echo "<li><a href='index.php?page=$nextpage'>>></a></li> "; // echo "<li><a href='index.php?page=$total_pages'>last</a></li></u><br><br>"; } ?> </div></div></div><div class="clearfix">
Hi fellow PHP coders, I have gotten stuck with this code a bit as I was trying to build my first pagination script. I am getting only the 10 latest results from the database on all result pages. I am not sure what exactly I did wrong in this code to make it show all the results database has to offer spanning across pages at a rate of 10 per page from most current first to the oldest. Anyone have any ideas what I am doing wrong here? Any suggestions are much appreciated.
Greetings All! New to PHP, and trying to learn as much as I can as quickly as I can for a client. I have been following some of Tutorials i understand most of it, but I still don't understand a few of the functions. Anyways, here is my problem. I am trying to combined the two tutorials (Pagination and Search Internal) but I seem to have myself in a loop... Code is as follows: Code: [Select] <?php $connect = mysql_connect("localhost","root","~~~~"); $db = mysql_select_db("~~~"); $button = $_GET['submit']; $search = $_GET['search']; if ($button) { if (strlen($search)<=0) echo "Please enter a keyword"; else { //explode our search terms $search_exploded = explode(" ",$search); foreach($search_exploded as $search_each) { //construct query $x++; if ($x==1) $construct .= "keywords LIKE '%$search_each%' OR vid_state LIKE '%$search_each%' OR users LIKE '%$search_each%' OR title LIKE '%$search_each%'"; else $construct .= " OR keywords LIKE '%$search_each%' OR vid_state LIKE '%$search_each%' OR users LIKE '%$search_each%' OR title LIKE '%$search_each%'"; } //eco out construct $construct = "SELECT * FROM video_url WHERE $construct"; $run = mysql_query($construct); $foundnum = mysql_num_rows($run); //max display per page $per_page = 3; //get start variable $start = $_GET['start']; //count records $record_count = $foundnum; //count max pages $max_pages = $record_count / $per_page; //may come out as decimal $pagenumbers = intval($max_pages) + 1; if (!$start) $start = 0; //setup previous and next variables $prev = $start - $per_page; $next = $start + $per_page; //show prev button if (!($start<=0)) echo "<a href='searchvideos.php?start=$prev'><img src='../images/texts/previous.png' border='0'></a> "; //show next button if (!($start>=$record_count-$per_page)) echo " <a href='searchvideos.php?start=$next'><img src='../images/texts/next.png' border='0'></a>"; //set variable for first page $i=1; for ($y=0;$y<$record_count;$y=$y+$per_page) { if($start!=$y) echo " <a href='searchvideos.php?start=$y'><span class='searchtext'>$i</span></a>"; else echo " <a href='searchvideos.php?start=$y'><span class='searchtext'> <font size='+1'><b>$i</b></font></span></a>"; $i++; } //show page numbers echo " / <font color='#FF6600' size='-1'>$pagenumbers</font> </td> <td align='right' width='50%'> <form action='../pages/searchvideos.php' method='get'> <span class='searchtext'>Search Videos</span> <input name='search' type='text' value='by Keywords, Title, Name, or State' size='35' /><input type='submit' name='submit' value='search' /> </form> </td> </tr> </table> </div> <br /><br /><div class='videotitle'><span class='createtext'> Videos </span></div> <br /><br />"; if ($foundnum==0) echo "No results found."; else { echo "$foundnum results found!<br><br>"; $query = mysql_query("SELECT * FROM video_url ORDER BY RAND() LIMIT $start, $per_page"); while($row = mysql_fetch_array($query)) //while ($numrows = mysql_fetch_assoc($run)) { $title = $row['title']; $url = $row['url']; $state = $row['vid_state']; $users = $row['users']; echo " <table bgcolor='#191919' cellpadding='0' cellspacing='0' background='../images/videobgs.png' align='center'> <tr> <td width='10px'></td> <td width='440px' height='370px' rowspan='6'> $url </td> <td width='340px' align='left'> <span class='createtext'>$title</span><hr /> $users<br /> $state </td> <td width='5px'></td> </tr> <tr><td> </td></tr> <tr><td> </td></tr> </table><br />"; } } } } ?> I know my code is dirty, and I have a lot to learn, and that I should probably be doing this a different way, but please try to correct the way I have it. Anyways..first page loads great, the search works great, the pagination works as it should (correct pages, correct page numbers, etc.). However, once I click on the "next" or the next "number" the next page is blank because the very first if statement throws a kink in my code... if ($button) - when continuing to the next page, a "$button" is not pressed and therefore doesn't continue the code, leaving the page blank. Any clues on how to fix this? I have tried combining the two in many different ways, this is the best i got so far... Thanks in advance, Phantaz I am having trouble showing reports for a given date range. Currently if I specify something like 11/03/2010 to 11/05/2010 I get results for all years within that month and day such as I may get results for 11/03/2008 11/03/2009 11/03/2010 11/04/2008 11/04/2009 11/04/2010 11/05/2008 11/05/2009 11/05/2010. I am using the following code $result = mysql_query("SELECT * FROM report WHERE date>='$date_begin' and date<='$date_end' ORDER BY 'date'",$db); I use the following format in my date feild mm/dd/yyyy My script is finally working as intended, but I want to add some additional data results. I am trying to resolve how I can display a count of ONLY the records updated by my query: // START :: Query to replace matches mysql_query("UPDATE orig_codes_1a AS a JOIN old_and_new_codes_1a AS b ON concat(a.orig_code_1, a.orig_code_2) = concat(b.old_code_1, b.old_code_2) SET a.orig_code_1 = b.new_code_1, a.orig_code_2 = b.new_code_2") or die(mysql_error()); // END :: Query to replace matches In this query I count ALL records selection: // START :: Create query to be displayed as final results of original codes table. $result = mysql_query("SELECT * FROM orig_codes_1a") or die(mysql_error()); I want to display a count on this part of the query: ....concat(a.orig_code_1, a.orig_code_2) = concat(b.old_code_1, b.old_code_2).... Hello, I'm working on a script which should read lines from a file keyword.txt create a new file with that variable name, insert the content close and loop through all the lines in the keyword file. The loop itself works but now that i'm adding the fopen fwrite and fclose i'm running into trouble. I'm not that great a coder and have pieced this together so far. I'd appreciate any suggestions on how to fix the fopen and other file functions to create unique files using the keywords from the file Thanks in advance <?php $read_file = file('keywords.txt'); foreach($read_file as $var) { $file = fopen($var, "x"); $content = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <html xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> <title>This is the title</title> </head> <body> <h2>The keyword is $var</h2> <p><p> </body> </html>"; fwrite($file, $content); fclose($file); } ?> Hi there, I have a form submitting to a mysql database. It was requested that I put a multiple file upload option on it. So I added the fields to the form and the database and added the upload script to the form processing file (and of course created the folder on the server with proper permissions to upload to). It should upload the file(s) to the folder on the server and insert the filename into the database. I keep getting: HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request. This leads me to believe the upload script isn't working properly. If someone could take a look at it I would be a very happy guy. This is the upload script: (insert.php) Code: [Select] <?php $con = mysql_connect("server","user","pass"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("db", $con); $dateSubmitted = date("Y-m-d"); $target = "attachments/"; $target = $target . basename( $_FILES['doc1']['name']); $target = $target . basename( $_FILES['doc2']['name']); $target = $target . basename( $_FILES['doc3']['name']); $target = $target . basename( $_FILES['doc4']['name']); $target = $target . basename( $_FILES['doc5']['name']); $sql="INSERT INTO investments (active, project, inv_amount, account_type, prefix, first_name, last_name, address1, address2, city, province, postal_code, country, phone, email, referral_fee, ref_agent, ship_name, ship_address, ship_city, ship_province, ship_postal, ship_country, notes, dateSubmitted, doc1, doc2, doc3, doc4, doc5) VALUES ('$_POST[active]','$_POST[account_type]','$_POST[project]','$_POST[inv_amount]','$_POST[prefix]','$_POST[prefix]','$_POST[first_name]','$_POST[last_name]','$_POST[address1]', '$_POST[address2]','$_POST[city]','$_POST[province]','$_POST[postal_code]','$_POST[country]','$_POST[phone]','$_POST[email]','$_POST[referral_fee]','$_POST[ref_agent]','$_POST[ship_name]','$_POST[ship_address]','$_POST[ship_city]','$_POST[ship_province]','$_POST[ship_postal]','$_POST[ship_country]','$_POST[notes]','$_POST[dateSubmitted]',$_FILES['doc1']['name'],$_FILES['doc2']['name'],$_FILES['doc3']['name'],$_FILES['doc4']['name'],$_FILES['doc5']['name'])"; //Writes the photo to the server if(move_uploaded_file($_FILES['doc1']['tmp_name'], $target)) if(move_uploaded_file($_FILES['doc2']['tmp_name'], $target)) if(move_uploaded_file($_FILES['doc3']['tmp_name'], $target)) if(move_uploaded_file($_FILES['doc4']['tmp_name'], $target)) if(move_uploaded_file($_FILES['doc5']['tmp_name'], $target)) { //Tells you if its all ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { //Gives and error if its not echo "Sorry, there was a problem uploading your file."; } if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } //echo "1 record added"; header("Location: ../forms.php"); mysql_close($con) ?> Thanks in advance. JE Im trying to search through the read column and see if any of the rows are read I echo $mail and it shows all the rows for the user. So im grabing the ones I want but now i dont know how to search through what I selected. Or is there a simplier way of having SQL do what im trying to do? Code: [Select] <?php $query = "SELECT `read` FROM pm WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'"; $results = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_assoc($results)) { $mail = $row['read']; } // checks if user has unread mail or not if ($mail == "unread") { echo '<td><b><a href="inbox.php?inbox=1">Messages</a></b></td><td id="diamond">♦</td>'; } else { echo '<td><a href="inbox.php?inbox=1">Messages</a></td>'; } ?> The first run of my for loop does not execute, but all after that works. I know I need to define my $strings before the for loop because they do not take effect until it has ran once and that is why it does not show the first run. But I don't completely understand how to solve the issue, and have tried everything to my knowledge. The code below imports a steam group page xml and gets the unique ids for each of the groups members, then retrieves information about members. <?php $groupxml = simplexml_load_file('http://steamcommunity.com/groups/MDK-Society/memberslistxml/?xml=1'); $members = $groupxml->memberCount; $array = $groupxml->members->steamID64; for($arraycount="0"; $arraycount<$members; $arraycount=$arraycount+1){ $xml = simplexml_load_file("http://steamcommunity.com/profiles/$array[$arraycount]/?xml=1"); echo "<a href=\"#\" title=\"<img src=$xml->avatarMedium align=right /> $xml->steamID<br />$xml->stateMessage<br /><br />Location: $xml->location<br />$xml->summary\"><img src=\"$xml->avatarMedium\" /></a>"; echo "<br>"; if ("$xml->onlineState" == "online") { echo "<img src=\"images/stateonlinemaster.png\" />"; } elseif ("$xml->onlineState" == "offline") { echo "<img src=\"images/stateofflinemaster.png\" />"; } else { echo "<img src=\"images/stateingamemaster.png\" />"; } echo "<br>"; echo "<br>"; } ?> Could you explain to me fully where I went wrong in the for loop. Thanks I'm starting to get peeved with PHP today, after many hours of trying to sort an issue - I'm sure you all know what I mean. Once again, the issue lies with foreach loops which I have never been able to fully understand, especially when dealing with multiple arrays. The code is for a CMS, where a restaurant owner can update his menu's and choose whether to show them on the website using a tick box. Here's a screenshot.. Essentially, the issue I am having is should I click say, the bottom tickbox and click Update it will for some reason, tick the second in the database.... In reverse, if all are ticked, and I untick the bottom, it will untick the box before it.... it is sooo frustrating.. From what I can see, it is likely to be where the array, where ticked boxes have a value, and non-ticked ones don't... but I tried to sort this in my foreach loop setting an empty value to off.... Here is the HTML code: Code: [Select] <form action="./includes/scripts/menus/update.php" enctype="multipart/form-data" method="post"> <button type="submit" onclick="return confirm('Updating Menu Changes...\n\nUpdating PDF files may time some time.. \n\nDo not navigate away from this page until you recieve a success or failure confirmation.\n\nClick Cancel to make changes.'); { return alert('noob'); }">Update Menu Changes</button> <button type="button" onClick="document.location.href='./includes/scripts/menus/new_row.php'">Add New Menu Item...</button> <br /><br /> <table border="0" width="962" cellpadding="0" cellspacing="0"> <tr style="padding-bottom: 3px;"> <th style="text-align: center;" width="195.4">Active</th> <th style="text-align: center;" width="195.4">Menu</th> <th style="text-align: center;" width="195.4">Current Menu</th> <th style="text-align: center;" width="195.4">Change Menu (PDF format only)</th> <th style="text-align: text-align: center;" width="195.4">Tasks</th> </tr> <? $query = "SELECT * FROM menus ORDER by id ASC"; $query = mysql_query($query) or die(mysql_error()); //Count rows $num_rows = mysql_num_rows($query); //If no rows exist if($num_rows=="0") { ?> <tr style="padding-bottom: 3px;"> <td colspan="4" style="text-align: center;">There are currently no menus listed in the Pen Mill Hotel database.</td> </tr> <? } //If new rows exist elseif($num_rows!=="0") { $i = "0"; while($row=mysql_fetch_array($query)) { //Database Variables $name = $row["menu"]; $id = $row["id"]; $location = $row["location"]; //Establish if a menu is present in database for current entry if(empty($location)) { $current = "<a style=\"cursor: pointer;\" onclick=\"alert('No menu found!');\" title=\"View Listed Menu\">View Current Menu</a>"; } elseif(!empty($location)) { $current = "../includes/menus/" . $row["location"]; $current = "<a href=\"$current\" title=\"View Listed Menu\" />View Current Menu</a>"; } //Establish whether to check tickbox or not. $active = $row["active"]; if($active=="on") { $active = " checked=\"checked\" "; } elseif($active!=="on") { $active = " "; } ?> <tr style="padding-bottom: 3px;" id="<? echo "$id"; ?>"> <td style="text-align: center;"> <input type="checkbox"<? echo "$active"; ?>name="active[<? echo "$i"; ?>]" /> </td> <td style="text-align: center;"> <input type="text" style="padding: 0px;" name="name[]" value="<? echo "$name"; ?>" /> </td> <td style="text-align: center;"> <? echo $current; ?> </td> <!-- Tell PHP, max file size is equal to 5MB (in bytes) --> <input type="hidden" name="MAX_FILE_SIZE" value="5242880" /> <td style="text-align: center;"><input type="file" name="menu_file[]" /></td> <td style="text-align: center;"> <a href="./includes/scripts/menus/delete.php?id=<? echo "$id"; ?>" onclick="return confirm('Are you sure you wish to delete this menu?\n ');"> Delete </a> </td> </tr> <input type="hidden" name="id[]" value="<? echo $id; ?>" /> <? $i++; ?> <? } } ?> </table> <br /> <button type="submit" onclick="return confirm('Updating Menu Changes...\n\nUpdating PDF files may time some time.. \n\nDo not navigate away from this page until you recieve a success or failure confirmation.\n\nClick Cancel to make changes.');">Update Menu Changes</button> <button type="button" onClick="document.location.href='./includes/scripts/menus/new_row.php'">Add New Menu Item...</button> </form> And here is the PHP, baring in mind it will also deal with a file upload, but that isn't the issue at the moment... Code: [Select] <? /* This script is for use on the Manage Menu's pages and updates all menu items. */ /*==================================*/ /* DATE BASE CONFIGURATION */ /*==================================*/ include_once "../../config/config.php"; /*==================================*/ /* SET VARIABLES */ /*==================================*/ $id = $_POST["id"]; $active = $_POST["active"]; $name = $_POST["name"]; $menu_file = $_FILES['menu_file']; $i = "0"; /*==================================*/ /* Loop Each Menu & Update */ /*==================================*/ foreach($id as $key) { //Set Sub Variables if(empty($active["$i"])) { $active["$i"] = "off"; } $active_post = $active["$i"]; $name_loop = $name["$i"]; //Set File Variables $file_name = $menu_file["name"]["$i"]; //name of file on users machine $file_type = $menu_file["type"]["$i"]; //type of file being uploaded $file_size = $menu_file["size"]["$i"]; //size of the uploaded file in bytes $file_error = $menu_file["error"]["$i"]; //returned PHP error codes for upload $file_temp = $menu_file["tmp_name"]["$i"]; //temporary name on server //Handle Uploaded File (if uploaded) if(!empty($file_name)) { //FILE ERROR CHECKS //If file type is not PDF. if($file_type!=="application/pdf") { $pass = "0"; header("Location: ../../../index.php?page=Menus&error=Incorrect_File_Type"); } //If file type is greater than 5MB. if($file_size>"5242880") { $pass = "0"; header("Location: ../../../index.php?page=Menus&error=Incorrect_File_Size"); } //If above error checks pass if($pass!="0") { //Get todays date for file rename $today = date("d-m-Y"); $uploaddir = "/home/penmillh/en/includes/menus/"; $upload_name = str_replace(" ", "", $name_loop) . $today . ".pdf"; $uploadfile = $uploaddir . $upload_name; //Move file only if PHP upload status is correct if($file_error!="UPLOAD_ERR_OK") { header("Location: ../../../index.php?page=Menus&error=File_Upload_Error"); } //If PHP status is okay, upload file and update table. if($file_error=="UPLOAD_ERR_OK") { //Upload move_uploaded_file($file_tmp, $uploadfile); //Update Database $query = "UPDATE menus SET active='$active', menu='$name_loop', location='$upload_name' WHERE id='$value'"; $query = mysql_query($query) or die(mysql_error()); header("Location: ../../../index.php?page=Menus&error=File_Upload_Success"); } } } //If no uploaded file, update database records if(empty($file_name)) { //Update Database $query = "UPDATE menus SET active='$active_post' WHERE id='$key'"; $query = mysql_query($query) or die(mysql_error()); // header("Location: ../../../index.php?page=Menus&error=Menu_Change_Success"); } $i++; } ?> Now, I have probably made this INCREDIBLY complicated, but that's all I could remember from my previous experience with foreach loops.... Any ideas? Hi all. How do I loop the below script? $query_basket = mysql_query("SELECT * FROM `store_basket` WHERE sessionid='".$sessionid."'"); $rows = mysql_num_rows($query_basket); $r = mysql_fetch_array($query_basket); $allitems = $rows; while($result_basket = mysql_fetch_array($query_basket)) { $price_without_tax = $result_basket['price']; $tax = 17.5; $price_with_tax = $result_basket['price'] + $tax; $price_times_qty = $result_basket['price'] * $result_basket['qty']; $basket_item = $result_basket['item']; $basket_qty = $result_basket['qty']; $basket_initial1 = $result_basket['initial1']; $basket_initial2 = $result_basket['initial2']; $basket_initial3 = $result_basket['initial3']; } if($allitems == 1) { $basket .= $allitems.":".$basket_item." ".strtoupper($basket_initial1)."-".strtoupper($basket_initial2)."-".strtoupper($basket_initial3).":".$basket_qty.":".$price_without_tax.":".$tax.":".$price_with_tax.":".$price_times_qty; } else { $allitems = $rows; $basket .= ":".$basket_item." ".strtoupper($basket_initial1)."-".strtoupper($basket_initial2)."-".strtoupper($basket_initial3).":".$basket_qty.":".$price_without_tax.":".$tax.":".$price_with_tax.":".$price_times_qty; } Basically if there is more than one row I need to loop the $basket string so that it shows the values for each item. Thanks Pete I am trying to recursively pull records from a database to write to a csv. There are three test rows of data in my table (and no not including the table headers). The only issue is i can’t seem to get my for loop to display all the records – it only displays the last 2 rows so i’m very confused. Anyone suggest why this isn’t working? Code: [Select] $num_rows = mysql_num_rows($export); for ($i=0; $i <= $num_rows; $i++ ) { $row = mysql_fetch_row($export); echo $row[1] . $row[2] . $row[3] . $row[4] . $row[5] . $row[6] ."<br/>"; echo $i; } Incidentally the query is just a fetch all from datasbase. Anyone see where i'm going wrong? Thanks, drongo |