[PHP] PHP access of FileMaker data
Can someone please point me to some PHP code or documentation for accessing FileMaker Pro tables with PHP? So far googling Zend and world-wide hasn't found me what I'm seeking. Thanks, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP access of FileMaker data
Thanks Daniel. However, as soon as I started reading the fx-php documentation I ran into this: FX.php is a PHP class which parses the XML output by FileMaker Pro's web companion... The FM Web Companion is another whole ball of wax and appears to be a live agent running on the server hosting the FileMaker tables. Is this right? Can you help demystify this for me? What I'm really looking for is a PHP class that will read FileMaker files in their native format. I'm beginning to suspect that none exists in the public arena. Someone please tell me there is! Regards, Paul At 11/12/2007 03:04 PM, Daniel Brown wrote: On Nov 12, 2007 5:58 PM, Paul Novitski [EMAIL PROTECTED] wrote: Can someone please point me to some PHP code or documentation for accessing FileMaker Pro tables with PHP? So far googling Zend and world-wide hasn't found me what I'm seeking. ... Back in 2004 I had a project that was to be a hybrid of PHP and FileMaker data, and I came across the perfect fit: FX.php by Chris Hansen. You can download the full source here: http://iviking.org/FX.php/ It had a mailing list of its own back then, too, which I was active on, but I'm no longer subscribed, and not even sure if it's still there. Either way, you'll find people like my friend, Gjermund Thorsen, still supporting the community on the script today, so you won't have to go it alone. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] PHP access of FileMaker data
At 11/14/2007 01:02 AM, George Pitcher wrote: Paul, What I'm really looking for is a PHP class that will read FileMaker files in their native format. I'm beginning to suspect that none exists in the public arena. Someone please tell me there is! ... I'm just exporting my tables (files rather than tables as I never upgraded beyong v5). Why not try that and then use PHP to transfer from the exported files into whatever you want? a) FileMaker is on my client's computer, not my own; b) it's going to be a frequent data transfer, not a one-time-only transform. My client is using an inventory management program in-house. Each time they modify their catalog inventory they need to upload the new dataset to the server so it will be reflected in their website. I'm writing the PHP software that converts their data to MySQL and then drives the website. The inventory application's native db format is FileMaker 8. The export function built into the inventory application can output XML and CSV which are easy for me to read in PHP, but when it does so it gloms various tables together in a pre-packaged join query that doesn't suit my purposes. The program is not built to export individual FM tables cleanly. What I really want is to be able to read each of the component tables (FileMaker files) and convert them to MySQL tables on the fly. The client is relatively unsophisticated and the most I can ask of them is to learn to use an FTP program to upload the FileMaker tables to the server. I don't want to ask them (or anyone) to run a conversion utility on a couple of dozen files before uploading. That's why I want to write a PHP script that can read the FM files. Ideally I'd like to be able to write to FM as well, but that's not crucial to the project. Ideas? Thanks! Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] help with multi dimensional arrays
Looks like you are missing a comma on line 3. James Lockie wrote: I get a syntax error on strlen. $newTypes = array(); $newTypes[0] = array(); $newTypes[0][0] = Starting with $newTypes[0][1] = strlen( $newTypes[0][0] ); Missing semicolon; Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Return or not to return, that is the question
At 5/30/2007 05:41 AM, Richard Davey wrote: /* check connection */ if (mysqli_connect_errno()) { printf(Connect failed: %s\n, mysqli_connect_error()); exit(); } If that was wrapped in a function, sticking 'return false' within the connect_error check is useful why exactly? Equally the fact the function didn't 'exit' implies it 'returned true' anyway, so why check it again in whatever called the function in the first place? it has performed its task, it didn't raise an error. (I know most of us would never use 'exit' in production code like the above, so replace it with whatever error handling mechanism you have, the question above remains the same.) I demur at your final point: If we don't use exit() and the function performs non-aborting error handling, it's going to return to the calling function which in most cases will need to know whether its child function succeeded or failed. In most of the applications I write, an SQL error (not merely an empty result set) indicates more often than not that the parent code should gracefully withdraw from the process it was attempting to perform. SQL errors are going to indicate a syntactical error in the query, a missing table or field, a connection failure, or another problem serious enough that the developer's attention should be drawn to it. It's certainly possible in a thoughtfully-written application for a parent function not to care whether a child SQL query was successful on this fundamental level, but in most apps we'll want to know. function parent() { lookUpData(); displayData(); } function lookUpData() { set up query; execute query; handle errors; } where handle errors might range from returning a failure flag to displaying an error message. In order that displayData() doesn't fall on its face, I would write the parent function in one of these ways: if (lookUpData()) displayData(); in which lookUpData() returns true or false, the record set being passed in a global variable (ugh); or, if displayData() is smart enough to deal intelligently with a null or empty result set: $aResultSet = lookUpData(); displayData($aResultSet); or: displayData(lookUpData()); in which lookUpData() returns a dataset array that's empty if no records were found or an error was encountered. In my programming style, I can't imagine wanting to write this code in such a way that lookUpData() didn't return some form of success or error indicator. Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re[2]: [PHP] Return or not to return, that is the question
At 5/30/2007 08:25 AM, Richard Davey wrote: In order that displayData() doesn't fall on its face, I would write the parent function in one of these ways: if (lookUpData()) displayData(); That's where our approach differs. If lookUpData falls flat on its face, my error handler will take over completely, finally resulting in an 'abortive' event, and never pass back to the parent. If an error is of a critical enough nature the system needs to stop. If it's not critical then the error handling within displayData() would detect it has nothing to display and error in its own accord. Hi Richard, If you write your applications like this then they'll fall over when something goes wrong -- and here I mean 'fall over' to mean aborting suddenly with a technical error message. That can be useful to us during development debugging but isn't really useful or friendly to the website visitor. It also gives every subroutine that handles errors the responsibility of deciding how to deal with the error -- whether to display it or not, how to display it, etc. It makes code less portable from one application to the next. Consider another model in which subroutines report errors back to the calling code but don't themselves 'act' on the errors. An error on a low level can bubble back up to some higher parent level in the application that knows what to do: whether to display and if so how and in what human language, whether to email the developer, whether to close down the application or continue, etc. An English SQL error message is of little use to a web page in Japanese. It's usually a mistake to display an SQL query in a public application because it exposes sensitive details of the database architecture. For example, we might want to generate the web page even if some part of its content is unavailable due to the SQL error. This leaves the visitor with a functional page from which they can navigate normally even if part of the content is missing. On this high level, the application might choose to behave nonchalantly as though SQL had returned an empty recordset and report the hard error to the webmaster behind the scenes. This kind of error-handling architecture can be handled in a variety of ways. One is to maintain a global error structure or class with a variety of fields that relate to the last error: true/false, error type, context, query code if applicable, etc. Because a low-level error may in turn trigger higher-level errors as it bubbles back up, it may make sense to turn this into an error stack to which each calling function adds its understanding of the problem as the error bubbles back up: 0: SQL error ZZZ in SELECT * FROM `users` ... 1: Can't query user list YYY 2: No users to display When a high-level function receives an error state from a called function, it can (if desired) walk down the stack to learn the technical origin of the error as well as its implications during the bubble-up. In my programming style, I can't imagine wanting to write this code in such a way that lookUpData() didn't return some form of success or error indicator. That's a *very* specific example though. My question was do people place a 'return' statement at the end of **ALL** of their functions, regardless of what that function actually did. In the code you gave there is a fair argument both ways, but that isn't always the case. Absolutely. I agree with most of the respondents to this thread: return a value only if the caller needs to receive a value back. Some languages (such as BASIC) distinguish between functions that return values and subroutines that don't. Because PHP gives only one type of function to call, with an option whether or not to return anything, it's clearly up to us to design and impose that architecture based on our knowledge and preferences. Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: Re[2]: [PHP] Return or not to return, that is the question
At 5/30/2007 10:51 AM, Richard Lynch wrote: On Wed, May 30, 2007 12:00 pm, Paul Novitski wrote: [snip] use the archives Good suggestion! HOWEVER: it is not a good idea, imho, to always let the errors bubble up to the outer layer, which is what Paul seemed to have typed... But didn't. The problem with that approach is that you end up being painted into a corner where your application can do little more than print It broke. because the low-level context is not available to the caller of the function. If you'll refer back to my posting to which you're replying without quoting, you'll read: At 5/30/2007 10:00 AM, Paul Novitski wrote: Because a low-level error may in turn trigger higher-level errors as it bubbles back up, it may make sense to turn this into an error stack to which each calling function adds its understanding of the problem as the error bubbles back up: ... When a high-level function receives an error state from a called function, it can (if desired) walk down the stack to learn the technical origin of the error as well as its implications during the bubble-up. It sounds like we're on the same page, Richard! Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: preg_match() returns false but no documentation why
On 5/30/07, Jim Lucas [EMAIL PROTECTED] wrote: The op will need to use something other than forward slashes. At 5/30/2007 03:26 PM, Jared Farrish wrote: You mean the delimiters (a la Richard's suggestion about using '|')? Hi Jared, If the pattern delimiter character appears in the pattern it must be escaped so that the regexp processor will correctly interpret it as a pattern character and not as the end of the pattern. This would produce a regexp error: /ldap://*/ but this is OK: /ldap:\/\/*/ Therefore if you choose another delimiter altogether you don't have to escape the slashes: #ldap://*# Cleaner and more clear. preg_match('|^ldap(s)?://[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$|', $this-server ) I also recommend using single quotes instead of double quotes here. Single Quotes: Noted. Any reason why? I guess you might be a little out of luck putting $vars into a regex without . concatenating. Both PHP and regexp use the backslash as an escape. Inside double quotes, PHP interprets \ as escape, while inside single quotes PHP interprets \ as a simple backslash character. When working with regexp in PHP you're dealing with two interpreters, first PHP and then regexp. To support PHP's interpretation with double quotes, you have to escape the escapes: Single quotes: '/ldap:\/\/*/' Double quotes: /ldap:\\/\\/*/ PHP interprets \\/ as \/ RegExp interprets \/ as / There's also the additional minor argument that single-quoted strings take less processing because PHP isn't scanning them for escaped characters and variables to expand. On a practical level, though, the difference is going to be measured in microseconds and is unlikely to affect the perceptible speed of a typical PHP application. So, for a pattern like this that contains slashes, it's best to use a non-slash delimiter AND single quotes (unless, as you say, you need to include PHP variables in the pattern): $pattern = '#ldap://*#'; Personally I favor heredoc syntax for such situations because I don't have to worry about the quotes: $regexp = _ #ldap://*$var# _; why is there a period in the second pattern? The period comes from the original article on SitePoint (linked earlier). Is it unnecessary? I can't say I'm real sure what this means for the '.' in regex's: Matches any single character except line break characters \r and \n. Most regex flavors have an option to make the dot match line break characters too. - http://www.regular-expressions.info/reference.html Inside of a bracketed character class, the dot means a literal period character and not a wildcard. All non-alphanumeric characters other than \, -, ^ (at the start) and the terminating ] are non-special in character classes PHP PREG Pattern Syntax http://www.php.net/manual/en/reference.pcre.pattern.syntax.php scroll down to 'Square brackets' Also, why are you allowing for uppercase letters when the RFC's don't allow them? I hadn't gotten far enough to strtolower(), but that's a good point, I hadn't actually considered it yet. Perhaps it has to do with the source of the string: can you guarantee that the URIs passed to this routine conform to spec? Another way to handle this would be to simply accept case-insensitive strings: |^ldap(s)?://[a-z0-9-]+\.[a-z.]{2,5}$|i Pattern Modifiers http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php i (PCRE_CASELESS) If this modifier is set, letters in the pattern match both upper and lower case letters. Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: Re: preg_match() returns false but no documentation why
At 5/30/2007 05:08 PM, Jared Farrish wrote: So what does the definition I posted mean for non-bracketed periods? Does it mean it will match anything but a line or return break character? How in practice is this useful? Read the manual: Pattern Syntax http://www.php.net/manual/en/reference.pcre.pattern.syntax.php . match any character except newline (by default) ... Full stop Outside a character class, a dot in the pattern matches any one character in the subject, including a non-printing character, but not (by default) newline. If the PCRE_DOTALL option is set, then dots match newlines as well. The handling of dot is entirely independent of the handling of circumflex and dollar, the only relationship being that they both involve newline characters. Dot has no special meaning in a character class. etc. How do you test regex's against any known variants? I suppose I need to build a test function to make arbitrary strings and then test and print the results. I just don't know if my regex is going to be that great in practice. rework - an online regular expression workbench by Oliver Steele http://osteele.com/tools/rework/ The RegEx Coach (a downloadable Windows application) by Edi Weitz http://weitz.de/regex-coach/ Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: Re: Re: preg_match() returns false but no documentation why
Hi Jared, At 5/30/2007 06:00 PM, Jared Farrish wrote: Read the manual: All due respect, I did read it. It's just... a little dense and not practically descriptive. Sorry, I didn't mean to be disrespectful, I thought your question was more elementary than it was. There are, though, a ton of regular expression resources on the net. Google Is Your Friend. I just got a million hits on 'regular expression tutorial.' Maybe it's more practical to ask, When is it practical to use it? It matches anything, so I assume that means you can use it to match, say, a paragraph that you can't predict or match against? One that you're looking for a pattern match on one or either end? Well, sure. It often appears as .* meaning none or any number of any characters. Use it when you honestly don't care what it matches. Say you want to find out if the word frog occus in a text followed by the word dog. You could match on: /\bfrog\b(.*\b)?dog\b/i / pattern delimiter \b word boundary frog1st word \b word boundary ( begin subpattern .* zero or any characters \b word boundary ) end subpattern ? zero or one instance of the preceding subpattern dog 2nd word \b word boundary / pattern delimiter i case-insensitive This guarantees that both words are bounded by word boundaries and allows any number of any characters to occur between them. (There's sort of an implicit .* before and after the pattern. Because I haven't used ^ and $ to define the beginning and end of the text, regex looks for my pattern anywhere in the text.) And why is it called full stop? That's what the 'period' is called in British English. http://google.ca/search?q=define%3Afull+stop In English syntax period and full stop are synonymous, and the RegEx manual is throwing dot into the same bag. Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] explode string at new line
At 6/5/2007 10:50 PM, Jim Lucas wrote: Windows uses \r\n newlines; *nix uses \n; Mac uses \r. ... PHP Code: $txt = preg_replace('/\r\n|\r/', \n, $txt); Another way to write that PCRE pattern is /\r\n?/ (one carriage return followed by zero or one linefeed). I recall also running into \n\r although I can't recall which system uses it. As an alternative to PCRE, we can pass arrays to PHP's replace functions, e.g.: $txt = str_replace(array(\r\n, \n\r, \r), \n, $txt); Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Updating dropdown list
At 6/11/2007 11:38 AM, Ashley M. Kirchner wrote: I have a page containing two drop down lists. I need to figure out a way to populate/update the second drop down list based on a selection of the first one (the data for both drop down lists is in a MySQL database). Is this something I need to do in JavaScript? Or can I somehow trick PHP to do this? I don't think you need to trick PHP -- it will be friendly and cooperative as long as you feed it some nice juicy strings from time to time. The main difference between implementing this in javascript and implementing it in PHP is that PHP will require a round-trip to the server between menu changes, while javascript will act more immediately. Because javascript is so commonly disabled, I write the logic first in PHP so that everyone can use the page, then again in javascript to enhance the experience for folks with scripting enabled. This is not a doubling of work: both scripts can utilize the same datasets (since PHP is downloading the page it can feed javascript a version of the same data it uses), and both scripts have very similar syntax (they're really cousins) so it's possible in many cases to write nearly identical logic in key functions, reducing programming, debugging, and maintenance time. This technique is known variously as 'unobtrusive javascript' and 'progressive enhancement.' Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Date Calculation Help
At 6/30/2007 08:14 AM, revDAVE wrote: I have segmented a year into four quarters (3 months each) nowdate = the month of the chosen date (ex: 5-30-07 = month 5) Q: What is the best way to calculate which quarter (1-2-3 or 4) the chosen date falls on? Result - Ex: 5-30-07 = month 5 and should fall in quarter 2 If you divide the month number by 3 you get: 1 0.3 2 0.7 3 1 4 1.3 5 1.7 6 2 7 2.3 8 2.7 9 3 10 3.3 11 3.7 12 4 The first digit is off by one, so subtract .1 from each result: 1 0.2 2 0.56667 3 0.9 4 1.2 5 1.56667 6 1.9 etc. Now you can see from the first digit that if you take the integer value and add 1 you'll get: 1 1 2 1 3 1 4 2 5 2 6 2 etc. In PHP this could be: intval(($month - .1)/3 + 1) or: intval(($month + .9)/3) I believe you can use intval() and floor() interchangeably in this circumstance. Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] PHP Brain Teasers
At 7/3/2007 12:11 PM, Jay Blanchard wrote: [snip] if($x == 0.01 || $x == 1.0){ $y = in; } [/snip] In for a penny, in for a pound. Metric, that is! Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: PHP Brain Teasers
At 7/5/2007 01:45 PM, Daniel Brown wrote: $objects-original_image = http://www.sewterific.com/images/Just%20Baskets/SmPicnicBasket.jpg;; $_SCRIPT[word] = task; $_SCRIPT[otherword] = ticket; $update_word1 = $_SCRIPT[word].et; $rgb1 = 134,89,32; $rgb2 = 231,223,48; $objects-paint($objects-original_image,$rgb1,$rgb2,$update_word1,str_replace(c,s,$_SCRIPT[otherword])); Without bothering to run the code I'd say a tisket, a tasket, a green and yellow basket. Now what obscure corner of childhood poetry memories did that come from? It's easy to google... My god, Ella Fitzgerald? THE Ella Fitzgerald?? Yowsa! Bemusedly, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Upload Tracker.
At 7/17/2007 11:46 AM, Tom Ray [Lists] wrote: I'm a little unsure on how to do this but basically when someone uses a form to upload a file I want to have a popup window come up and so the process in percentage of the transfer. Anyone do this before? Is it possible in PHP or do I need to do it in javascript or a mixture of both? Upload progress can't be reported using PHP alone, but here's a PHP-perl amalgam you can check out: Mega Upload http://www.raditha.com/php/progress.php I haven't used it can can't vouch for it. When I tried their demo it failed but I think for reasons other than the functionality of the widget itself. Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: Pirate PHP books online?
At 7/17/2007 07:42 PM, you wrote: Really people. I find it hard to believe that the otherwise-intelligent people on this list have such a hard time with the concept that something should not be done for reasons that don't involve physical property, just as I find it hard to believe that making up things that someone supposedly said has suddenly become the in thing to do. Larry, please relax a little and don't take these comments so personally. As you point out, most folks who have posted to this thread are not responding to what you've actually written. When you make the technical point that copyright infringement isn't the same as property theft, some people have misunderstood and thought you meant that copyright infringement isn't a bad thing. I suggest that their missiles aren't actually aimed at you, so just turn your head and watch them go by. They're really aimed at the violation of those intellectual property rights by which nearly everyone on this list survives, or tries to. Naturally it's a hot topic. But it's not about you. The issue of whether property theft and copyright infringement are governed by different legal codes is interesting to an extent but clearly separate from the issue of whether or not copyright infringement is an abhorrent practice. Since you clearly realize that folks are really addressing the latter issue, one with which you apparently agree, I suggest you let go of the fact that you contributed the former idea since almost no one is actually addressing it. So far you're shouting past them as much as they're shouting past you because you're all addressing different topics in a single thread. Warm regards, Paul __ Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Hide the real URL
At 7/26/2007 08:08 AM, M. Sokolewicz wrote: // output to browser, suppressing error message why are you suppressing error messages?? @readfile($Filename); http://php.net/readfile Reads a file and writes it to the output buffer. Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readfile(), an error message is printed. I figured that in the case of an image it would make more sense to download a FALSE value to the browser than a text error message. During development debugging phases error messages are invaluable, but after publication some circumstances dictate no display rather than display of a message. Since the OP was looking for a solution that obfuscated the image URL, I thought the less techy information communicated to the user the better. Richard Heyes' suggestion of using passthru() might work better if it can be used with a mixture of content types on the same page. And, yes, heredoc is definitely a matter of taste. In my own work, its disadvantage (hugging left margin) is outweighed by its advantages (separation of logic from data/template/output, omission of escape codes except the occasional {}, fewer typographical errors, faster proofreading, etc.). I don't feel the need to convince anyone else to use heredoc, but I'm totally sold on it myself. Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Hide the real URL
At 7/26/2007 06:18 AM, elk dolk wrote: I want to hide the real URL to my images It should be pointed out that you can't really hide the real URL of your images. If an image appears in a browser, the browser will accurately report its location to the user, and the user can save it to their hard drive. If you're in a situation in which you're trying to avoid people downloading images without permission, your best bets might be to watermark, crop, low-res-ify, or otherwise disfigure the displayed images to make them less attractive than the originals. Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Hide the real URL
At 7/26/2007 06:18 AM, elk dolk wrote: I want to hide the real URL to my images by masking it with PHP the code looks like this: $query = SELECT * FROM table; $result=mysql_query($query); while ($row = mysql_fetch_array($result)) { echo img src='http://www.mysite.com/img/{$FileName}'/; } if you look at the source in browser you will see: img src='http://www.mysite.com/img/111.jpg' / how can I show it like this: img src='show.php?FileName=111.jpg' / Your primary script would echo: while ($row = mysql_fetch_array($result)) { // get the file name from the data table $FileName = $row['filename']; // encode the filename to be legal in an URL $FileName = urlencode($FileName); // download to browser echo _ img src=show.php?FileName=$FileName / _; } and the secondary script show.php could use logic such as this: // if the querystring contains the expected parameter if (isset($_GET['Filename'])) { // get requested filename $Filename = 'img/' . $_GET['Filename']; // if that file exists if (file_exists($Filename)) { // output to browser, suppressing error message @readfile($Filename); } } Notes: Your sample script included: echo img src='http://www.mysite.com/img/{$FileName}'/; Marking up your images as img ... / indicates that you want to use XHTML. XHTML requires that attributes be quoted with double quotes, not single quotes (apostrophes). Use http://validator.w3.org/ to validate your markup. However, simply reversing the quotes in your statement would result in: echo 'img src=http://www.mysite.com/img/{$FileName}/'; This would not work because PHP would fail to expand the variable name inside single quotes. Therefore you'd need to escape the inner quotes like so: echo img src=\http://www.mysite.com/img/{$FileName}\/; or use heredoc (...) which I prefer to use because it means not having to escape the quotes. In a case like this it also means not having to enclose the variable in curly braces: echo _ img src=show.php?FileName=$FileName / _; urlencode: http://php.net/urlencode heredoc syntax: http://php.net/heredoc#language.types.string.syntax.heredoc isset: http://php.net/isset file_exists: http://php.net/file_exists readfile: http://php.net/readfile @ Error Control Operator: http://php.net/@ Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Hide the real URL
At 7/26/2007 08:40 PM, Chris Aitken wrote: There's a couple of protect your image schemes that will frustrate the typical user, but they can be easily broken, like the one I created here: http://www.webbytedd.com/b/protect_image/ Firefox - Tools - Page Info - Media - Scroll Till Find - Bingo! Say Firefox to a typical user and they will assume you are swearing at them in another language. ... Typical users don't even KNOW they have a printscreen button just like most typical users don't know there is ANOTHER kind of browser :) That said, I don't think the hypothetical typical clueless user is relevant here. A user who really wants to scrape images off websites will find a way with very little effort -- just google and a few clicks -- to view background images, to view page source, to disable javascript disabling of context menus, to install Firefox and the web developer toolbar, whatever; it's all within easy reach of anyone with motivation and average intelligence. Sure, you can make it difficult for X% of computer users to locate your images, but those aren't the people you're worried about, it's the Y% who don't take no for an answer and try, try again. Trying to solve the problem of theft of intellectual property at the browser level always seems to end in failure. Just go back to the source and provide content that you don't mind people taking cuz you can't stop them if they really want to. Had to smile yesterday, was walking past an espresso bar that doubles as an internet cafe. A customer had approached the counter and was asking the barrista how to access his email because he couldn't find Explorer, and she advised him to click on Foxfire. (Great movie, though.) Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com
Re: [PHP] Comment modes behavior in HTML and PHP
At 7/28/2007 07:40 AM, C.R.Vegelin wrote: I have a PHP script, as follows: !-- ?php echo should this be echoed ?; ? -- As expected, the browser shows nothing, but when I view Source in the browser, I see: !-- start HTML comment should this be echoed ?-- Shouldn't it be just: !-- --, without the echo result ? I don't expect PHP to be active between !-- --. !-- ... -- is an HTML comment. /* ... */ and //... are PHP comments. The HTML comment syntax does not affect PHP, and PHP comment syntax does not affect HTML. http://www.php.net/manual/en/language.basic-syntax.comments.php Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Bizarre array create error
At 7/29/2007 09:59 PM, Ken Tozier wrote: /*--*/ /* Next two lines are where the problem starts */ /* If I comment either of them out the script runs */ /* but with both uncommented, it dies /*--*/ // create the rect and usable rect records $result-rect = array(0, 0, $result-page_width, $result- page_height); Does this typo exist in your script? $result- page_height with a space between - and ? Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Friday morning brain farts....
At 8/10/2007 07:43 AM, Jason Pruim wrote: I want to be able to sort that info so my sql query looks like: Select * from current order by '$order'; and $order is populated by a GET when they click on a link: A href=index.php?order='Last'Sort by last name/A Now... the whole PHP page is being included in a .shtml page to actually display it and make it look purrdee :) ... $order = $_GET['order']; --Line 6 Your HTML should read: a href=index.php?order=LastSort by last name/a Note double-quotes around the href expression and no quotes around the querystring parameter value. Also, you'll want to check the incoming values to prevent SQL injection (q.v.). If you insert unevaluated input into an SQL query you're leaving yourself vulnerable to everything from data exposure to data manipulation from outside sources. Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Separation between View and State (The Back Button)
At 11:27 AM 7/13/2006, Michael B Allen wrote: Let's say you have a Buy button that posts a form to a script that inserts or increments the quantity of a record in a shopping cart table. So you click Buy and then Checkout. Now if you hit the Back button it asks the user if they would like to repost the form. If you click Ok the db script runs again and now they have two items in the cart. Not good. It seems to me this is a fundamental model view controller kind of problem. There's no seperation between the view and the controller. What I'm thinking is that I need to give each form a unique token. When the form is submitted a new token is generate. So if at any time a form is reposted the token will be invalid and action regarding the form contents can be igored. Perhaps, but I'll bet that a lot of re-posts will be from people who click, realize they forgot to change the quantity or another value, and back up in order to correct their mistake. You might consider accepting the most recent post, not the first, when the form token matches. You might also want to include a current timestamp in the form so that you can easily detect the sequence of multiple posts. One technique that might help is to insert a processing script between input form output page. The form posts to the script which doesn't download anything to the browser but instead redirects to the destination page, so backing up from the destination doesn't automatically prompt for a re-post; the user would actually have to return to the form and re-submit it manually. And of course that's going to happen, too, so your underlying engine will need to be smart enough to know how to deal with multiple buy requests for the same product in any case. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: Help with some clever bit operations
Niels schrieb: The problem: A function tries to update an existing value, but is only allowed to write certain bits. There are 3 variables: A: the existing value, eg. 10110101 B: what the function wants to write, eg. 01011100 C: which bits the function is allowed to write, eg. With these examples, 1000 should be written. How do I combine A, B and C to get that result? 1) First, AND the mask with the value the function wants to write in order to suppress bits: 01011100 (B: value the function wants to write) (C: mask) 1100 (D: intermediate result) $D = $B $C; 2) Next, OR the above result with the existing value: 10110101 (A: existing value) | 1100 (D: B C) 1001 (E: final result) $E = $A | $D; Or, more succinctly: $E = $A | ($B $C); I love Boolean operations. Used cleverly, they can replace code branching with simple statements. Back when I was coding in assembler PL/M it was a righteously fast way of producing complex results. Regards, Paul [Sorry if this question has long since been answered, but I missed the rest of the thread.] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] different value in array
At 11:18 PM 7/28/2006, weetat wrote: I have 2 array which populated from MYSQL as shown below : My program will update status in the temporary table according to compare of 2 arrays, for example from 2 array below: in $temptablearr = there 3 elements in $currenttablearr = there 2 elements If value different betweeen elements in the $temptablearr and $currenttablearr , the status is change to 'update'. If value are same between $temptablearr and $currenttablearr , no action taken. If there are new elements in $temptablearr and not found in $currenttablearr, the status is change to 'new' If there are elements found in $currenttablearr and not found in $temptablearr , the status is change to 'deleted' Anyone have any ideas or suggestion how to do this ? Thanks for your help. ... $currenttablearr = array( 0 = array(chassis_serial_no=1235, country=Malaysia, card_serial_no=cd-12345, card_model=ws8950), 1= array(chassis_serial_no=1235, country=Singapore, card_serial_no=cd-890, card_model=ws1234), ); ... $compare = true; foreach($temptablearr as $key = $val) { if($currenttablearr[$key] != $val) { $compare = false; } if($compare === false) { echo 'update status in table to updatebrbr'; }else if($compare === true){ echo 'skip, do not shown in page.brbr'; } } Weetat, You might consider concatenating all the elements in each sub-array to make the comparison logic simpler, e.g.: foreach ($currenttablearr as $key = $subarray) { $comparisonArray[$key] = explode(_, $subarray); } This would result in: $comparisonArray[0] == 1235_Malaysia_cd-12345_ws8950 $comparisonArray[1] == 1235_Singapore_cd-890_ws1234 If you do that for both arrays you're comparing then it requires less complicated code to discover which values in one array don't exist in the other. Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] different value in array
At 12:20 AM 7/29/2006, Paul Novitski wrote: You might consider concatenating all the elements in each sub-array to make the comparison logic simpler, e.g.: foreach ($currenttablearr as $key = $subarray) { $comparisonArray[$key] = explode(_, $subarray); } This would result in: $comparisonArray[0] == 1235_Malaysia_cd-12345_ws8950 $comparisonArray[1] == 1235_Singapore_cd-890_ws1234 Sorry, of course I meant implode(), not explode()! http://php.net/implode Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] call a javascript within php
At 09:59 AM 7/30/2006, Jochen Kaechelin wrote: How can I call a JavaScript inside php? You can't literally call client-side JavaScript from server-side PHP because they're executing at different times and in different computers. PHP executes on the server then downloads the page to the browser, then JavaScript executes in the browser. What you can do is to write your PHP script so that it generates your JavaScript code as part of the page download, set to execute automatically when the page downloads. The JavaScript can either be inline in the HTML page itself or linked to the HTML page with a script tag and a SRC attribute that produces the desired JavaScript on the fly, e.g.: echo hdJS script src=myJavaScriptGenerator.php?param=value type=text/javascript/script hdJS; If your JavaScript is static -- already written, not needing modification -- you can simply link it to your PHP-generated HTML page as usual: echo hdJS script src=myJavaScript.js type=text/javascript/script hdJS; Another variation involves a static JS script that's fed dynamically-generated variables by PHP. This isn't a shared variable space between the two languages but more like a communication channel between them: $frog = 'Hello'; $dog = 'world'; echo hdJS script type=text/javascript var frog = $frog; var dog = $dog; /script script src=myJavaScript.js type=text/javascript/script hdJS; Of course you can generate entire blocks of JavaScript logic with PHP if need be, but I would suspect that in most cases you'd be better off feeding a few key variables to a static JS script. _ Most of the time you'll want your JS script to execute after the HTML finishes downloading, so that JavaScript will be able to find all the page elements in the DOM. Three ways of doing this are: 1) Use the window.onload method in a linked JavaScript script: window.onload = jsFunctionName; function jsFunctionName() { ... } Notice the lack of parentheses in the onload statement. This is because you want to set window.onload equal to the content of the function, not execute the function as would occur if you wrote window.onload = jsFunctionName();. The window.onload statement wipes out any pre-existing onload function. Multiple linked scripts can use this method cooperatively this way: // save any pre-existing onload function var uniqueVariableName = window.onload; // do the following when the page finishes downloading: window.onload = function() { // if there was a pre-existing onload function, run it now if (uniqueVariableName) uniqueVariableName(); // run the function jsFunctionName(); } // here's the function you want to execute when the page has loaded function jsFunctionName() { ... } In this example, uniqueVariableName is different for each script that uses it. I usually use the name of the JavaScript file as part of this variable name to ensure uniqueness. Multiple onloads can also be implemented using the addEventListener method: http://developer.mozilla.org/en/docs/DOM:element.addEventListener 2) Use the onLoad attribute in the body tag: body onLoad=jsFunctionName(); ...where jsFunctionName() is a function in a linked or inline script. I don't recommend this method because it mixes HTML with scripting more than is necessary. The more separate you keep them, the easier both will be to maintain. 3) Insert the function call in a script statement at the bottom of the HTML markup: ... script type=text/javascript jsFunctionName(); /script /body /html Same argument against mixing HTML with scripting, although one could argue that this constitutes the same degree of mixing that occurs with the script src= tag. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] sorting in array
At 10:31 PM 7/30/2006, weetat wrote: I have problem when doing usort() when 'country' = '', i would like to display records where country = '' last. Any ideas how to do that ? ... $arraytest= array( array ( 'country' = '', ) , array ( 'country' = 'Thailand', ) ... function cmpcountry($a, $b) { $country1 = $a['country']; $country2 = $b['country']; return ($country1 $country2) ? -1 : 1; } Weetat, You can sort the blank fields to the end simply by forcing their evaluated values in your usort callback function: function cmpcountry($a, $b) { $country1 = $a['country']; $country2 = $b['country']; if ($country1 == '') $country1 = zzz; if ($country2 == '') $country2 = zzz; return ($country1 $country2) ? -1 : 1; } ...or, using ternary syntax: function cmpcountry($a, $b) { $country1 = ($a['country'] == '') ? zzz : $a['country']; $country2 = ($b['country'] == '') ? zzz : $b['country']; return ($country1 $country2) ? -1 : 1; } Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] sorting in array
At 05:40 PM 7/30/2006, Peter Lauri wrote: function cmpcountry($a, $b) { $country1 = $a['country']; $country2 = $b['country']; if($country1=='') return 1; else return ($country1 $country2) ? -1 : 1; } Good call, Peter; my suggestion was unnecessarily fat. Weetat, both Peter's and my solutions do work -- see here: http://juniperwebcraft.com/test/sortTest.php source code: http://juniperwebcraft.com/test/sortTest.txt I could make that last statement just a bit simpler: function cmpcountry($a, $b) { $country1 = ($a['country'] == '') ? zzz : $a['country']; $country2 = ($b['country'] == '') ? zzz : $b['country']; return ($country1 '' $country1 $country2) ? -1 : 1; } I'm curious to know why none of this code works properly if it directly compares ($a['country'] $b['country']). Why are the intermediate variables necessary? Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] sorting in array
At 12:22 AM 7/31/2006, Paul Novitski wrote: I could make that last statement just a bit simpler: function cmpcountry($a, $b) { $country1 = ($a['country'] == '') ? zzz : $a['country']; $country2 = ($b['country'] == '') ? zzz : $b['country']; return ($country1 '' $country1 $country2) ? -1 : 1; } *Sigh* I shouldn't post this late at night. This is the comparison function that works for me: function cmpcountry($a, $b) { $country1 = ($a['country'] == '') ? zzz : $a['country']; $country2 = ($b['country'] == '') ? zzz : $b['country']; return ($country1 $country2) ? -1 : 1; } demo: http://juniperwebcraft.com/test/sortTest.php code: http://juniperwebcraft.com/test/sortTest.txt Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] sorting in array
At 01:14 AM 7/31/2006, weetat wrote: Thanks Paul, Very weird tried Peter's option, it doesn't work. Btw , how to sort by ascending ? Please explain what you mean. The current script DOES sort ascending by country (except for the blank country fields which are placed at the end): http://juniperwebcraft.com/test/sortTest.php Singapore, Singapore, Thailand is an ascending sort. Your original code also sorted ascending by country, but with the blank countries at the front: function cmpcountry($a, $b) { $country1 = $a['country']; $country2 = $b['country']; return ($country1 $country2) ? -1 : 1; } Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] How to recognise url in a block of text
At 10/17/2006 12:39 AM, AYSERVE.NET wrote: Please, I need help on how to to recognise url in a block of text being retrieved from a database and present it as a link within that text. Here's an illustration of your problem: Input: Text text http://example.com/directory/filename.html#anchor text text http://www.example.com/filename.php?arg=valarg=val text text. Output: Text text a href=http://example.com/directory/filename.html#anchor;http://example.com/directory/filename.html#anchor/a text text a href=http://www.example.com/filename.php?arg=valarg=val;http://www.example.com/filename.php?arg=valarg=val/a text text. Method: - find each URL within the text - replace each URL with an anchor tag that includes two copies of the URL, one in the href attribute and one enclosed in the tag. Technique: I'd use Regular Expressions for this: PHP - Regular Expression Functions (Perl-Compatible) http://php.net/pcre To write your own regexp to identify URIs, you'll want to read the spec: RFC 1738 - Uniform Resource Locators (URL) http://www.faqs.org/rfcs/rfc1738.html Specifically you'll need to know what characters can and cannot occur in an URL, and in what context, so that you can separate an URL from surrounding text and punctuation such as parentheses, periods, commas, etc. If you google regular expression url you'll find a lot of examples of regexp's that find URLs, including: Regex for URLs by Abigail http://foad.org/~abigail/Perl/url2.html Have fun, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OPTION
At 10/25/2006 04:09 PM, Stut wrote: Dang that's painful!! Try this... ?php foreach (range(1, 31) as $day) { print 'option value='.$day.''; if ($selected_day_of_month == $day) print ' selected'; print ''.$day.'/option'; } ? Ouch! Gnarly mix of logic and markup. I suggest something more like: foreach (range(1, 31) as $day) { $sSelected = ($selected_day_of_month == $day) ? ' selected=selected' : ''; print hdDay option value=$day$sSelected$day/option hdDay; } -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] heredoc usage [WAS: OPTION]
At 10/25/2006 04:09 PM, Stut wrote: print 'option value='.$day.''; if ($selected_day_of_month == $day) print ' selected'; print ''.$day.'/option'; On Wed, 2006-10-25 at 17:35 -0700, Paul Novitski wrote: print hdDay option value=$day$sSelected$day/option hdDay; At 10/25/2006 06:57 PM, Robert Cummings wrote: Ewww, I'll take Stut's style anyday. Heredoc has its uses, but I wouldn't consider your above usage one of them :/ Now to add my own flavour... echo 'option value='.$day.''.$selected.'' .$day .'/option'; Rob, I'd love to know what aspect of my heredoc usage you find objectionable. From my perspective it's a single integrated expression, cleaner, easier to read and proofread, and easier to maintain than a concatenation of expression fragments strung together with syntactical punctuation and quotation marks. I especially value the fact that heredoc lets me separate program logic from text output to the greatest extent possible. Am I unwittingly committing a stylistic or logical faux pas? Conversely, what applications of heredoc do you find valid and valuable? I ask because I use heredoc all the time, sometimes for inline code as above but most often for template assembly, maintaining HTML in external files that can be edited independently of the PHP logic. Curiously, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] heredoc usage [WAS: OPTION]
At 10/25/2006 11:24 PM, Robert Cummings wrote: Now, the thing that I dislike about heredoc for such small strings is the switching between heredoc mode and the switching back. It's ugly on the scale of switching in and out of PHP tags. It's so interesting that some details bug some people and others bug others. In an expression such as this: echo 'option value=' . $day . '' . $selected . '' . $day . '/option'; ...I count eight transitions (instances of switching between PHP syntax and output text) -- one each time you open or close a quote -- compared to just two transitions (the opening closing labels) for the comparable heredoc statement: print hdDay option value=$day$sSelected$day/option hdDay; it would be less ugly if the closing delimiter didn't have to be at the beginning of it's own line in which case code could still maintain indentation formatting. I agree. Too bad the PHP developers didn't come up with a special symbol for heredoc closing labels to give us more control over script formatting. I do however find this a fairly minor irritation, a small price to pay for heredoc's power. To lighten the mess of heredoc I personally use the following format: $foo = _ ... _; Nice and concise! Thanks, I'll use that. However that's only useful if indenting the content is not an issue. I don't see how you draw that conclusion. Heredoc doesn't become useless if we need to indent the content, it just means we lose complete control over indenting every line of our PHP script. The functionality is still totally there. This script indenting issue with heredoc is for me one of the few irritations of PHP. I love the language and the power that heredoc gives me. I'm also irritated by the class member syntax $this-that but I still use it as well. I ask because I use heredoc all the time, sometimes for inline code as above but most often for template assembly, maintaining HTML in external files that can be edited independently of the PHP logic. I use a tag based template system, there's no PHP in my content so my content files for the most part just look like more HTML. This is a different topic, but also one close to my heart. Yes, I too use my own selector-based templating system. It does allow me to embed PHP variables into the template if I want, but the primary merge between plain HTML template and MySQL content happens through CSS-style selectors. Hello jinn:render name=email selector=firstName/, Cool. My comparable example (but in an HTML context) would look like: Hello span class=firstNameFIRSTNAME/span, where the engine replaces the content of the span with the value from the database based on a match of 'span.firstName' or perhaps just '.firstName'. (In this example the 'FIRSTNAME' content in the template is merely a place-holder to make it easier to preview the markup and isn't necessary to the merge process.) | InterJinn Application Framework - http://www.interjinn.com | Interesting project! Good work. Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] heredoc usage [WAS: OPTION]
At 10/26/2006 08:24 AM, tedd wrote: At 1:04 AM -0700 10/26/06, Paul Novitski wrote: My comparable example (but in an HTML context) would look like: Hello span class=firstNameFIRSTNAME/span, where the engine replaces the content of the span with the value from the database based on a match of 'span.firstName' or perhaps just '.firstName'. (In this example the 'FIRSTNAME' content in the template is merely a place-holder to make it easier to preview the markup and isn't necessary to the merge process.) I think a div would work just as well -- span seems so old-world to me. :-) By default, div is a block element and span is inline, so span seemed like the natural fit for a sentence fragment. I don't think there's anything old-world (!) about spans, Tedd, they're just tags. I use both in my markup with a clear conscience. However, if you used preg_match_all, I think you could do away with the spans all together by matching FIRSTNAME to your first name variable. That way your document would simply read: Hello FIRSTNAME That's true, and in tighly-defined micro-contexts that might work just fine. For a robust general CMS, though, I want a completely unambiguous demarcation of replacable content. All-caps tags will work in some circumstances but certainly won't in others. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] counting records in db
At 10/26/2006 10:38 AM, [EMAIL PROTECTED] wrote: what would be better solution to count records in table (e.g., how many customers have last name 'Smith'): $query = mysql_query( SELECT COUNT(*) as NoOfRecords FROM customers WHERE last_name = 'Smith'); $result = mysql_fetch_array($query); $NoOfRecords = $result['NoOfRecords']; OR $query = mysql_query( SELECT cust_id FROM customers WHERE last_name = 'Smith'); $NoOfRecords = mysql_num_rows($query); My understanding of why COUNT() is the better solution is that mysql_num_rows() requires MySQL to cycle through the found records on a second pass to count them, whereas the first gathers the count during the first pass, the record-selection phase. Of course, if you also need to have the selected records accessible to a loop, using COUNT() will force you to execute two queries, one for the record count and one for the data themselves, so at that point the relative advantage is less clear. While we're talking about optimization, I'd want to check to make sure COUNT(*) didn't ask MySQL to generate a throw-away recordset consisting of all fields. I wonder if it would be more machine-efficient to use COUNT(`last_name`), specifying a single field, in this case the same field your query is examining anyway. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] counting records in db
At 10/26/2006 11:16 AM, [EMAIL PROTECTED] wrote: Would it be ok to use the same code to check if customer is loged in? $query = mysql_query( SELECT COUNT(Username) as NoOfRecords FROM customers WHERE Username = '$Username' AND Password = '$Password'); if (mysql_result($query, 0) == 0) I'd question whether you really needed to get a record count. If your logon system is robust, each member will be listed only once; even if not, it's probably not the number of records you're interested in learning but whether or not there are any. I'd suffice with: SELECT Username FROM customers WHERE Username = '$Username' AND Password = '$Password' LIMIT 1,0; In a case like this, where I'm confident I have either one record or none, I'd be happy to use mysqsl_num_rows(). In the example above, which field you select is arbitrary, unless you actually want more information about the logged-on user: SELECT FirstName, LastName, SecurityLevel FROM customers WHERE Username = '$Username' AND Password = '$Password' LIMIT 1,0; Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] heredoc usage [WAS: OPTION]
At 10:23 AM -0700 10/26/06, Paul Novitski wrote: For a robust general CMS, though, I want a completely unambiguous demarcation of replacable content. At 10/27/2006 09:01 AM, tedd wrote: If you want a completely unambiguous demarcation then use xml with a defined schema. I don't think you can get any more defined than that, right? Yes, I find XHTML markup sufficiently specific for my CMS. Cheers, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] heredoc usage [WAS: OPTION]
On Thu, 26 Oct 2006 01:04:25 -0700, Paul Novitski wrote: It's so interesting that some details bug some people and others bug others. In an expression such as this: echo 'option value=' . $day . '' . $selected . '' . $day . '/option'; ...I count eight transitions (instances of switching between PHP syntax and output text) -- one each time you open or close a quote -- compared to just two transitions (the opening closing labels) for the comparable heredoc statement: print hdDay option value=$day$sSelected$day/option hdDay; At 10/28/2006 04:28 AM, Nisse Engström wrote: That's funny. I count eight transitions in both examples. The difference in the second example is that the transition switches have changed from open/closing quote to '$'/not-a-variable-character. Yes, from the point of view of the PHP parser, a transition is made each time you encounter an embedded variable requiring evaluation and each time you return to the quoted expression that doesn't require that same kind of evaluation. What I was referring to were transitions of PHP syntactical punctuation that fragment the expression from the human point of view. I personally find the heredoc expression much easier to read, proofread, and maintain because it appears to be all one simple, unbroken expression. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] str_replace on words with an array
At 10/29/2006 01:07 PM, Dotan Cohen wrote: The purpose of the ^ and the $ is to define the beginning and the end of a word: http://il2.php.net/regex No, actually, ^ and $ define the beginnning end of the entire expression being searched, not the boundaries of a single word. Therefore searching for ^mouse$ will locate mouse only if it's the only word in the entire string, which I gather is not what you want. I suspect what you want is either this: (^| )WORD( |$) (the word bounded by either the start/end of string or a space) or perhaps better yet this: \bWORD\b (the word bounded by word boundaries). See [PCRE regex] Pattern Syntax http://il2.php.net/manual/en/reference.pcre.pattern.syntax.php Further to your problem, I believe this is incorrect: $noiseArray = array(1, ... ... $searchQuery=str_replace( ^.$noiseArray.$, , $searchQuery); Since $noiseArray is your entire array, it doesn't make sense to enclose it in word boundaries of any kind. Instead, I imagine each member of the array needs to be bounded individually. If you go this route, perhaps you could enclose each member of your original array in \b word boundary sequences using an array_walk routine so that you don't have to muddy your original array declaration statement. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] str_replace on words with an array
Paul Novitski wrote: If you go this route, perhaps you could enclose each member of your original array in \b word boundary sequences using an array_walk routine so that you don't have to muddy your original array declaration statement. At 10/29/2006 01:54 PM, rich gray wrote: IIRC str_replace() does not interpret or understand regular expression syntax - you'd need preg_replace() for that You're absolutely right -- I was focusing so much on the regexp syntax that I failed to broaden my gaze... When the OP corrects his PHP to use preg_replace() instead of str_replace(), I believe he'll still need to provide word boundaries around each member of his noise-word array, otherwise the function will simply remove all letters and digits from the words in the search-string he considers meaningful and he'll end up searching thin air. Aside, without knowing the context of his search, it seems a bit extreme to remove all single characters from the search string. It's not hard to think of examples of them occurring as part of valid entity names in our universe -- she got an A, Plan B From Outer Space, Vitamin C, etc. An alternative strategy might be to trust the user to enter a valid search string and simply warn them that the quality of the answer they get will depend on the quality of their input. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Decide witch table within a union
On Oct 29, 2006, at 2:00 PM, Børge Holen wrote: Would you suggest to use a extra field to hold the table name as default? At 10/29/2006 04:16 PM, Ed Lazor wrote: Definitely not. Review your design. If you need to know which table data comes from, then perform table specific queries. If you need to combine data from more than one table, code your application to respond accordingly. You may also need to review your database schema design in order that it best meet your needs. That seems unreasonably harsh. What in your view is wrong with a union query that preserves an indicator of which component table a particular record comes from? I can easily imagine a circumstance in which this could be valuable, say the union of several mailing lists that are in separate tables simply because they originate from different sources. We union them to print a single alphabetical list, for example, but we want an indicator as to the source of each record. I can imagine modifying the OP's query to read: $sql= (select '1' as tableId, * from table_1 WHERE pid='0' order by id desc limit 10) union (select '2' as tableId, * from table_2 WHERE pid='0' order by id desc limit 10) union (select '3' as tableId, * from table_3 WHERE pid='0' order by id desc limit 10) union (select '4' as tableId, * from table_4 WHERE pid='0' order by id desc limit 10) order by date desc limit 10 ; Would this be so egregious? and if so why? You say, If you need to combine data from more than one table, code your application to respond accordingly. What does this mean, exactly? Surely you're not suggesting that we code an application to somehow divine the source of a record in a union query when the query itself could simply supply that datum easily. Curiously, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Decide witch table within a union
At 10/29/2006 08:04 PM, Ed Lazor wrote: That seems unreasonably harsh. I can see what you mean, but don't take it that way. I was trying to help. Sorry, Ed, I had intended my reply to be friendly as well. I'm allergic to smiley-face icons, but I should have tried harder to convey my tone. Dang this poker-faced email! What in your view is wrong with a union query that preserves an indicator of which component table a particular record comes from? Read earlier in the thread. He's talking about adding a field to the table and that the value of this field in every single record will be the name of the table the record belongs to. I said I would definitely not recommend doing that. Me neither. You're right. I was only referencing his next email in which he said, Would you suggest to use a extra field to hold the table name as default? which I thought was a great idea, but only because I thought he meant the query. Warm regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Trying to create an encryption method
At 11/4/2006 08:15 PM, John Meyer wrote: I'm trying to create this encryption method for puzzles (nothing super secret, just those cryptograms), but this seems to time out, can anybody point out what I'm doing wrong here: for ($i=1;$i=26;$i++) { $normalAlphabet[$i] = chr($i); } //now, to shuffle for ($j=1;$j=26;$j++) { do { $k = rand(1,26); } while ($k == $j || (strlen(trim($normalAlphabet[$k])) === 0)); $arEncryptedAlphabet[$j] = $normalAlphabet[$k]; $normalAlphabet[$k] = ; } $arNormalString = str_split($normalzedString); $encryptedString = ; for ($i=0;$icount($arNormalString);$i++) { if (ord($arNormalString[$i])=65 ord($arNormalString[$i])=90) { $encryptedString = $encryptedString . $arEncryptedAlphabet[ord($arNormalString[$i]) - 64]; } else { $encryptedString = $encryptedString . $arNormalString[$i]; } } return $encryptedString; } At 11/4/2006 08:43 PM, Stut wrote: Both the inner loop and the outer loop are using $i, meaning the outer loop will never end since it gets reset in the inner loop. No, there is no loop nesting. The OP's indenting is misleading. Here's a reformatted version: for ($i=1;$i=26;$i++) { $normalAlphabet[$i] = chr($i); } //now, to shuffle for ($j=1;$j=26;$j++) { do { $k = rand(1,26); } while ($k == $j || (strlen(trim($normalAlphabet[$k])) === 0)); $arEncryptedAlphabet[$j] = $normalAlphabet[$k]; $normalAlphabet[$k] = ; } $arNormalString = str_split($normalzedString); $encryptedString = ; for ($i=0;$icount($arNormalString);$i++) { if (ord($arNormalString[$i])=65 ord($arNormalString[$i])=90) { $encryptedString = $encryptedString . $arEncryptedAlphabet[ord($arNormalString[$i]) - 64]; } else { $encryptedString = $encryptedString . $arNormalString[$i]; } } return $encryptedString; } The script spends eternity executing the do...while loop. John, display your values at each loop while your code is running to see where your problem lies. By the way, are you aware that chr(1) isn't 'A'? It's hex(01). 'A' = hex(40) = dec(64). Your array $normalAlphabet is not going to contain the alphabet the way it's written now. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Staff log-in
At 11/10/2006 07:09 AM, tedd wrote: Lastly, I think we all know that non-profit simply means that at the end of the year you get to roll your profits over to the next year without incurring taxes on the excess. Nothing more. Plus, there's no limit or requirements as to the amount/percentage you pay yourself as compared to what amounts you apply to your cause. So, mentioning non-profit to me is like saying you're just another scam -- and one, who's trolling for free php services. My, aren't we grumpy! What big bad non-profit organization rained on your parade? One of the many things that distinguishes non-profit organizations [1] from for-profit businesses is that, because they don't generate a profit [2] and are not permitted to pay out dividends, they don't attract financial investors. Most non-profits are therefore dependent on donations and grants. The financial downturn in recent years has decimated granting foundations which have been forced to reduce their grants to a small fraction of their previous funding levels and stopped granting entirely in many sectors and geographical areas. Non-profit organizations that are attempting to make positive change in areas where there is little or no short-term capitalistic reward, such as health, education, and environmental protection, have fallen on very hard times. I urge you not to be so suspicious of nor antagonistic toward a purported non-profit until you check them out, as do the grantors, to make sure their cause is true and their administrators are really wearing patched and shabby clothing and that their children are going hungry as signs of their honesty. After all, if you're doing good work in the world, you aren't allowed a decent wage; it's only people working for their own profit who can eat well without criticism. [1] http://en.wikipedia.org/wiki/Nonprofit [2] http://en.wikipedia.org/wiki/Profit In the meantime, I suppose it is emblematic of my own innocence that it always surprises me when someone asks a naive question and is answered by insults and jeers in a listserve composed of bright and knowledgeable people who have purportedly come together for mutual education. There may be no such thing as a stupid question, but the same cannot be said of the range of possible answers. Had the original poster known enough about our field to ask for recommendations of open source solutions, would he have been treated so roughly? He didn't, by the way, ask for anything for free. He said, I unfortunately can't make it myself because I don't have the knowledge, can anyone of you do this for me? When no mention of remuneration has been made, why do you assume none will be forthcoming? Is this how you greet all prospective clients, non-profit or otherwise, who approach you asking for help? Are we to assume that this indicates your innate curiosity, your desire to gain clients, your ability to negotiate, your willingness to devote yourself to a good cause, or your capacity for politeness? On the surface you appear defend your right to be paid for your work (as though anyone had demanded otherwise!), but I would be very surprised if the OP considered for a moment hiring any self-proclaimed professional who replied so harshly to his query. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] one click - two actions?
At 11/13/2006 01:28 AM, Mel wrote: Could someone please help me figure out how to show some description (where applicable) at the same time as I show an image, when I click on a link, without repeating the entire query? The image and the description are both in the same table in my database. I now show the image when I click on the link which is good, but the description stays on at all times instead of appearing only when active. http://www.squareinch.net/single_page.php Mel, I think what you're looking for is JOIN syntax for your queries: http://dev.mysql.com/doc/refman/4.1/en/join.html For example: SELECT * FROM client, job WHERE client.companyId=job.companyId AND (client.status='active' or client.status='old') order by client.companyName; (Note that when you extract fields from more than one table like this, you identify the table that each field belongs to, e.g. client.companyId.) Then you can extract the desired fields from both tables in the same loop because they've been captured together. Your current logic executes a job query for every row of client, which is extremely inefficient. The dataset produced by the join query is going to look something like this: client. job. companyId companyId 1 2 1 3 1 9 2 4 2 5 ... In other words, there will be one row for each job record, with the (parent) client fields duplicated each row. You can further improve the efficiency of your query by naming only the fields you need, instead of using * to extract all fields: SELECT client.companyName, job.pix, job.jobType, job.url, job.web FROM client, job WHERE client.companyId=job.companyId AND (client.status='active' or client.status='old') order by client.companyName; Once you execute the join query, your PHP loop can cycle in a similar way, echoing a company name and then listing all the job types until a new company name occurs, etc. You've got other problems, however. If you look at your HTML source, you'll see markup like this: span class='navCompany'Builtworks/spanspan class='navArrow' /span span class='navText'a href='single_page.php?art=btw_logo.jpg'logo/a/span span class='navText'a href='single_page.php?art='/a/span span class='navText'a href='single_page.php?art='/a/span span class='navText'a href='single_page.php?art='/a/span span class='navText'a href='single_page.php?art='/a/span brspan class='navCompany'Citizens Bank / eProperty/spanspan class='navArrow' /span span class='navText'a href='single_page.php?art=ctz_web1.jpg'website/a/span All those empty hyperlinks aren't doing anything but making your download heavier than it has to be. I think you need to test your 'jobType' fields and output only those that aren't blank. Finally, to answer one of your questions, your logic to display the description area has a snarl of syntax flaws: /* query 2 from job */ ... foreach($row as $url) { $row = mysql_fetch_array($result2,MYSQL_ASSOC); if (url={$row['url']}) echo span class='navText'a href='{$row['url']}'{$row['web']}/ a/span; } You're testing if (url={$row['url']}) 1) Because you've put that expression in quotes, you're testing the true/false value of a string expression which will always test true unless it's blank, which this one will never be. Expressing it as a string might be correct if you were using eval(), but you're not and you're safer not to. Eval() can get you into big trouble if there are PHP code fragments in your database fields; until you get better control of your logic I urge you not to use it. 2) You omitted the $ in front of $url. 3) You used a single equal sign instead of two. This: if ($url = $row['url']) tests whether $row['url'] is blank, and also sets $url equal to that value. I think you meant this: if ($url == $row['url']) which tests whether the variable $url is equal to the database field $row['url']. Good luck, Paul This is the code I have for the image area: /* query 1 from client */ $query = SELECT * FROM client where status='active' or status='old' order by companyName; $result = mysql_query($query) or die (Couldn't execute query); while ($aaa = mysql_fetch_array($result,MYSQL_ASSOC)) { echo span class='navCompany'{$aaa['companyName']}/spanspan class='navArrow' /span\n; /* query 2 from job */ $query = SELECT * FROM job WHERE companyId='{$aaa['companyId']}'; $result2 = mysql_query($query) or die (Couldn't execute query2); foreach($aaa as $jobType) { $bbb =
Re: [PHP] Splitting a string
At 11/14/2006 03:17 PM, Børge Holen wrote: $number = 123456789 should print as following: var1: 12345 (and it is this lengt witch varies) var2: 67 var3: 89. You can also do this with a regular expression: $iNumber = '123456789'; $sPattern = '/(\d+)(\d{2})(\d{2})$/'; preg_match($sPattern, $iNumber, $aMatches); Then $aMatches contains: Array ( [0] = 123456789 [1] = 12345 [2] = 67 [3] = 89 ) The regexp pattern /(\d+)(\d{2})(\d{2})$/ means: (one or more digits) (two digits) (two digits) [end of string] preg_match http://ca3.php.net/manual/en/function.preg-match.php Pattern Syntax http://ca3.php.net/manual/en/reference.pcre.pattern.syntax.php Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] CSS / PHP / Javascript
At 11/14/2006 08:00 PM, Ed Lazor wrote: I'm reading a book on CSS and how you can define different style sheets for different visitors. I'm wondering how you guys do it. The book recommends using Javascript functions for identifying the user's browser and matching them with the corresponding style sheets. Anyone using PHP for this instead - specifically with defining style sheets for different target browsers and platforms? The simple answer to your question is that you can get a browser's calling card with $_SERVER['HTTP_USER_AGENT'] which will report, for example, Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0 -- leaving you free to parse to guess at what user agent generated it. However, the street-wise programmer doesn't use JavaScript or PHP or any other language to determine browser type based on HTTP_USER_AGENT because that field can be and is so easily and routinely spoofed. It's better to let a browser's own innate abilities be the filter. For example, IE and only IE responds to Microsoft's conditional comments such as: !--[if IE 6] serve something only to Internet Explorer 6 ![endif]-- http://msdn.microsoft.com/workshop/author/dhtml/overview/ccomment_ovw.asp If you'll tell us why you want to serve different stylesheets to different visitors, you're sure to get suggestions for how to write your CSS to sidestep browser differences and/or how to write hacks which identity browsers by their idiosyncratic bugs. This topic will be much better received in a CSS listserve such as CSS-D. Before you post, check their wiki for plentiful suggestions: http://css-discuss.incutio.com/ and specifically: http://css-discuss.incutio.com/?page=BrowserDetection Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Splitting a string
At 11/15/2006 02:06 PM, Børge Holen wrote: Oh this was good. I added a while loop to insert extra strings 0 in front of the number to add if the string is less than 5 chars short. I forgot to mentinon that the string actually could be shorter (just found out) and the code didn't work with fewer than 5 char strings. But now is rocks. Hey Børge, If you need to left-pad with zeroes, PHP comes to the rescue: http://php.net/str_pad However, if you're using the regular expression method then you might not need to pad the number. You can change the pattern from this: /(\d+)(\d{2})(\d{2})$/' to this: /(\d*)(\d{2})(\d{2})$/' so it won't require any digits before the final two pairs. * 0 or more quantifier + 1 or more quantifier http://ca.php.net/manual/en/reference.pcre.pattern.syntax.php Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Looping through array
At 11/16/2006 12:19 PM, Ashley M. Kirchner wrote: Say I have an array containing ten items, and I want to display them in a table as follows: 5 4 3 2 1 10 9 8 7 6 What's the best way to loop through that array to do that? My thinking gets me to create a loop for 5 through 1, repeated twice, and the second time I add '5' to the index value. There's got to be a saner way... In order to figure out the best PHP logic to generate the series, I'd first make sure the markup is solid. I realize that you've already indicated a table markup in two rows, but I'd like to examine that. Can you tell us why the numbers are in this particular sequence? Do the numbers represent items that are conceptually in ascending order but are presented in reverse order on the screen? If so, I'd wonder whether someone reading the page with assistive technology might be confused by the reverse order, and I'd try to find a way to mark them up ascending and then change the sequence stylistically. Are they split into two rows because they represent two discrete groups in the data set or because of display considerations? If the latter, I'd argue that they don't really belong in two table rows; that using tables to force presentation is misapplying the tool. Have you considered an unordered list, floated right, wrapped in a container whose width naturally forces a wrap after the fifth item? I like that solution because it allows you to mark up the numbers in sequence and in future change the number of items in the sequence and/or change the way the series is presented visually without having to mess with the logic generating the markup. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: Space in regex
At 11/16/2006 01:56 PM, Dotan Cohen wrote: $text=preg_replace_callback('/\[([A-Za-z0-9\'.-:underscore:]+)\|([A-Za-z0-9\'. -:underscore:]+)\]/i' , findLinks, $text); This regex should match any pair of square brackets, with two bits of text between them seperated by a pipe, like these: [Ety|wife] [Jarred|brother] [Ahmed|neighbor] [Gili and Gush|pets] [Bill Clinton|horny] I would expect that the . would match spaces, but it doesn't. So the first three examples that I've shown are matched, but the last two are not. I've even added \w, \s, , and :space: to the regex, but of course that's not matching, either. What am I doing wrong? Note that I've been honing my regex skills for the past few days, but I've not so much experience with them. Thanks in advance to whoever can help me understand this. Dotan, I'm surmising what you really want to do is grab all the characters between [ and | for the first field, and everything from | to ] as the second field. I would therefore identify the first field with: [^\]|] anything except the close-bracket and the vertical pipe and the second field with: [^\]] anything except the close-bracket Therefore: /\[([^\]|]+)\|([^\]]+)\]/ Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Splitting a string
On Thursday 16 November 2006 01:38, Paul Novitski wrote: If you need to left-pad with zeroes, PHP comes to the rescue: http://php.net/str_pad However, if you're using the regular expression method then you might not need to pad the number. You can change the pattern from this: /(\d+)(\d{2})(\d{2})$/' to this: /(\d*)(\d{2})(\d{2})$/' At 11/16/2006 03:23 PM, Børge Holen wrote: Cool solution, and it works. =D I do however need some chars to fill in on the finished product for the look of it all, so the 0 is needed... Witch is a bit of a shame with this cool string. Well, just to make sure you don't discard regexp unnecessarily... // the pattern guarantees five digits, then two, then two: $sPattern = '/(\d{5})(\d{2})(\d{2})$/'; // prepend 9 zeroes to the number to enforce the minimum requirements: preg_match($sPattern, '0' . $iNumber, $aMatches); Results: $iNumber = ''; $aMatches: ( [0] = 0 [1] = 0 [2] = 00 [3] = 00 ) $iNumber = '123'; $aMatches: ( [0] = 00123 [1] = 0 [2] = 01 [3] = 23 ) $iNumber = '12345'; $aMatches: ( [0] = 12345 [1] = 1 [2] = 23 [3] = 45 ) $iNumber = '123456789'; $aMatches: ( [0] = 123456789 [1] = 12345 [2] = 67 [3] = 89 ) Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: Space in regex
At 11/16/2006 08:46 PM, Myron Turner wrote: The underscore plus alphanumeric are included in \w, so to get a regex such as you want: [\w\s\.\-\']+ You should escape the dot because the unescaped dot stands for any single character, which is why .* stands for any and all characters. Not actually. Inside a character class, a dot is just a period. You may escape it (or any other character) but you don't need to. To quote the manual: __ Meta-characters ... In a character class the only meta-characters are: \ general escape character ^ negate the class, but only if the first character - indicates character range ] terminates the character class ... Square brackets ... A closing square bracket on its own is not special. If a closing square bracket is required as a member of the class, it should be the first data character in the class (after an initial circumflex, if present) or escaped with a backslash. ... All non-alphanumeric characters other than \, -, ^ (at the start) and the terminating ] are non-special in character classes, but it does no harm if they are escaped. __ http://ca.php.net/manual/en/reference.pcre.pattern.syntax.php Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: Space in regex
At 11/16/2006 03:19 PM, Dotan Cohen wrote: However, this function: $text=preg_replace_callback('/\[([A-Za-z0-9\|\'.-:underscore:]+)\]/i' , findLinks, $text); Does what I want it to when there is no space, regardless of whether or not there is a pipe. It does not replace anything if there is a space. I see your problem -- you're omitting the brackets around your metacharacters. I believe you should be using [:underscore:] not :underscore: -- therefore, /\[([A-Za-z0-9\|\'.-[:underscore:]]+)\]/i I'm not sure why you need those metacharacters, however; I've never had trouble matching literal space and underscore characters, e.g. [ _] Also: - You don't need to escape the vertical pipe. - You don't need to escape the apostrophe. - You do need to escape the hyphen unless you mean it to indicate a range, which I'm sure you don't here. On other regexp points: Thanks, Paul. I've been refining my methods, and I think it's better (for me) to just match everything between [ and ], including spaces, underscores, apostrophies, and pipes. I'll explode on the pipe inside the function. So I thought that a simple /\[([.]+)\]/i should do it. Oops: [.]+ will look for one or more periods. .+ means one or more character of any kind. So you'd want: /\[(.+)\]/i In a case like this where you're not using any alphabetic letters in the pattern, the -i pattern modifier is irrelevant, so I'd drop it: /\[(.+)\]/ Then your problem is that regexp is 'greedy' and will grab as long a matching string as it can. If there's more than one of your link structures in your text, the regexp above will grab everything from the beginning of the first link to the end of the last. That's why I excluded the close-bracket in my pattern: /\[([^]]+)]/ I know [^]] looks funny but the close-bracket doesn't need to be escaped if it's in the first position, which includes the first position after the negating circumflex. I've also omitted the backslash before the final literal close-bracket which doesn't need one because there's no open bracket context for it to be confused with. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Powered by?
At 11/21/2006 03:02 PM, pub wrote: Is it appropriate to ask your client to add Powered by your company to the sites you design and maintain? And when you see Powered by does it mean designed by or maintained by or both? 'Powered by' sounds like an engine or a fuel, so I imagine it to mean that the site utilizes is driven by a software package you wrote or runs on hardware you manage, both on an ongoing basis. For me it strongly implies that the agency credited for powering the site is not the one that designed or created it; otherwise they'd say so. 'Designed by' implies to me just graphic design. Since I'm primarily a programmer, most of my work is either implementing another agency's graphic design or, when my partner and I do all the work, both design and implementation. If this is a credit on page footers, brevity is golden. I generally just say 'Website by' and allow that ambiguity to fill the available space. It works by itself and also in conjunciton with a separate 'Design by' credit. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] getting around the undefined index
At 11/27/2006 11:21 AM, Ross wrote: $text = $_REQUEST['text_size']; if ($text) { echo $text; } I send the $text_size variable to the browser with lines like... a href=? $_SERVER['PHP_SELF']; ??text_size=small class=size1 id=oneA/a When the page initially loads I get a undefined index error as it does not exist but is there a way of wrapping in in a switch statement or funtion so the variable is only used when $_REQUEST['text_size']; actually exists. Using isset() you can determine whether or not a variable has been initialized (including an array element) before testing its value: http://php.net/isset By the way, I think you can simplify your href to: a href=?text_size=small ... By specifying just the querystring and not the file name, I believe it will always simply reload the current page with the querystring attached. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] text only and text sizer
At 11/27/2006 02:11 PM, Ross wrote: $text_only = isset($_GET['text_only']) ? $_GET['text_only'] : 1; if ($text_only==1) { ? a href=?php echo $_SERVER['PHP_SELF'];??text_only=0off/a // import css here ? } else { ? a href=?php echo $_SERVER['PHP_SELF'];??text_only=1on/a/span // import css here ? } ? I'd begin by simplifying the logic and separating it from the HTML: $text_only = isset($_GET['text_only']) ? $_GET['text_only'] : 1; $onoff = ($text_only) ? 'on' : 'off'; echo _ a href={$_SERVER['PHP_SELF']}?text_only=$text_only$onoff/a _; How can you import CSS after a hyperlink? Shouldn't it go in the document head? echo _ link href=textsize$text_only.css rel=stylesheet type=text/css / _; That will link to either textsize0.css or textsize1.css depending on the value of $text_only. ? $text_size = isset( $_REQUEST['text_size'] ) ? $_REQUEST['text_size'] : ''; switch ($text_size) { case medium: ? link href=css/medium.css rel=stylesheet type=text/css / ? break; case larger: ? link href=css/larger.css rel=stylesheet type=text/css / ? break; case largest: ? link href=css/largest.css rel=stylesheet type=text/css / ? break; } ? Again, you don't need the switch block because the values you're testing for map one-to-one with the values you're using in your output: echo _ link href=css/$text_size.css rel=stylesheet type=text/css / _; these work great independently but when I use one the other switches off. any ideas how I can combine them? If you need to remember two separate values through multiple pageviews you can either: a) include them both in each hyperlink so they're both refreshed each time a link is clicked: a href={$_SERVER['PHP_SELF']}?text_only=$text_onlyamp;text_size=$text_size$onoff/a b) or, more reasonably, store their values in the $_SESSION cookie so you can read write them as needed throughout the current session. http://php.net/session I use standard subroutines for getting their values, something like this: if (isset($_GET[$argname])) { return $_GET[$argname]; } elseif (isset($_SESSION[$argname])) { return $_SESSION[$argname]; } In other words, if the value has been set by the last request from the client, use that, otherwise fall back to the session value. In other cases my fallback might be $_GET or $_POST to $_SESSION to $_COOKIE. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Detecting naughty sites
Hi all. I am building a web app and as part of it advertisers can upload their ad image and website URL to go with their ad. Is there a good way to detect whether that site is a porn site via php? If the sites home page contains the words sex, babes, and a few other choice words, which I'll leave to your imagination, then chances are it's a porn site. What chances are those, exactly? One in a blizzard? This is exactly why filtering realistically for pornography is virtually impossible -- we can't define the problem sufficiently to derive realistic solutions, and our inherently flawed solutions are weak. This listserve thread, containing as it does the words sex and babes and porn, has now flagged the PHP list archives as a porn site -- for anyone silly enough to use a simple keyword match to identify porn. Such a trap would also catch websites discussing the social historical significance of porn, sites that detail ways to identify porn which might include the FBI's, dictionaries and encyclopedias that explain porn, vendors who try to use sexy keywords to attract visitors to their non-porn sites, websites on human sexuality, websites about safe sex, sites about scientific research in human sexual response, and on and on and on. Such a simplistic filter would overlook websites written by people smart enough to obfuscate the key words, say by imagizing them, misspelling them, or using metaphorical language. More to the point, though, pornography isn't one concrete thing out there in the world. It's nebulous, self-defined, ambiguous, ever-changing, and psychologically and culturally dependent. This is why anti-pornography laws are pissing into the wind (oops, did I just commit porn?) -- they want to legislate human desire by attempting to define one corner of creative expression, then discover that that's like trying to contain any aspect of the human spirit. You can only accomplish it partially and temporarily by brute force or intellectual repression or both. Better to challenge those aspects of our culture that breed men who take and take with no empathy for their victims. I don't think an automated solution (PHP or otherwise) is feasible. The best you can do is to create a club advertisers can ask to join but can remain in only if their ads meet your approval. There's no machine that can judge what's porn -- machines get turned on and disgusted by a whole different set of words and images than we do -- you know, like muddy screwdrivers and oily vises -- you're going to have to do it yourself. Look at each image and judge for yourself. At least you can rest assured that your own judgement is sound. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Detecting naughty sites
At 11/28/2006 11:57 AM, Rory Browne wrote: I didn't mean something quite that simple, or as an absolute solution. I meant something slightly more advanced, but based on that idea. From a robot point of view, what do you think is the difference between the php archives and a porn site? What eaxctly do you mean by porn? Certainly there are websites that 99 people in a room of 100 would label as pornography, but the grey area is the killer -- an enormous volume of material that various people will label pornographic and others won't. Whose opinion will you use in crafting your software? Only when you define porn site with sufficient specificity can you attempt to write an algorithm to recognize one. When you've accomplished all that, you can apply similar logic to recognizing truly good movies, really delightful reads, absolutely delicious recipes, and undeniably correct political opinions. You'll be a genius -- providing you can find enough people to agree with you. If we humans can't reliably define the boundaries of a set, how can we write software to recognize its (pardon the expression) members? How would we know when the software was functioning correctly? Who would judge the accuracy of its findings? You can work for weeks developing an algorithm to detect porn and it will take others an hour or a day to find the gaps in the definition. I think any program you could write would have so many false positives false negatives that you'd end up having to manually moderate the process anyway. Please understand that I love (if I may use that verb ever so delicately) writing software that parses human expression in search of patterns and specific content. I love bestowing on a program the flexibility and grace it requires to enter that messy jungle and return with a map or a fact. I could write a spider that flagged websites containing certain words (in English, at least, without assistance), but I'm not as comfortable with the prospect of writing a sexual content filter so dependable that I'd be happy to leave it to guard a gate on its own. I'm sure it would slam the door on many undeserving people and would happily let in others my client wouldn't want. For a commercial site hoping to make money from advertisers, it wouldn't pay to have a near-sighted or illiterate gatekeeper. Perhaps the only way to do what you're suggesting is to write an image pattern recognition algorithm so sophisticated that it can differentiate a photograph of a hand caressing a breast from a photograph of a breast self-exam. Or are photos of breast self-exams pornographic? Yikes, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Tidy HTML source?
At 11/28/2006 05:05 AM, Satyam wrote: May I invite you to check http://satyam.com.ar/pht/? This is a project I started some time ago to help me produced HTML in a more clean and efficient way. Usually, producing good HTML involves running a sample output through some HTML validator or looking at the HTML and checking it out by hand, which, of course, requires good formatting to make it understandable. In the case of too dynamic HTML (meaning, output can vary widely) it is impossible to produce enough samples of all the possible outputs to get them checked out. So, my idea was to embed HTML into the language itself so that the final output could be checked at 'compile time' and even before, using the standard tools provided by the IDE (even just matching braces goes a long way into checking for missmatched HTML tags). Satyam, That's an impressive bit of work, congratulations. It's interesting to see someone spend such energy merging PHP logic with HTML. I've gone in the opposite direction, separating the two as much as possible. My own CMS merges content with HTML based on CSS-style selectors so that the logic layer of my applications doesn't need to know -- or contain -- the full details of the markup. I find this a natural and agreeable extension of the move to separate HTML markup from CSS presentation and JavaScript behavior. It's interesting to note that for all your effort to generate good, clean HTML, you're still able to generate a div nested inside a table: table for ( $i=1; $i 10; $i++) { div { style = ($i 1?odd:even); tr { Ouch! According to the spec, this is an illegal structure: http://www.w3.org/TR/html4/struct/tables.html#h-11.2.1 Your pre-compiler has ensured that all your tags are well-formed, but it doesn't ensure that you've followed the rules of correct markup. Perhaps a future iteration of your software will incorporate more HTML structural rules and will give you precompiler errors in such cases. You write: So, we have two well structured languages, one is procedural (any flavor of C, JavaScript, PHP, Perl, etc.), the other descriptive. Their blocks are quite compatible: to start with, they nest nicely within each other. If an XML block is contained within an if() block, it has to be completely within it, the boundaries of their blocks should not overlap. Help me understand the relevance of this statement. A very common pattern in a mixed logic/HTML script goes like this: echo 'ul'; foreach (array as item) { echo 'liitem/li'; } echo '/ul'; In these cases the boundaries of the HTML block do in fact overlap the boundaries of the foreach() logic block. And, of course, I would appreciate any comment on the project, EXCEPT that you use template engines and that you do not generate HTML directly. I've heard that and it is completely missing the point so, please, spare me that one. At one point or another plain HTML has to be generated. Unless I'm missing the boat, it seems to me that the primary advantage of your precompiler is that it enables you to close HTML tags simply by closing braces, a convention policed by your pre-compiler and the PHP interpreter itself, so that you'll get pre-compiler or interpreter errors for incorrect closure instead of waiting for the W3C validator to check your work. I don't mean to minimize the significance of your accomplishment, but personally I don't find generating accurate markup to be a great problem. I'm a careful hand-coder, and true to the topic of this thread I find that neatly-indented HTML helps me validate my own markup. Online validators help me catch any errors I miss. What I find to be a much greater problem is the human readability of logic code when HTML is mixed throughout. Your innovation is helpful here, as you're nearly making HTML tags into PHP key words, eliminating some of the literal quoting that makes PHP+HTML so tiresome. However, even with your pre-compiler the messy quotes are still there on the attribute level. And, stepping back, you're perpetuating the embedding of markup with logic so that it will still take a PHP programmer to modify the markup of one of your pages. Do you not see the advantage in separating the two layers? Again, in spite of this criticism I'm impressed with your effort. Good work! Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Detecting naughty sites
At 11/29/2006 01:51 AM, Robin Vickery wrote: Cubist Porn - very big in certain 'artistic' circles. What, both eggs on the same side of the sausage? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Tidy HTML source?
At 11/29/2006 05:13 AM, Satyam wrote: - Original Message - From: Paul Novitski [EMAIL PROTECTED] What I find to be a much greater problem is the human readability of logic code when HTML is mixed throughout. Your innovation is helpful here, as you're nearly making HTML tags into PHP key words, eliminating some of the literal quoting that makes PHP+HTML so tiresome. However, even with your pre-compiler the messy quotes are still there on the attribute level. The value of the attribute is any valid PHP expression and if they are literal strings there will be quotes, but then, you can also use heredoc if, for example, you are putting some JavaScript code into an event. If the value is a numeric value, there is no need for any quotes at all. In the end, the value of an attribute is any valid PHP expression and it follows PHP rules. XHTML, which I would hope you would lean toward in your pursuit of XML, does require quotes on all attributes: XHTML™ 1.0 4.4. Attribute values must always be quoted http://www.w3.org/TR/xhtml1/#h-4.4 But it's not the quotes in the attributes I was referring to as messy, but instead the necessity for two sets of nested quotes when quoted expressions and concatenation syntax are contained within assignment statements. I am an ardent user of heredoc exactly because it allows a level of separation of logic from markup, and at the same time permits embedded PHP variables. I use heredoc extensively for both HTML markup and SQL queries, both when they appear in my PHP scripts and when they imported from separate files. By the way, I'm not expressing strong opposition to embedding PHP variables in HTML, as in: a class=$sClass href=$sBaseURL/$sPagename$sCaption/a To my eye, this is a small step away from the more ideal: a class=x href=xx/a where the attribute values and the content of plain old validatable HTML are replaced based on selectors. Instead, what I'm objecting to are control structures, concatenation, mixed quotes, and escaped quotes fracturing the integrity of the output string. And, stepping back, you're perpetuating the embedding of markup with logic so that it will still take a PHP programmer to modify the markup of one of your pages. Do you not see the advantage in separating the two layers? Yes, I do, and I would recommend using templates or similar tools to provide for separation of code and markup, but sometimes there are reasons not to do so, for example, web services. Please explain why you think web services promote mixing markup with logic. I appreciate your comments and, I admit, my main purpose in doing this was to learn how to do it. I am an engineer and when I studied, a couple of semesters of Fortran IV was all I got (and punching cards at that, yes, I am that old), all the rest was self-taught so I wanted to go deeper into some aspects of computer science such as compilers (there is also a PHP grammar for JavaCC which I made earlier in the process). Hah! Fortran on punch cards was my first computer language as well, back there in the Mesozoic. And writing compilers is the best fun. I like to view programming in general as language creation -- we create functions and objects as the key words in the custom language we use at the higher levels of our own scripts. Writing compilers seems like just an extension of that. In fact, my original idea was some sort of embedded SQL as it exists for C, but I know it does not work quite Ok, in fact, it has been there for quite some time and it doesn't catch up. SQL is such a different kind of beast that it is hard to make it compatible. SQL cursors and error handling are concepts which are hard to blend into a procedural language so I believe it is better to handle SQL through functions where it is clearly separate from the language calling them. Thus, I thought, we have three main languages here, HTML, PHP and SQL. I know PHP and SQL don't mix well, how about the other end? That's when I started to think about this pre-compiler and found it to be a pretty logical mix. That's interesting, I don't have a problem allowing PHP MySQL to play together. I'm pretty happy with the PHP mysql function library in which the two communicate with strings and handles; and negotiation of SQL data structures maps nicely onto PHP logic blocks. Can you give an example of where you see the discord? I try to separate the text of my SQL queries from my PHP logic in the same way that I try to separate PHP from HTML. Warm regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Tidy HTML source?
At 11/30/2006 01:52 AM, Satyam wrote: And, stepping back, you're perpetuating the embedding of markup with logic so that it will still take a PHP programmer to modify the markup of one of your pages. Do you not see the advantage in separating the two layers? Yes, I do, and I would recommend using templates or similar tools to provide for separation of code and markup, but sometimes there are reasons not to do so, for example, web services. Please explain why you think web services promote mixing markup with logic. I didn't say it promotes but it does not require. In web services there is usually no presentation layer, there is no end user to see anything at all, then there is no need for a graphics designer separate from the application programmer. The application consuming that service might have to display the data, but the service does not. To reach clarity on this point, let's leave presentation out of it. I was referring to the separation of presentation from markup merely to suggest an analagous separation that many of us have accepted as being helpful to design, development, and maintenance. What I'm really curious about in this discussion is the separation of markup from logic. With respect to separating code and markup, you said sometimes there are reasons not to do so, for example, web services. What are some of those reasons? Cheers, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Tidy HTML source?
On Thursday 30 November 2006 18:51, Paul Novitski wrote: With respect to separating code and markup, you said sometimes there are reasons not to do so, for example, web services. What are some of those reasons? At 11/30/2006 10:57 AM, Sancar Saran wrote: What about performance ? Web services tend to be quite small applications, but even for larger ones I've never found performance to be an issue. Servers are fast and built for this kind of work: opening and reading files, running software. They have fast chips and big RAM. Regardless of which technique you use, you're going to utilize server resources and get your results in however many milliseconds. A templating system requires the processor to merge content with template. An inline markup assembly system requires the processor to build the markup from function calls. Where is the technique that doesn't take machine cycles? What about compexity ? I separate logic from markup in order to reduce complexity. I find both PHP logic and HTML markup easier to write, read, proofread, and modify when they're separate from one another (I use the word 'clean'). Those SO nice seperated template system produces lots of mini TPL files. I'm not talking about those template systems, whichever ones you're referring to, I'm talking about programming style and practice. I don't use any templating system you've ever seen. I roll my own code. I can make my templates as few or many as the project deserves. You only need to produce as many template files as you need and want. Separation of markup from logic doesn't necessarily mean separate files: when I'm doing somethign quick dirty I'll include the markup in the PHP file as a heredoc. What's most helpful to me is to remove the markup tags and attributes from the PHP logic structures as much as possible. I haven't seen any templating system out there in the world that I like, mostly because they mix the markup logic too much for my taste or because they don't let me design the markup precisely the way I want. You have to include them... Includes are easy. Actually I usually use file_get_contents() in a function that selects accompanying CSS template files programmatically. You have to parse them. Not necessarily. But if you do need to parse them, you need to write the parsing engine only once. Also you have to track and manage them. Yes, as you must manage all the files that make up a project. Adding a few more isn't a burden, especially if they bring clarity and efficiency to the work. And I'm not sure those template system gives you freedom. Because you cannot change your site design with this tpl files. If you change them too much you have to change your php code. I beg to differ: you *can* change your site design if you're using templates. That's part of the purpose of layer separation and templating in the first place, to enable markup changes without necessarily requiring software changes. You're free to change the template and/or change the stylesheet and/or change the data source according to your needs. Although we talk of separating logic from markup from presentation, these are not absolutely clean separations -- each component must have hooks in the others, otherwise there's no basis for a merge! Therefore if you change one component greatly enough, at least one other component must change as well. This is true of HTML and CSS, it's true of HTML and JavaScript, it's true of HTML and PHP. It's true of any interactive components in any system. It's true of PHP itself -- if you change a function's arguments or return type or a class's methods, you'll have to change the parts of your code that call that function or invoke that class. That's just the way it is. I'm sure you wouldn't argue that we write our software as one long mainline stream just to avoid includes and function calls. But it sounds as though you're suggesting that logic markup should be combined in the same statements simply because you don't want to have to change more than one component. Really good website designs can make modification less onerous. Layer separation is one of those techniques. Fortunately there are many ways to accomplish similar goals. I'm not claiming that my own programming preferences are the best, only that they work the best for me. It's good that we take different paths -- that's how evolution happens. What I'm asking for are the rationales so I can see if Satyam's methodology could work for me. I agree that his pre-processed PHP looks very clean. If I thought markup should be constructed incrementally with program logic I'd be tempted to use it. ... And my point of view. Using html tag ?php echo value ? ?php echo value ?/htmltag days are over... I agree completely! I hate that messy crap that results from mixing markup with PHP. Sancar, you seem to have had some very
Re: [PHP] Remote MySQL connection via PHP file
At 12/1/2006 10:17 AM, Scott wrote: For a project of mine, I need to keep the connection information to a MySQL server database on another server. I'm sure there are more efficient ways to do this, but here's a fall-back: Write a PHP program (web service) to run on the server where the database is located. From the other server, make an HTTP request that includes the connection details (obfuscated), some sort of password that can verify the authenticity of the requesting agent, and either the literal SQL query or a symbolic pointer to a stored query. http://example.com/sqlservice.php?u=HJDFHp=hglkdla=1095673263q=members or http://example.com/sqlservice.php?u=HJDFHp=hglkdla=1095673263q=SELECT%20Firstname... The web service validates the request and returns the dataset, in XML, as a serialized array, or in another easy-to-use format, for the requesting program to parse and utilize. The first thing I'd put in the return dataset would be a status code to communicate MySQL errors, perhaps also num_rows for SELECT queries to reduce the number of trans-server requests necessary for typical jobs. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Tidy HTML source?
At 12/1/2006 02:22 PM, Richard Lynch wrote: On Thu, November 30, 2006 6:47 pm, Paul Novitski wrote: A templating system requires the processor to merge content with template. An inline markup assembly system requires the processor to build the markup from function calls. Where is the technique that doesn't take machine cycles? You did NOT just compare a function call with an fstat and disk seek and disk read as if they were equal?!!! Show me *ANY* machine on the planet where those two options have similar performance metrics. Actually I was referring to machine cycles, not disk access time. But on the topic of disc access, most mid-to-large PHP applications are going to be opening reading various files -- PHP includes, databases, and not uncommonly images and text files. Even if a templating application had a somewhat higher different disk-access profile from the average PHP app, I wouldn't consider that by itself to be a reason not to open template files. I consider that to be good use of the resources, not abuse. You have to parse them. Not necessarily. But if you do need to parse them, you need to write the parsing engine only once. You mean all those templating languages are still on version 1.0 of their parser? I think not. I think not, either. The person I was replying to said, You have to parse them, as though parsing a lot of files meant a lot of human labor. My reply meant that once you write the parser, your work is done, and then the parser parses any and all files you give it for lunch. Of course you're going to improve a parser over time, just as you are going to improve all aspects of a maturing application. Also you have to track and manage them. Yes, as you must manage all the files that make up a project. Adding a few more isn't a burden, especially if they bring clarity and efficiency to the work. Few? Try 10 X as many for most templating solutions. Ten times as many templates as there are pages on the site? Wow, that's a lot. Fortunately I don't use any of those templating solutions you're referring to, and excessive templates isn't a problem for me. My own software usually takes three templates per page -- header, body, and footer, and the header and footer are generally global throughout the site. That seems quite reasonable to me. Warm regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Distinguishing between a mouse click and a refresh?
At 12/4/2006 01:08 PM, Jay Blanchard wrote: [snip] Is there any way for PHP to know whether it is being called due to a browser refresh versus a mouse click? I think the answer is no but I just want to be sure. Thanks. [/snip] Not unless you specifically capture and send a JavaScript onClick event. A mouse click typically takes you somewhere else, so if you are using for a page refresh you could capture and send a JavaScript variable to the PHP script. The tricky bit would be distinguishing between a page loaded with a mouse-click and a subsequent reload of that same page, as they would share the same querystring. One way would be to use javascript to supply the current absolute time in the querystring at the moment of click (you could do the same sort of thing with submit using a hidden field or a querystring appended to the form action), then PHP could compare that time with its own current time to see if the querystring represented a current or old rendering. That would fail with javascript disabled, of course. A server-side-only solution could pre-populate all the links on the site that point to this page with a special querystring. When the script/page is invoked with that querystring, PHP does the necessary processing and then redirects to itself (the same page) but without the special querystring. Therefore reloading the page that's downloaded to the client won't reinvoke the post-click process. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] heredoc
At 12/18/2006 10:14 PM, clr wrote: Please can someone advise me on heredoc and its shortcommings, I am designing a complex site and elected to use DIV's as opposed to frames. Heredoc seems to be ideal in that I can do all processing first and then layout with relative ease. I was wondering if it was acceptable to use and maintain going forward as i have read on a few mailing archives that this is a cheat and lazy and to be depreciated?? Yikes! Then a scoundrel I must be indeed. I love using heredoc, primarily because it lets me compose blocks of pure output text without interrupting it with control structures, nested quotes, and concatenation syntax, even when it contains nested variables. It helps me to separate logic from markup, something that benefits my code (if not my character!). I imagine you'll hear from others whose sensibilities are offended by heredoc -- in particular those whose careful indentation it spoils -- so I wanted to make sure you knew that it had an (admittedly cheating and lazy yet) ardent supporter as well. I don't know whom, in programming, you can cheat other than yourself; I've been suffering under the misapprehension that laziness is a virtue because it teaches efficiency; but I really hadn't heard that heredoc was going to be deprecated. If it is then it will be my loss and the gain of those who earn royalties from the use of quotation marks and periods and who make their living pulling the tangled and bloody fragments of logic and markup from the wreckage of their collision. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: ECHO
On 12/18/06, Fahad Pervaiz [EMAIL PROTECTED] wrote: I have written a framework for internationalization. Now i have incoorperate it into and existing system that is huge and it will take alot of time to change ECHO to a function call, so i want to override its implementation so that i can use it for my own purposes with having to change all the echo calls At 12/18/2006 10:01 PM, Casey Chu wrote: You could try to manipulate what the echo's output by ob_start(), etc. Or maybe you could change the standard output? Given the probably unalterable nature of echo, I'd say Casey's suggestion of buffering output and running it through a post-processor is an excellent one. However my first choice would probably be to bite the bullet and globally replace echo with my own function. Once that painful step is taken, you can modify the output methodology to your heart's content. This sounds like an excellent object lesson in the separation of logic from markup. If you design your applications to first figure out what to output and then to output it as one or more solid lumps, you can more easily tweak the logic or the markup or the output method without messing with the others. It can be hard medicine to swallow the first time, but it will make you a leaner cleaner coder. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Database Question
At 12/19/2006 11:01 PM, Ashley M. Kirchner wrote: I'm starting to log weather data to a database and I'm trying to figure out what's the best way to create the tables. The reports are coming in every minute, of every hour, 24 hours a day. Eventually, I'd like to do some calculations on the statistics, displaying daily values (which can be broken down to hourly), but then also daily and monthly averages. To me, it doesn't make sense to dump everything into one big table, but I can't figure out what's the best way to break it down either. Keep in mind that the only data I have, is what comes in for that minute. The daily averages I have to calculate myself (later.) But I can't see one large table being very effective when it comes to calculating that stuff. So, how should I break the tables down? Create a new table every day (20061219_data, 20061220_data, etc.) and insert all the values in it? Or, break it down per values (temp_table, humidity_table, etc.) and insert daily data in them? (This question doesn't pertain to PHP but to database techniques; you may get better and more friendly advice on a MySQL list.) I'm curious, why doesn't it make sense to you to keep all the data in one big table? MySQL is certainly robust enough to keep a whack of data together. Only when table size becomes problem, say with the practicality of backup or the speed of queries or the size of the hard drive, do you need to worry about breaking it down into smaller chunks. But every database has its limits and you're smart to decide up front how to split it up. A major factor in how you choose to store your data should be how it will be used. What kinds of queries will be most common? What time-spans do they cover? Do they usually interrogate just one parameter, e.g. either temperature or humidity but not both, or do they often query two or more parameters in search of correlations? Without knowing more, my first tendency would be to keep all the data in a single table. One table would actually occupy less disk space than splitting the data into parallel tables because some fields would need to be duplicated in every table (timestamp, record id, perhaps location, etc.). I might choose to split the data into one table per year for ease of backup and archiving. Another approach is to allow up to 5 or 10 years of data accumulate in a single table, then archive (copy out delete) the oldest year's data every year to keep the table size manageable. The daily averages I have to calculate myself (later.) But I can't see one large table being very effective when it comes to calculating that stuff. I believe it will be more efficient to calculate averages from a single table than from multiple tables. In both cases the database engine has to select the same fields to calculate the averages, but if the data is split into separate tables the engine will have to select from each table separately before compiling them. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Excluding apostrophe's
RAFMTD (Ian) wrote: ... $name = mysql_real_escape_string ($_POST['name']); ... mysql_connect(humbug,$username,$password); ... the script fails with the following report Warning: mysql_real_escape_string(): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) At 12/22/2006 05:36 AM, Stut wrote: You need to connect to the database before using mysql_real_escape_string. Ian, this is a perfect example of when it comes in handy to consult the documentation: http://ca.php.net/manual/en/function.mysql-real-escape-string.php string mysql_real_escape_string ( string unescaped_string [, resource link_identifier] ) Escapes special characters in the unescaped_string, taking into account the current character set of the connection ... link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated. Remember, my son, PHP-general helps those who help themselves. Piously, Poop Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Script's length, echo, and execution speed
At 12/23/2006 10:33 AM, Jean-Christophe Roux wrote: Hello, I have this php script of 3,500 lines with a big switch that is such that on each pass maybe 300 lines of codes are executed at most. The current speed of the file is ok. I like to keep the file like that because at each pass there is a check on the whole script and it fails if there is a typo somewhere. Also, I like to have one file instead of many files. But I am wondering if speed is not severaly hurt. What are the general guidelines in terms of length of script? Also, I am writing things like that: echo 'table'; echo 'tr'; echo tdContent/td; echo '/tr'; echo '/table'; I like it this way because the script is visually very well aligned, with one action per line and that makes things easier for me to read and understand. But, so many echoes may be considered bad practice; maybe it impacts speed significantly. Are you encountering a speed problem or just pondering this theoretically? My guess is that ECHO 'TEXT'; is one of the fastest, most optimized operations the PHP interpreter executes. But you don't need to guess at it: time it. Check the server logs, or output the current time at the beginning and end of script execution. My guess is that the difference between the execution of your script and one much smaller will lie in a scale of tens or hundreds of milliseconds. Servers are bloody fast; that's their job. In general I think it's smarter to spend your time making your script easy to read and proofread for you, the human slow link in the development chain, than it is to make it faster to run on a machine. Machines will keep getting faster; you're not likely to. That said, there are things you can do that make your script more efficient to execute AND to maintain. Personally I favor separating out the HTML into larger, pure chunks that can be proofread more easily than when tags and attributes are atomized and strewn throughout the logic. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Chocked
At 12/28/2006 03:51 PM, Skip Evans wrote: chocked ? chocking ??? RTFM: http://php.net/chocked Warm regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] php/ajax question
At 12/30/2006 10:56 AM, tedd wrote: Why can't the php script redirect the browser when called via ajax ? Ajax is giving PHP control over just that byte-stream that ajax is receiving and perhaps inserting into the page, not the full page itself. Say you use javascript to set the src of an img to a PHP script. When the request is made, PHP redirects to another resource. This will affect only the image object in question, not the HTML page in which the image exists. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Help me about detect client screen resolution!!!
At 1/2/2007 12:24 AM, Le Phuoc Canh wrote: Can we use php to detect client screen resolution? Please help me ? Do you really want screen resolution or do you want browser window size? Not every PC user keeps their windows maximized, and I have yet to meet a Mac user who attempts to do so. For cross-browser javascript that measures the viewport, see Peter-Paul Koch's page: Viewport properties http://www.quirksmode.org/viewport/compatibility.html PHP and javascript can act in concert. If PHP doesn't yet know the monitor size, it can download a javascript-only page that will talk back, e.g.: document.location.href = '?width=' . x . 'height=' . y which PHP can receive as $_GET['x'] and $_GET['y'] and then use to download the desired page. Keep in mind that the user can change window size at any time and many people do so from one page to the next to accommodate varying content and their other desktop activities at the time. Therefore you can't really rely on intial measurements; if the proper rendering of your page DEPENDS on knowing the window size, you'll need to re-measure it for every pageview. Downloading a measuring script in advance of each web page would make the browsing experience a bit sluggish. If possible, try to make your page layouts more robust. There are many techniques for engineering pages to tolerate a wide spectrum of window widths; see the CSS-D wiki for links: http://css-discuss.incutio.com/ Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] software recommendation: ServiceCapture
I've recently discovered a tool that I recommend for web work: ServiceCapture by Kevin Langdon http://kevinlangdon.com/serviceCapture/ It acts as an HTTP proxy, inserting itself between browser and the net, and logs the details of http requests and responses. It's been a great help to me lately while working on a PHP-Flash dialog via AMF-PHP, and will undoubtedly save time on future projects when I need to debug cookies and posts. (This is a spontaneous, unsolicited, uninvested recommendation. I just really like the software and thought you might find it useful.) Regards, Paul __ Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] colon in coma [was: Re: [PHP] Anyone would like to test my open source application http://sourceforge.net/projects/dfo/ ?]
, comma ; semicolon : colon http://www.usask.ca/its/courses/cai/javascript/js_semicolon.html http://en.wikipedia.org/wiki/Punctuation http://www.cogs.susx.ac.uk/doc/punctuation/node00.html -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Going back with multiple submits to the same page
At 1/15/2007 01:52 PM, Otto Wyss wrote: When values are entered on one of my page I submit the result back to the same page (form action=same_page). Unfortunately each submit adds an entry into the history, so history back doesn't work in a single step. Yet if the count of submits were known I could use goto(n). What's the best way to get this count? PHP or Javascript? What you're suggesting doesn't sound easy. If you're going to programmatically take the user to a previous page, say for example if they click a form button within your page, then using JavaScript you could simply walk backward through the window.history() array until you came to an URL that doesn't match with the current page. Of course such a solution would break if JavaScript were disabled so you'd need to build a redundant system server-side to make sure your site didn't break. Only JavaScript is aware of the window.history() array, but I don't believe JavaScript can detect when the back button is activated. You can test for window.onunload, but that doesn't tell you which direction the user is headed -- forward, backward, sideways, or same page reload. In a cacheing system the browser might not even make a server hit when going back. If you can take your computer off-line and still walk backward in browser history, your problem complicates. Of course PHP isn't naturally aware of browser history but you could store in the session or cookie the name of the last page in the current session that wasn't the current page. You'd also need to set flags in each iteration of a page so that PHP could determine whether the page being requested had already been downloaded. What happens when the user simply wants to reload the current page? It sounds messy. Perhaps, rather than interfering with the normal functioning of the browser, you could simply let it do its thing and take steps server-side to prevent the user from re-submitting the current form or whatever your goal is. Good luck, Paul __ Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] More efficient thumbnail script
At 1/16/2007 12:54 PM, Jason Pruim wrote: First off, thanks to everyone who helped me get started with a thumbnail gallery that would display info you could just copy/paste into a weblog (Or any webpage) and have the picture display. I am moving along with a few additions and seem to be running into a problem. The script I have works just fine, it's just slow when you put some large files in it, the page takes awhile to load weither I'm calling it through the php file it's self or through a include in an html file. ... The php script I'm using can be seen here: http://www.raoset.com/ tests/picture/images/wheeler.php the html file I want to include it in is: http://www.raoset.com/tests/ pictures/index.shtml Jason, I'm not able to see your PHP script because when I navigate to the script it is interpreted, not downloaded as text. Please copy the script into a file ending in .txt if you'd like people to be able to read it. Is your thumbnail script slow because you're creating images on the fly every time? If so, an obvious fix would be to cache thumbnails on the server so you only have to create them once. The logic could look something like: if (thumnbail doesn't exist) { // create thumbnail save it to the server } // use existing file Then you might consider putting the thumbnail-cacheing logic into the script that lets people upload their images in the first place, so there won't be so much processing the first time the thumbnail gallery is loaded. Regards, Paul __ Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Storing dynamic attribute data in a db
At 1/18/2007 02:56 PM, Chris W. Parker wrote: I'm currently working on trying to find a solution that is both simple and flexible for storing the data of a complicated set of dynamic options for some of our products. My current thinking is that I will use Modified Preorder Tree Traversal to organize the data. Are you considering keeping all the levels of your data tree in a single table because you can't predict how many levels there will be? If you CAN predict its depth, wouldn't it be simpler and easier to conceive, code, and debug with N tables chained in parent-child relationships? I'm not asking rhetorically but seriously, for discussion. How are you weighing the pros cons of using MPTT? Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP Warning: session_destroy
At 1/20/2007 02:14 PM, Andre Dubuc wrote: However, checking the live version, I get an secure-error_log entry: PHP Warning: session_destroy() [a href='function.session-destroy'function.session-destroy/a]: Trying to destroy uninitialized session Question is: didn't the session_start(); on the calling page take effect, or is this some other problem? I've gotten the distinct impression from the documentation and from my own experiences that session_start() is required at the beginning of every page/script that references the session. See http://ca3.php.net/session_start including Examples 1 and 2. Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] one click - two actions?
At 1/21/2007 01:54 AM, pub wrote: I am working on my query as you suggested. I have a joint query that seems to work except that I get the name of the company repeated for each job. Could you please help me figure out how to make it echo the company once and list all the jobs next to it on the same line and start a new line with the next company like you suggested bellow? You want to output the company name only when it changes. I usually do this by keeping a variable equal to the previous value in the loop and compare it each time with the current value: PreviousCompany = ''; while (fetching data records) { if (PreviousCompany != CurrentCompany) { output CurrentCompany; PreviousCompany = CurrentCompany; } output Job; } One markup structure you might consider for this application is the definition list: dl dtCompany/dt ddjob 1/dd ddjob 2/dd ddjob 3/dd ddjob 4/dd dtCompany/dt ddjob 1/dd ddjob 2/dd ddjob 3/dd ddjob 4/dd ... /dl Regards, Paul __ Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] losing session in new window (IE only) [WAS: loosing...]
At 3/25/2008 12:49 PM, Lamp Lists wrote: i have a list of people on one page. each row, on the end has link a href=person.php?id=123 target=_blankview details/a. it's requested to open detail page in new window. very few people complained they can't open detail page. all of them use IE. Try putting the attribute values in double quotes and see if that helps: a href=person.php?id=123 target=_blankview details/a How does your page validate? http://validator.w3.org/ Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] losing mysql connection during cron job
I've got a simple script running as a cron job that's getting intermittent Lost connection to MySQL server during query errors. The script sends out listserve messages, 50 BCCs each minute, sleep()ing for 60 seconds between sends and updating a data table after each send. The whole BCC list varies from one message to the next, but messages typically take 10 or more sends in batches of 50 recipients. Inconsistently, the script aborts with the lost connection error after a varying number of sends. Rarely it bombs not at all and performs all 10 or 12 updates without error. The script cycle is, symbolically: foreach (recipients as batch) { mail() using batch of recipients; mysql_query() update table; sleep(60); } final mysql_query() update table as complete; In an attempt to cure the problem I'm re-establishing the $conn before each query and doing a mysql_close() after each query, but the error still occurs. The hosting is Media Temple's gridserver. I've never encountered this error in any of the many PHP/mysql scripts I run on Media Temple accounts, but this is different as it's a cron job. Can you suggest aspects of the process that might lead to this error that I should look at more carefully? I can understand that sleep() might lose the connection between PHP the MySQL server, but why would the script be unable to reconnect after sleeping? Would that be a server-dependent issue or is there something I can do in PHP to nail down the connectivity? I'm hoping to get assistance on this issue without having to clean up the script enough to invite in guests, but I'll do so if required. Thanks, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] losing mysql connection during cron job
At 6/18/2008 04:49 PM, Shiplu wrote: why don't you edit your code? foreach (recipients as batch) { mail() using batch of recipients; mysql_query() update table; if(mysql_errno()==ERROR_CODE_YOU_GET){ mysql_connect(); mysql_select_db(); } sleep(60); } Thanks for the suggestion. I am currently successfully working around this error by another method, although your suggestion is probably better. The reason I posted this problem, though, is that I want to understand *why* I'm getting the Lost connection to MySQL server during query error. If anyone has had a similar experience using cron jobs or sleep() I'd love to hear from you. Thanks, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Capitalization of variable
At 6/18/2008 09:38 PM, Nathan Nobbe wrote: $streetAddr = 817 17th ST, DENVER COLORADO; echo ucwords(strtolower($streetAddr)); // 817 17th St, Denver Colorado I'd like to mention that, in practical usage, capitalizing the first letter of every word does not correctly capitalize addresses in most languages expressed in Roman script. In North America we see numerous common exceptions such as PO, APO, NE/NW/SE..., MacDonald, Macdonald, deCamp, D'Angelo, de la Rosa, Apt. 3E, et cetera, et cetera. If you're serious about correcting a mailing list for upper- lowercase, I suggest you build or use a replacement dictionary that's smart about postal addresses and smart about the languages you're liable to encounter. If you're in North America, a simple correcting algorithm is pretty much impossible because of the damage done by Ellis Island that has rendered the spelling of names arbitrary, even random, and often incorrect relative to their origins. Good luck! But don't give up -- as Xeno will attest, your earnest attempt to reach the tree with your arrow will gain praise even if it's doomed never to actually arrive. Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] losing mysql connection during cron job
At 6/18/2008 02:47 PM, Paul Novitski wrote: I've got a simple script running as a cron job that's getting intermittent Lost connection to MySQL server during query errors. At 6/18/2008 10:43 PM, Chris wrote: You need to do a mysql_close(); mysql_connect(...) before mysql_query works again - otherwise mysql_connect will just return the same resource id (or I guess just use the 'new_connection' flag for mysql_connect and skip the mysql_close()). Thanks! Adding the new_link parameter to mysql_connect() did the trick. What had me stumped before was that each mysql_connect() succeeded but the mysql_select_db() immediately afterward failed. But as the documentation says: new_link If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. http://ca3.php.net/mysql_connect Reminder to self: RTFM doesn't always work if you think you know the page and don't re-read it with new eyes. Cheers, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Associative Arrays
At 6/19/2008 05:55 PM, VamVan wrote: How to create an associative array of this kind in PHP? return array( 12345 = array( 'mail' = '[EMAIL PROTECTED]', 'companyName' = 'Asdf Inc.', ), 54321 = array( 'mail' = '[EMAIL PROTECTED]', 'companyName' = 'Asdfu Corp.', ), ); This is the right PHP syntax, except that you've got an extraneous comma before the closing parenthesis of each array that's going to throw a parse error. Regards, Paul __ Paul Novitski Juniper Webcraft Ltd. http://juniperwebcraft.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Associative Arrays
At 6/19/2008 07:36 PM, Robert Cummings wrote: 54321 = array( 'mail' = '[EMAIL PROTECTED]', 'companyName' = 'Asdfu Corp.', ), ); This is the right PHP syntax, except that you've got an extraneous comma before the closing parenthesis of each array that's going to throw a parse error. Actually that's allowed (and by design too) :) Yep, it's there to primarily simplify generated PHP code. Additionally, it sure makes commenting out chunks simple since you don't need to comment out the preceding comma if commenting out the last entry. Thanks. I could have sworn I'd gotten parse errors on that. Damned cross-language memory leakage... I've gotten into the habit of writing comma-delimited lists like so: (item ,item ,item ,item ); which works for functions with long parameter lists and SQL field lists as well as arrays. Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Mysql Rows
At 08:57 AM 3/6/2006, tedd wrote: What I find interesting in all of this exchange -- however -- is that everyone agree's renumbering the id of a dB is something you don't do, but no one can come up with a concrete (other than relational) reason why. It's simply -- concretely -- inefficient inelegant to modify on average half the records in a database simply in order to delete one record, when queries give us fast, simple, READ-ONLY methods for enumerating existing data. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: Incremental Date Based ID
At 05:05 PM 3/7/2006, Kevin Murphy wrote: Well, part of the issue is that I want to be able to use this as part of the link: /news.php?article=2006-03-05a /news.php?article=2006-03-05b With respect, I too think you should re-examine your reasons for wanting to number (or letter) the links consecutively in the database. To whom does the spelling of an URL really matter? I believe that website visitors rarely care; they care about how things are labelled in the foreground and they want to get to the correct page, but I don't think many people really study the details of the address bar and even fewer make judgements about the quality or completeness of website content on that basis. There are in fact solid reasons for NOT changing URLs once they're established -- for example, the persistence of bookmarks, links from other websites, and search engine memory. Once you establish an URL pointing to a particular page it's going to be recorded, stored, and repeated by many other entities on the internet. If you're whimsically changing URLs at random intervals, old URLs will no longer point to the same content. You'll be doing your own material a disservice by frustrating one of the most powerful assets the internet can lend you: its persistence of vision. I wonder if your desire for contiguously lettered URLs can be satisfied by simply assigning consecutive letters to the display text that links to the articles: HTML: ol lia href=/news.php?article=9568367Title of article/a/li lia href=/news.php?article=1937452Title of article/a/li lia href=/news.php?article=4694832Title of article/a/li CSS: ol { list-style-type: lower-alpha; } RESULT: a. Title of article b. Title of article c. Title of article As others have pointed out, the sequence in which the URLs spill out from the database can be controlled by a timestamp in each record. The lettering of the articles a-z can be controlled by the ordered list for the benefit of the visitor. When an article is inserted into or deleted from the list, the list retains its contiguity IN THE PRESENTATION and you aren't put in the inelegant position of trying to renumber records in a database. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] .DAT file with PHP
At 07:41 AM 3/8/2006, Jabez Gan wrote: Sorry im new but, how do we read from a file to an array? I've studied C but not with PHP and it's not working for me... Suggestions? file() Reads entire file into an array http://php.net/file Doesn't require open close. Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] .DAT file with PHP
At 10:27 AM 3/8/2006, Rory Browne wrote: $filename = filename.txt; $file_content = join(\n, array_reverse(file($filename))); echo $file_content; Rory, I think you've got the logic right. Tangentially, however, I recommend that you break it out into separate statements and not throw multiple functions into the same statement -- it's hard to proofread, it's hard to pinpoint where errors occur, and it's next to impossible to insert echo statements to debug the process. Also for ease of debugging maintenance, I recommend indicating the type of each variable with a prefix (a=array, s=string, etc.): $sFilename = filename.txt; $aFile_content = file($sFilename); $aFile_reverse = array_reverse($aFile_content); $sDisplay_content = join(\n, $aFile_reverse); echo $sDisplay_content; I don't think PHP will care whether it's broken out or not -- internally it's having to create temporary variables on the fly to store incremental values -- but your future self and other folks reading your code will thank you for it. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] .DAT file with PHP
At 07:05 PM 3/8/2006, Jabez wrote: I used the following code that Paul suggested, but it didn't reverse my content. The file I would want to have the content reversed is as attached. Chinese characters is in the file so... Suggestions? Jabez, The data in your file is all in one text line. You have inserted the string br between what I assume are your data elements, but not PHP linefeed characters. Try using \n (backslash-n) as your line delimiter and try again. By the way, I neglected to tell you earlier that when file() reads a file into an array, it includes the linefeed characters at the end of each array element. These might or might not get in your way if you're outputting your data to an HTML file -- a linefeed will render as a whitespace character. If you'll be writing the data to another text file where linefeeds are crucial, you may wish to massage the array to ensure that every array element (including the last one read from the original file) ends in \n. Regards, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] heredoc syntax vs Double-Quotes
At 07:06 PM 3/15/2006, Chris Kennon wrote: when is using heredoc advisable over Double-Quotes? I love using heredoc primarily because it helps me separate logic from markup when generating HTML. The text in a heredoc expression is vanilla, no escape sequences needed, so there's less worry about typos. I find it one of the strongest features of PHP as compared to other scripting languages. Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] php error reporting problem
At 10:57 AM 3/28/2006, ngwarai zed wrote: hi, I omitted a semicolon ; at the end of a php statement on purpose to see what the error looks like. I ran the script and a blank page just came out.No error message. I then edited php.ini and set Display_errors = On and errror_reporting = E_ALL then restarted httpd. Ran the script again and the same thing happens. My question is:- how do I make php to show me a simple error like omitting a semicolon? If you omit the semicolon at the end of a line, PHP attempts to join it with the next line into one statement. Sometimes, by coincidence, this results in a legal statement. To show the error message, enter two statements that you're sure will combine into invalid syntax, such as: $x = 4 $y = 3; Their concatenation results in: $x = 4 $y = 3; which should get you parse error, unexpected T_VARIABLE. Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Faking Boolean
At 11:08 PM 4/5/2006, John Taylor-Johnston wrote: How can I take enquiry: input name=searchenquiry type=text value=john or input name=searchenquiry type=text value=john johnston and parse its value to come up with this to do a boolean search +john or +john +johnston John, If you're splitting your search string into discrete words, most search engine logic doesn't require quotes. Typically, quotation marks combine multiple words into single expressions, which makes sense with John Johnston but not with John Johnston. But since you requested the quotes I'll include them: Here's one way to convert an incoming word series for a search: // get the entered text $sEnquiry = $_GET[searchenquiry]; RESULT: [ johnjohnston ] // protect against input attacks here ... // remove whitespace from beginning end $sEnquiry = trim($sEnquiry); RESULT: [johnjohnston] // replace internal whitespace with single spaces $sEnquiry = preg_replace(/\s+/, , $sEnquiry); RESULT: [john johnston] // replace each space with quote-space-plus-quote $sEnquiry = str_replace( , \ +\, $sEnquiry); RESULT: [john +johnston] // add beginning ending delimiters $sEnquiry = +\ . $sEnquiry . \; RESULT: [+john +johnston] Another technique that's worth exploring uses explode implode to isolate the words and the join them again with different delimiters, e.g.: // remove extraneous whitespace $sEnquiry = ... // split string into array of words on each space $aWords = explode( , $sEnquiry); RESULT: array( john johnston ) // concatenate the array back into a string using desired delimiters $sSearch = implode( +, $aWords); RESULT: [john +johnston] Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php