Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
OK, I lied. I decided to read through the code. I'm surprised you are not getting any errors. One problem that I see right off is that your else/if are malformed. Each subsequent IF statement is "embedded" in the one before it. So, you would not have enough closing brackets. here is part of your IF/ELSE section with spacing added to see the structure: if($from == '') { print "You have not entered an email, please return and try again"; } else { if($company == '') { print "You have not entered a company name, please return and try again"; } else { if($name == '') { print "You have not entered a contact name, please return and try again"; } else { if($phone == '') { print "You have not entered a phone number, please return and try again"; } I think you meant to do something more like this: if($from == '') { print "You have not entered an email, please return and try again"; } elseif($company == '') { print "You have not entered a company name, please return and try again"; } elseif($name == '') { print "You have not entered a contact name, please return and try again"; } elseif($phone == '') { print "You have not entered a phone number, please return and try again"; }
-
Not to be rude, but I'm not going to read through all of that. But, if you were able to get the "default" setup to work then you can solve this yourself. Start with the default form. Then add some additional functionality you need. Test it. Does it still work? If so, add some more functionality you need. If not, find the error in the code you just added. By adding small bits of functinoality at a time you know exactly what code is causing the problem. When you add a whole bunch of functionality at one time there can be many different errors causing problems making debugging much more difficult.
-
How to check if mailto link has been pressed?
Psycho replied to davey10101's topic in PHP Coding Help
What?! JavaScript is needed to run AJAX. When the user clicks the link you already have all the information you need in the browser (i.e. JavaScript can access it). So, what benefit would there be in using AJAX to do a server-side call? You would only be having the client-side JavaScript sending information based on what the user clicked to a server page so that page can return back what? The same information it just sent? -
How to check if mailto link has been pressed?
Psycho replied to davey10101's topic in PHP Coding Help
Here is an example PHP script which dynamically creates the email links and includes JavaScript to populate a textarea based on which links are clicked. <?php $contacts = array ( 'Michael' => 'michael@domain.com', 'Jane' => 'jane@domain.com', 'Dave' => 'dave@domain.com', 'Linda' => 'linda@domain.com', 'Bob' => 'bob@domain.com' ); //Create email links $emailLinks = ''; foreach($contacts as $name => $email) { $emailLinks .= "<a href=\"mailto:{$email}\" onclick=\"addEmailToList('{$name}: {$email}');\">{$name}</a><br />\n"; } ?> <html> <head> <script type="text/javascript"> function addEmailToList($value) { var textareaObj = document.getElementById('emailList'); textareaObj.value += ((textareaObj.value)?'\n':'') + $value; return true; } </script> </head> <body> Send an email to the following people:<br /> <?php echo $emailLinks; ?> <br /><br /><br /> Email links clickd:<br /> <textarea id="emailList" style="width:300px;height:150px;"></textarea> </body> </html> -
How to check if mailto link has been pressed?
Psycho replied to davey10101's topic in PHP Coding Help
I think you have a disconnect between what PHP and JavaScript do. PHP is used to create the HTML output that is sent to the browser. The browser does not know or care "how" that HTML content is produced (flat file, PHP, ASP, etc.). JavaScript is included in the HTML code and allows functionality to occure within the browser. The fact that you create the text area in PHP has no relevance on whether you can implement JavaScript. You will just nclude the JavaScript code in the output created by the PHP code. I'll post an example in a sec. -
There are plenty of sources: http://lmgtfy.com/?q=php+create+thumbnail
-
Use the CSS @media property. You can them apply different styles to obects based upon the "media" that it is in. So, you can set a different "display" propert based upon whether the element is displayed in a browser or in the "print" media. So, for the elements you do not want printed give them a display value of "none" for the print media. There was a similar post which I replied to with example code: http://www.phpfreaks.com/forums/index.php/topic,289715.msg1372740.html#msg1372740
-
Thanks for pointing that out Andy, but it had no effect. If i comment out the 4 echo statements the image shows. It's either the text or image, never both. Are you sure about that? This is what is in the script above print "<img src=\"./uploads/{$_FILES['photo']['name']}"; Which will produce something like this <img src="./uploads/filename.jpg Since you don't close the src parameter (or the img tag), the browser gets confused. I'm guessing it works when you don't include the other echos because the browser is not seeing any other content after that so it "assumes" that is the end of the source and "fixes" the mistake. Change that line to this: print "<img src=\"./uploads/{$_FILES['photo']['name']}\" />"; Are you using IE for testing? If so, try switching to FF. IE has a habit of trying to "correct" malformed HTML. So, if you have errors in the HTML code it may look fine in IE, but not in other browsers. Also, when you have these types of error, it helps to look at the actual HTML produced. Trying to spot HTML errors in PHP code can be difficult.
-
The problem is that you are giving the input fields the same name (and it is not an array). Therefore only one value is passed. Just change the field name to be an array using square brakets, like so: <input type="hidden" readonly="readonly" name="goal_id[]" id="goal_id" value="<?php echo $row1['goal_id'];?>" size="12"/> Then in your receiving page, you can create one UPDATE query using the IN control: $idList = implode(',', $_GET['goal_id']); //Assumes numeric field $query = "UPDATE table SET filed='value' WHERE goal_id IN ({$idList})"; Also, you need to give every element a unique ID, you cannot use the same ID twice.
-
This is a slightly improved version of that function which can strip all the tags at once without a foreach loop. I also removed the section to handle <> in the value when passed as a string. I figured if the values can't include those when passing the values as an array then the same rules should apply when passing as a string. Instead, I modified it to allow multiple values to be passed in a single comma separated string: <?php function strip_only($str, $tags) { if(!is_array($tags)) { $tags = explode(',',$tags); } $tagsPattern = implode('|', $tags); return preg_replace("#</?({$tagsPattern})[^>]*>#is", '', $str); } $str = ' <br><br><span id="1.612802118875386"><b>Other Page: </b>Matte Card<br><b>Gramage: </b>80 gram<br>sdafsdaf<br> <a href="#" onclick="removetext(1.612802118875386)"> Remove </a> </span><br><br><span id="1.014127052347593"><b>Other Page: </b>Matte Card<br><b>Gramage: </b>100 gram<br>sdfasfsdfdsfsdafsdafas<br> <a href="#" onclick="removetext(1.014127052347593)"> Remove </a> </span>'; echo strip_only($str, 'span,a'); // OR echo strip_only($str, array('span', 'a')); ?>
-
I responded to you in the PM you sent. What you are asking seems pretty simple, and I would be happy to do it for you. But, before I do anything let me know exactly what you want done so I can see what would be involved. Also, there are other problems with your script that shoud be addressed. For instance you are creating output before your BODY tag.
-
echo "<input type=\"checkbox\" name=\"checkfiles[]\" value=\"$file\" checked=\"checked\" />$file<br />\n";
-
Just to pile on to what Teamatomic is saying: PHP does not do any client-side, real-time functionality such as checking/unchecking checkboxes, enabling/disabling fields, etc., etc. The only way you could do it with PHP is to have the user submit the page (such as a "check all" button as teamatomic stated) and then determine the action the user selected and then resend the page to the user with the appropriate controls modified. It's a waste of time and the it will be a poor experience for the user. Client-side functionality such as this is exactly what JavaScript is for.
-
One thing you can do to really improve the performace of this script would be to remove everything from within the loop that does not need to be there. For example, there is no need to redefine these variables with the same values on every iteration of the loop // From email address $from = "xxxxxx"; $from_name = "xxxxxx "; Define them before the loop. But, what will help the most will be to remove the UPDATE query from within the loop. Instead save the $tomail variables to an array and then run a single update query at the end. In fact you should only mark a record as processed if the mail sends without error. Something like this: $processed = array(); while($row = mysql_fetch_array($objRSm, MYSQL_ASSOC)) { //Do some stuff if (mail($tomail, $subject, $mailmessage, $headers)) { $processed[] = $tomail; } //Do some more stuff } //end loop //Single update query for all processed records $upd = "UPDATE maillist SET sent='6' WHERE email IN ('" . implode("', '", $processed) . "')"; As for echoing every 100 records to the page, you are apparently using the id field as the counter. Not sure what data you actually have in your database, but it is perfectly possible that you don't have the id numbers that you think you do.
-
Don't quite get Returning Values By Value script
Psycho replied to co.ador's topic in PHP Coding Help
Pretty much. Look at the link I posted. The first example should give you a perfect idea of how it works. -
sort by last name comma delimited .txt file and display resluts
Psycho replied to briankopy's topic in PHP Coding Help
@teamatomic: Not sure where you were going with that, but it doesn't sort by last name. The asort() is sorting the lines as an entire sting and the string begins with the first name. The OP wants to sort by last name. @OP: This is tested: Just read the data into a multidimensional array and then create a custom function to use with usort() to sort in any manner you wish. The example below will sort by last name and then by first name (if the last names are the same). You can add as many sub sorts as you wish. <?php $dataFile = "data.csv"; //The data file to read $contactData = array(); //Array to hold the results //Array of keys to apply to each line of data $keys = array('first', 'last', 'street', 'city', 'state', 'zip', 'area', 'phone'); //Read CSV and put into multi-dimensional array if (($handle = fopen($dataFile, 'r')) !== FALSE) { while (($contactLine = fgetcsv($handle, 1000, ",")) !== FALSE) { //Trim values and add to output array $values = array_map("trim", $contactLine); $contactData[] = array_combine($keys, $values); } fclose($handle); } //Create function for sorting output array function sortContacts($a, $b) { //Sort by last name if different if ($a['last']!=$b['last']) { return strcmp($a['last'], $b['last']); } //Sort by first name if different if ($a['first']!=$b['first']) { return strcmp($a['first'], $b['first']); } return 0; } //Sort the array using custom function above usort($contactData, 'sortContacts'); //Ouput the results echo "<pre>"; print_r($contactData); echo "</pre>"; ?> -
Don't quite get Returning Values By Value script
Psycho replied to co.ador's topic in PHP Coding Help
Edit: Nightslyr beat me to it, but I'll post this anyway: This is all about variable scope. The process above is pretty strait-forward. When you set $num = 10 it is done outside of any function so it has "global" scope. When you are then IN a function that variable is not directly available. FOr example, if you defined $num inside a function it is a different instance of $num. However, you can reference global variables in a couple of ways. 1. Initiate the gloabl variable within the function function name() { global $num; } In that case $num inside the function is the same variable as $num outside the function 2. Using $GLOBALS keyword as in the script above. It is an associate array of all the gloabl variables. So, since $num was defined outside the function it is gloabl and you can reference it inside a function, any function, using $GLOBALS['num'] See the manual here: http://php.net/manual/en/reserved.variables.globals.php Although I agree that function looks to be a bad idea, but is constructive for understanding the behavior -
What? Not at all. In fact I typically separate my logic in one file and the HTML in another file. Just put an include at the end of the PHP section with the file with the HTML code.
-
So, do some basic debugging to find the problem: - Echo the query to the page to see if it looks correct. - Test the query in PHP admin to ensure it returns results or echo mysql_num_rows() to see how many records are displayed. See what those return and then go from there.
-
Getting the data will be easy, the problematic issue is displaying the results because the number of columns will be determined by the Account with the most Formats and that is not known until you have processed all the records. In other words, when you create the first row you won't know how many columns to create. So, you may need to pre-process the data from the query first. One thing I don't understant is what the totals at the bottom are supposed to represent. The ones on the right will be the total of all formats for an account, but the totals at the bottom don't mean anything because they will change based upon the order of the formats listed for each account. Anyway, see what this does for you (not tested): <?php //Query the data $query = "SELECT s.Account, o.Format FROM tblSchools s JOIN tblOrders ON o.SystemName = s.SystemName ORDER BY s.Account, o.Format"; $result = mysql_query($query) or die(mysql_error()); //Put data into array $accountData = array(); while($row = mysql_fetch_assoc($result)) { if(!isset($accountData[$row['Account']])) { $accountData[$row['Account']] = array(); } $accountData[$row['Account']][] = $row['Format']; } //Determine maximum formats $maxFormats = 0; foreach($accountData as $accountFormats) { if(count($accountFormats)>$maxFormats) { $maxFormats = count($accountFormats); } } //Create the header row $tableOutput .= "<tr>\n"; $tableOutput .= "<th></th>\n"; for($i=0; $i<$maxFormats; $i++) { $tableOutput .= "<th>Format {$i}</th>\n"; } $tableOutput .= "<th>Total</th>\n"; $tableOutput .= "</tr>\n"; //Create the data rows $columnTotals = array(); $tableOutput = ''; foreach($accountData as $account => $accountFormats) { $subTotal = 0; $tableOutput .= "<tr>\n"; $tableOutput .= "<th>{$account}</th>\n"; for($i=0; $i<$maxFormats; $i++) { $format = ''; if (isset($accountFormats[$i])) { $format = $accountFormats[$i]; $subTotal += $accountFormats[$i]; $columnTotals[$i] += $accountFormats[$i]; } $tableOutput .= "<td>{$format}</td>\n"; } $tableOutput .= "<td>{$subTotal}</td>\n"; $tableOutput .= "</tr>\n"; } //Create the bottom total row $tableOutput .= "<tr>\n"; for($i=0; $i<$maxFormats; $i++) { $tableOutput .= "<td>{$columnTotals[$i]}</td>\n"; } $tableOutput .= "<td>" . array_sum($columnTotals) . "</td>\n"; $tableOutput .= "</tr>\n"; ?> <html> <head></head> <body> <table> <?php echo $tableOutput; ?> </table> </body> </html>
-
OK, I did not have your database so some of the coding had to be done without testing. I tried to make the query be "flexible" but must have created an error when doing so. One of the queries is failing. The code above is apparently being included in another file, correct? Because the line number in the error (line 304) is greater than the line numbers above. You need to figure out which query is failing and why. The code doesn't have any error handling for query failures and it should - but that was outside the context fo this post. There are two lines where you actually run queries. Change both of them as indicated. die() is not recommended for "normal" debugging in a production script, but is fine for on-the-fly debugging such as this. Change this: $result = mysql_query($query); To this: or die ("Query:<br />{$query}<br />Error:<br />".mysql_error()); Also, I see another error. Change this: $total_records = mysql_fetch_assoc($result); $total_records = $result['num']; To this: $result_row = mysql_fetch_assoc($result); $total_records = $result_row['num'];
-
MIght I also suggest that for the query you only match the beginning of first name or last name instead of anywhere in the string? This is typical when doing name searches. For example, I did a seach for last name with the letter "D" expecting all the results where the last name began with "D". Instead I got results for all records where "D" was included anywhere in the last name, such as "Ward".
-
You should never be using die() when there are validation errors. You should separate the logic from the presentation in your code. Do all the PHP code up front and THEN create the output. The only PHP code that should be interspersed in the HTML is simple echo commands for output text you generate in the logic. Here is a rewrite of your page. See if this works for you. Notice the separatation of the logic at the top of the page and the output at the bottom When following this process you can separate the logic and the output into separate files. Make the managemetn and upkeep much simpler. NOTE: I did not test this, so there may be some syntax errors. <?php $error_msg = ''; $fname = ''; $lname = ''; if (isset($_POST['first']) || isset($_POST['last'])) { //User submitted a search query $fname = trim($_POST['first']); $lname = trim($_POST['last']); if(empty($lname)) { //No last name entered $validationError = "Please enter a last name"; } else { //Perform the database search mysql_connect("antondad.db.4161444.hostedresource.com", $username, $password); @mysql_select_db($database) or die( "Unable to select database"); $sql_fname = mysql_real_escape_string($fname); $sql_lname = mysql_real_escape_string($lname); $query="SELECT block, plot, first, last FROM names WHERE last LIKE '%{$sql_lname}%' AND first LIKE '%{$sql_fname}%'"; $result=mysql_query($query); if(!$result) { $error_msg = "Database error occured."; } elseif(mysql_num_rows($result)==0) { $error_msg = "Sorry, no results found."; } else { $recordResults = ''; while ($record = mysql_fetch_assoc($result)) { $recordResults .= " <tr>\n"; $recordResults .= " <td><class=\"body\">{$record['block']}</font></td>\n"; $recordResults .= " <td><font face=\"Arial, Helvetica, sans-serif\">{$record['plot']}</font></td>\n"; $recordResults .= " <td><font face=\"Arial, Helvetica, sans-serif\">{$record['first']}</font></td>\n"; $recordResults .= " <td><font face=\"Arial, Helvetica, sans-serif\">{$record['last']}</font></td>\n"; $recordResults .= " </tr>\n"; } } mysql_close(); } } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Eugene Pioneer Cemetery</title> <script type="text/javascript" src="js/nav_buttons.js"></script> <LINK rel="stylesheet" type="text/css" href="css/ds.css"> </head> <body bgcolor="#EEEEEE"> <table align="center" cellpadding="0" cellspacing="0" width="891" border="0"> <tr> <td align="center" class="form" valign="top"> WHOLE BUNCH OF HTML<img src="img/TP_pixel.gif" width="1" height="10" border="0" alt=""> <div style="color:#ff0000;"> <p style="color:#ff0000;"><?php echo $error_msg; ?></p> <form action="record.php" method="post"> <div align="left"> <img src="img/TP_pixel.gif" width="280" height="1" border="0" alt=""> First Name:<img src="img/TP_pixel.gif" width="105" height="1" border="0" alt="">Last Name: </div> <input type="text" name="first" value="<?php echo $fname; ?>" /> <img src="img/TP_pixel.gif" width="20" height="1" border="0" alt=""> <input type="text" name="last" value="<?php echo $lname; ?>" /><br /> <img src="img/TP_pixel.gif" width="1" height="30" border="0" alt=""><br> <input type="submit" name="submit" value="Submit" /> </form> </td> </tr> <tr> <td align="center"> <table border="1" cellspacing="2" cellpadding="2" align="center"> <tr> <th><font face="Arial, Helvetica, sans-serif">Block</font></th> <th><font face="Arial, Helvetica, sans-serif">Plot</font></th> <th><font face="Arial, Helvetica, sans-serif">First Name</font></th> <th><font face="Arial, Helvetica, sans-serif">Last Name</font></th> </tr> <?php echo $recordResults; ?> </table> </td> </tr> </table> </body> </html>
-
Hmm... the style property for direction:rtl appeared to foul up the Next/Prev links. The double arrows had a different page number than the word. Very odd. I even checked the HTML output and it made no sense. I had to take it out. Anyway, that script is much, much more complex than it needs to be. I have rewritten it to be much more elegant. All the configuration variables are at the top. There is now one for direction. Change it from a 1 to a -1 to make it go from right to left. <?php //Configuration variables $tbl_name="class"; //your table name $targetpage = "result.php"; //your file name (the name of this file) $limit = 1; //how many items to show per page $adjacents = 2; // How many adjacent pages should be shown on each side? $beginend = 2; //Number of pages to always show at beginning & end $direction = -1; //Direction: 1 = forward, -1 = reverse $next_text = "Next »"; $prev_text = "« Prev"; //Default query $default_query = "SELECT [FIELD_LIST] as num FROM class WHERE $category_sql AND $type_sql AND $area_sql AND $rooms_sql AND $preco_between AND $day_sql"; //Get total number of records $query .= str_replace("[FIELD_LIST]", "COUNT(*) as num", $default_query); $result = mysql_query($query) $total_records = mysql_fetch_assoc($result); $total_records = $result['num']; // Determine total pages $total_pages = ceil($total_records/$limit); //total pages = total pages / items per page, rounded up. //Determine current page $page = (int) $_GET['page']; if ($page==0 || $page>$total_pages) { $page = 1; //if no page is given or > total pages, default to 1. } // Get data for current page $limit_start = ($page - 1) * $limit; //first item to display on this page $query .= str_replace("[FIELD_LIST]", "*", $default_query) . " LIMIT $limit_start, $limit"; $result = mysql_query($query); //Now we apply our rules and draw the pagination object. //We're actually saving the code to a variable in case we want to draw it more than once. function createPageLink($baseLink, $linkText, $pageNum=false) { if($pageNum) { $link = "<a href=\"$baseLink&page=$pageNum\">{$linkText}</a>\n"; } else { $link = "<span class=\"disabled\">{$linkText}</span>\n"; } return $link; } $pagination_link="{$targetpage}?category={$category}&type={$type}&area={$area}&rooms={$rooms}&preco1={$preco1}&preco2={$preco2}$day={$day}"; if($total_pages > 1) { //pages $loopStart = ($direction==1) ? 1 : $total_pages; for($counter=$loopStart; $counter>0 && $counter<=$total_pages; $counter=$counter+$direction) { //Add ellipses at beginning if needed if ( ($counter > $beginend) && ($counter < ($page-$adjacents)) ) { $page_links .= createPageLink('', "...\n", false); $counter = ($direction==1) ? ($page-$adjacents) : $beginend; } //Add ellipses at end if needed if ( ($counter > ($page+$adjacents)) && ($counter < ($total_pages-$beginend+1)) ) { $page_links .= createPageLink('', "...\n", false); $counter = ($direction==1) ? ($total_pages-$beginend+1) : ($page+$adjacents); } //Add page link $page_links .= createPageLink($pagination_link, $counter, (($counter!=$page)?$counter:false)); } //previous/next buttons $prev_bttn = createPageLink($pagination_link, $prev_text, (($page>1)?($page-1):false)); $next_bttn = createPageLink($pagination_link, $next_text, (($page<$total_pages)?$page+1:false)); //Create pagination div $pagination.= "<div class=\"pagination\" style=\"direction:; float:right;\">\n"; //Add prev/next buttons and page links if($direction==1) { $pagination .= $prev_bttn . $page_links . $next_bttn; } else { $pagination = $next_bttn . $page_links . $prev_bttn; } //End pagination div $pagination.= "</div>\n"; } echo $pagination; ?>
-
Really? That would produce an error after the first iteration of the loop. :-\