Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Tots posted:

...
Can someone give me a hint?

Ah well, first thing is that opendir() returns a "directory handle" that you need to keep track of in order to use readdir(). Second thing is that PHP, like a lot of other languages, has assignments that return a value, so $a in "$a=($b=4);" has the value 4. So to make the first example more readable,
php:
<?
$dh=opendir('/whatever'); //$dh is directory handle
if($dh){ // if $dh has a value
 /* process directory */
 closedir($dh);
}
?>
BTW "$path" wasn't the greatest choice of variable name in the first example. If you "echo $path;" you'll get "Resource id #2" or something.

readdir() lets you walk through a directory or reset the cursor or whatnot. 99% of the time you just use it like:
php:
<?
while(($entry=readdir($dh)) !== false){
  /* do something with $entry */
}
?>
The while expression first sets the value of $entry, then tests that against false. (Side note, you test against false explicitly just in case you have some funky entry that evaluates to false. Not sure how that might happen, but eh.) Also to pick on the example code further, readdir() returns both directories and files, so using "$file" isn't quite right.

It's sort of like PET BASIC, if you're old like me. A floppy's directory was stored in a special file called "$", so if you wanted to list the contents of the disk programatically you'd open the file "$", read in each line, then close "$". In PHP, they just built a special command around "$", so opendir() ~= fopen(), readdir() ~= fgets(), and closedir() ~= fclose().

Edit: moved closedir to inside of if

Tad Naff fucked around with this message at 20:32 on Feb 23, 2009

Adbot
ADBOT LOVES YOU

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

VerySolidSnake posted:

Need some help on figuring this out. I'm trying to simply split up my code into functions, to easily come back and edit them. Here is the code I'm trying to use:

code:
<?
function db_connect() {
	global $link;
	$link = mysqli_connect('localhost', 'user', 'pass', 'db');
	
	global $test;
	$test = "omg lolz";
	
	if (!$link) {
	   printf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error());
	   exit;
	} 					
}

function simplequery() { 
	if ($result = mysqli_query($link, 'SELECT firstname FROM edu_user')) {
	
		echo "First names are: ";
	
		while( $row = mysqli_fetch_assoc($result) ){
			echo $row['firstname'];
		}
	
		mysqli_free_result($result); 
	}
}

function test() {
 echo $test;
}

?>
What I can't figure out is why simplequery() doesn't work, because of $link not transferring through. Also, when I call test() on my page, it doesn't echo "omg lolz". These basics are really confusing me, but once I get them I can get going on this!

"global $foo;" means you're using the $foo in the global context. Once you enter a function you lose $foo unless you have a "global $foo;" in there. So you'd need to say "global $test;" in the test() function and "global $link;" in simplequery().

But this is all avoiding the fact that you should avoid global variables if at all possible. Better to return $link in db_connect and use it as a parameter in simple_query, so you can:
php:
<?
function test(){
 $link=db_connect();
 if($link){
  simplequery($link);
 }else{
  echo 'DB connect failed.';
 }
}
?>

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

VerySolidSnake posted:

Changed the code to:

[...]

The error: Warning: mysqli_query() expects parameter 1 to be mysqli, null. What should be changed?

Also another question on writing code like this. When there will be multiple queries, with each having to run db_connect(), won't that just open tons of connections to the database? Shouldn't there be a more efficient way to do this?

Still need to "return $link;" in db_connect(). If you want to re-run queries, you don't have to create a new link each time, just reuse $link. For example:
php:
<?
function db_connect() {
    $link = mysqli_connect('localhost', 'user', 'pass', 'db');
    
    if (!$link) {
       printf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error());
       exit;
    }
     return $link;                
}

function simplequery($link, $field) { 
    if ($result = mysqli_query($link, 'SELECT '.$field.' FROM edu_users')) {
    
        echo "Values are: ";
    
        while( $row = mysqli_fetch_assoc($result) ){
            echo $row[$field];
        }
    
        mysqli_free_result($result); 
    }
}

$myLink=db_connect();
echo("First Names:\n");
simplequery($myLink,'firstname');
echo("Last Names:\n");
simplequery($myLink,'lastname');
mysqli_close($myLink);
?>
Also, yes, DB abstraction is a good thing.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

niralisse posted:

Not if you use exec() with an &$output argument.

The glob() version is probably the way to go. You could also get fancy and use a DirectoryIterator.

For some reason the first results for this problem are always junk like readdir().

Where the heck did DirectoryIterator come from? PHP is such a mindfuck sometimes.

[looks it up] oh, 5.0. I was held back for way too long by sysadmins who wouldn't trust that new PHP 5 (probably with good reason) so I used 4.3.x long past its expire-by date.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Vedder posted:

[...]The only trouble is I receive some Word documents with all sorts of formatting, bold text here, underlining here etc and was wondering whats the best way to insert that data?

I have read up on htmlentities() and while that has worked great for things like pound signs and quotations there doesn't seem to be one for bold, italic, bullet points etc..

What is the best way to do this? I understand for some I could simply add the HTML tags in the textpad but I imagine this is a bit of a scummy way of doing things. Am I better creating some sort of input page for this data as the way I am inserting data into MySQL at present is a bit primitive. Any help appreciated.

It was a neverending pain in the rear end for me in that situation. Generally I'd use Word's Export to HTML (different from "Save as HTML"), then HTML Tidy, then manually fix whatever goofiness remained, then grab the body of the page and throw it into the CMS. There's also "antiword" for Linux which extracts text from Word docs (I don't think anything post-Word 97), but it also strips formatting so you'd have to reapply it all over again.

Making an input page is a good idea in theory, but if people are using Word to write for the web, it's guaranteed that they will just copy from Word and then paste into the form, which leads to all sorts of misery with the curly quotes and formatting. Things like FLK and TinyMCE just exacerbate the problem, because they look like Word so people expect them to actually be Word. I hate to say it, but if you have the power to make suggestions you might want to get contributors to use a WYSIWYG HTML editor rather than Word. You'll still have to clean it up, but at least it'll arrive with the entities already done and no wacky "mso:normal" sort of tags in it.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

duck monster posted:

The questions is, how does one write a regex that preg_match_all can read so that a url like

/users/32 can match on /users/ and then extract the 32 into a variable.
Any regex gurus able to help me here?

Not a guru, but something like this:
php:
<?
    function route() {
        foreach ($this->table as $k=>$v) {

            $urlsplit = explode(URL_SLICE,$_SERVER['REQUEST_URI']);
            $url = $urlsplit[1];
            if (preg_match('!^/'.$k.'/(.*)$!',$url,$matches)) {
                global $_URL;
                $_URL = $matches[1];
                $obj = new $v[0]();
                print $obj->$v[1]($_SESSION,$_REQUEST,$_URL);        
            }
        }
    }
    
}
?>
$matches[0] has the whole matching string (useless), $matches[1] will have the first group, etc.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Sylink posted:

EDIT: NEVERMIND I AM RETARDED PLEASE REMEMBER THAT = IS NOT THE SAME AS == I HAVE HIGHLIGHTED THE STUPID ERROR FOR OTHER MORONS LIKE ME TO LEARN FROM

...and you'll probably want session_start() at the beginning of login.php and logout.php.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Uncle Marx posted:

How do I round up a number if a division doesn't have an integer as the result?

Examples:
8 stays 8
7.58333 becomes 8
7.00001 becomes 8

The only thing I have is checking the result with !is_int(), but I have no idea how to round the number up to the next integer.

ceil()

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

supster posted:

I need to do a database export from within a PHP application (without using mysqldump) similar to how phpMyAdmin does it. I've searched around a bit and surprisingly did not find anything that did this - does anyone havea any suggestions?

Well probably since phpmyadmin is written in PHP, you can find out how it does a dump, and just copy/adapt that. On the copy I'm looking at (version 2.9.2), it's in export.php around line 461, the line
code:
} elseif ($export_type == 'database') {
Myself, I'd probably attempt calling mysqldump from PHP first since I'm terribly lazy.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Aredna posted:

This is probably just going to show how bad I am at google today...

Where can I find a regex that will check if a string is a valid regex for use with preg_match?

e: To give some more context, I'm validating data in an array and rather than rewrite the code several dozen times to check, I created a function. I need to validate both the key and value are either an exact value or they match a certain regex, but it will vary by what I'm expecting to see for that row in the array so I could have any combination of regex/plain text for the key and value. Rather than creating 4 functions to handle each situation or making the plain text checks into regex, I want to check if the string is a valid $pattern for preg_match and then use either that or an equality check.

I was going to just check for starting and ending with a slash, but that failed as soon as I wanted a case-insensitive check so I realized someone has to have written this before so I should just find and use theirs rather than trying to write one myself that is all inclusive.

Here I thought I was the only one perverse enough to think of writing a regex to validate regexes. I gave up after a bit (checking for matching brackets is really hard). The cheap-rear end PHP way to do it might be something like:
code:
$test=@preg_match($maybe_valid_regex,"some string or other");
if(!$test===false){// preg_match returns false, 0, or 1
  //invalid regex 
}else{
  //valid
}
... or something with a try - catch, maybe.

or, maybe you can get away with just
code:
preg_match('/^\/.*\/[imsux...]?$/', $maybe_regex)
if you can trust that if it looks like a regex, then it's a valid regex ("imsux" would be the valid pattern modifiers you want to use).

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

ABombInABowl posted:

code:
header("Location: /packages/".$filename);
header("Content-disposition: attachment; filename=".$filename);

I think that Location: might be just sending you directly to a nonexistent file, try taking it out. Also, because this bit me once, it's best to put the filename in quotes in that Content-disposition, i.e.
code:
header('Content-disposition: attachment; filename="'.$filename.'"');

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:
Before I kill myself any further, is there something in PHP already out there that functions as a proxy? I'm working on a mobile (i.e. PDA) interface to a highly organic (since 1996 if not before) site that has all manner of crap in it, from PDFs to JSP to Perl CGI to straight (if very nonstandard) HTML. The basic operation is:

code:
[url]http://site.com/m/index.php?page=http://site.com/requested_page.html[/url]
will return http://site.com/requested_page.html with images/embeds/style/script taken out and some other minimalization and URL rewriting to point back at the minimizer/proxy. It's working pretty well, but the thing that's blocking me is cookies, it seems. I'm using curl like so:

code:
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
but the minified login page always complains that I have to turn cookies on. So, a) like I asked before, is there something like what I'm trying to do out there already, or b) am I totally wrong on that cookie business?

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Lumpy posted:

I have successfully done this, so I know it can be done... I'd have to dig through my work machine's backup HD to look for my stuff, but this page here might give you an "ah-hah!" until I can find my stuff or somebody else can help you out:

http://www.weberdev.com/get_example-4555.html

Gah, I did it. I was totally on the wrong track, of course. For anyone else doing this sort of thing, don't keep POSTing info when you're following redirects.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Bitruder posted:

I need to parse some LaTeX code into human readable code (just a small subset). However, I'm not sure how to use preg_replace (or another suitable tool) to parse something like the following:
code:
\emph{{M}olossus molossus} from {C}uba
... becomes ...
<em><strong>M</strong>olossus molossus</em> from <strong>C</strong>uba
I figure I first need to replace the \emph{blah} with <em>blah</em>, and then do the left over {}'s, but how do I make sure that the } after the M in Molossus doesn't stop preg_replace from matching?

I just noticed the other day that PHP's PCRE has this new "?R" thing which supposedly solves the parenthesis-matching problem, see http://ca2.php.net/manual/en/regexp.reference.php under "recursive patterns".

PHP Manual posted:

Consider the problem of matching a string in parentheses, allowing for unlimited nested parentheses. Without the use of recursion, the best that can be done is to use a pattern that matches up to some fixed depth of nesting. It is not possible to handle an arbitrary nesting depth. Perl 5.6 has provided an experimental facility that allows regular expressions to recurse (among other things). The special item (?R) is provided for the specific case of recursion. This PCRE pattern solves the parentheses problem (assume the PCRE_EXTENDED option is set so that white space is ignored): \( ( (?>[^()]+) | (?R) )* \)

First it matches an opening parenthesis. Then it matches any number of substrings which can either be a sequence of non-parentheses, or a recursive match of the pattern itself (i.e. a correctly parenthesized substring). Finally there is a closing parenthesis.

Haven't tried it yet myself but it sure sounds better than some of the hacks I've done.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Agrikk posted:

I need help breaking up lines of data in a flat file into variable to be imported into a database, and explode() doesn't seem to cut it.
...
How can I accomplish this?

I'd suggest unpack(), which seems to be tailor made for splitting out fixed-length fields, and as a bonus you get to specify the packed type. That or a bunch of messy substr()'s...

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Jreedy88 posted:

I'm trying to pass some PHP strings to JavaScript. I'm doing this for an AJAX request on the server. The problem comes when the string contains either a " or '. Is there a function I can use to put escape characters in there so that when I call the echo, it echoes the entire string and doesn't get cut off in the wrong spot?

php:
<?
$job = 1" Trim;
echo "ordernumber.innerHTML = \"$job\";\n";
?>
This breaks horribly. Help me fix it.

To be clear, I have no control over $job. It's being pulled from a SQL database where both ' and " are allowed.

I made this thing after getting too insane with escaping HTML for exporting to JS:
php:
<?
function jsescape($str){
        $str=str_replace(
                array('"',"\n"),
                array('"+String.fromCharCode(34)+"','\\n'),
                $str);
        return '"'.$str.'"';
}
?>
Then you'd just do:
code:
echo "ordernumber.innerHTML = ".jsescape($job).";\n";

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:
Edit: PDO is nice, I'm sure. I just don't like the verbosity. And 90% of the servers I work on are on RHEL<=5.

Tad Naff fucked around with this message at 05:57 on Jul 1, 2009

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Safety Shaun posted:

I tried but this is regexing the source of a requested URL which contains HTML and Javascript.

Why oh why is it returning it as an integer?

Because the matched part is really returned elsewhere... like so:

php:
<?
$matches=array();
$number_of_matches=preg_match_all($regex,$source,$matches);
var_export($matches);
?>
edit: Changed to preg_match_all. preg_match stops at the first match.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Pimpsolo posted:

Basically you can see that I would like to automate filling out this form so that with a single click I get the results of my query. So if either of my methods are impossible and there's an alternate, I'm open to another method. Thanks in advance for any help.
You might try grabbing the form source and substituting <input type="hidden" name="the_same_name" value="whatever" /> for the fields you want to pre-fill. This isn't guaranteed to work if the server does any sort of valid-token stuff but it usually works (if there is any token stuff, you might have to scrape the form on the server side first).

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

xezton posted:

I do that, too. I agree it's cleaner and it's easier to pick out variables in strings when you're scanning through code (in my opinion at least).

I'm so very, very ashamed...
php:
<?
foreach(array('Type','Null','Key','Default','Extra') as $v){
  if(${"c$v"}!=${"n$v"}){
    echo("***\t ojs222.$table.$cField $v '".${"c$v"}."' => ojs.$table.$nField $v '".${"n$v"}."'\n");
    switch($v){
      ...
    }
  }
}
?>

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Agrikk posted:

Two things:

I have this code:

php:
<?
$Size = 0;

if ($Size === "S" || $Size === 0)  $Test =  "S";
if ($Size === "LGG") $Test =  "LGG";
if ($Size === "SGG") $Test =  "SGG";
if ($Size > 0 && $Size <=9)  $Test =  $Size;
if ($Size === "A" )  $Test =  "A";

echo $Test;
?>
Assuming the valid values for $Size are S, LGG, SGG, A and the numbers 0-9, is there a more efficient way of evaluating $Size to produce $Test?

php:
<?
$Size=0;
$Test=($Size===0)?'S':$Size;
if(!preg_match('~^(S|LGG|SGG|[0-9]|A)$~',$Size) unset($Test); // this line might be unneccessary, depending
echo $Test;
?>

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:
I am getting annoyed with charsets. I've been working on an email archiver, but it seems like there are more encodings than there are email clients. So far I've got a bunch of heuristics about uppercasing, making "utf8" into "UTF-8" etc., falling back to whatever mb_detect_encoding says and then iconv, but it's still missing a lot and/or getting it wrong. Here's a link to a log. Anyone out there have experience with this sort of thing? Some sort of PEAR module maybe?

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

MrMoo posted:

How can you mess up gb2312? iconv has oodles of aliases already setup for each encoding, e.g. utf8, UTF8, UTF-8, etc.

Are you suggesting using iconv before mbstring? Because I could do that too; mbstring just seemed more 'mature' at first glance, mostly because I could actually get a list of its supported encodings.

... unless you're joking about gb2312.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

MrMoo posted:

Actually I'd try recode first considering the source material. The other modules are more strict on character set names.

Run recode -l on the command line for supported sets and aliases.

PHP is like a series of tunnels, endlessly twisting. Thanks, I'll definitely be giving that a try tomorrow.

E: Any tips on getting the PHP extension installed on RHEL5? Not seeing it in any of my current repos.
E2: Scratch that, had PHP excluded from yum (5.3 breaks every drat thing).

Tad Naff fucked around with this message at 06:44 on Sep 29, 2009

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Plorkyeran posted:

Don't use regexps to parse xml.

Aw, c'mon. I do it all the time. Granted, I'm usually checking for the existence of "AuthSuccess" in the document and I don't care about the rest of it.

But yeah, if you want to keep the structure and all you might need to use an XML parser.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

TreFitty posted:

I have a question about PHP/MySQL and checkboxes. I want to store boolean values in a database table and when I submit a form with an unchecked box, it stores the value as '0'. That's great. When I submit a form with a checked box, it tries to store the value as 'on'. NOT great.

After the values are stored, I need to be able to repopulate the same form with that information at some point. Going through and changing all the values (all 30 of them) in the database from 'on' to something usable by my site by way of conditional statements is something that I probably shouldn't be doing.


I'm also using CodeIgniter for this site, but I don't think that matters here.

Any of you have any ideas?

edit: Pretty sure that setting the value of the checkbox in HTML to "1" will fix my problem, but I haven't tried it yet. Didn't want to delete my post in case some other moron like myself found this as a solution.

Try setting value="1" in the checkbox <input>s? I think you end up with "on" if you don't specify the value.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

fletcher posted:

Never even heard of this. I currently use Notepad++ as well (and sftp-drive) to write all my code. All I want is an editor that can do key based authentication to edit remotely hosted code, sftp-drive is the biggest piece of poo poo.

90% of the time I use SSH and nano, but occasionally if I can be bothered to set up a share drive I'll use Notepad++. Just recently I finally got around to writing a half-decent PHP syntax highlighter for nano, up until then I was doing everything in glorious monochrome.

Some day I'll learn something proper like vi or emacs.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:
OK, I'm avoiding work so here's a possible rewrite.

code:
<form name="search_rentals" action="pages/properties/69.php" method="GET"><!-- or POST, whatever works for you -->
<!-- I hope $data is defined somewhere previous to this -->
    <input type="hidden" name="cid" value="<?php echo $data['id']; ?>" /> 
    <input type="hidden" name="ms_search_home" value="ms_search_home" /> //??
    <input type="hidden" name="city_id" id="city_id" value="0" />
<!-- you seem to have 'cid', 'city', and 'city_id' all in here and I suspect they're all the same thing. -->
    <div class="search_lite">
        <h2>Select a City</h2>
        <div style="float:left;"><?php echo city($data['id']); ?></div> <!-- float necessary? should go in CSS file if it is -->
        <div style="clear:both;"></div> <!-- I'd just take out these divs and use a <br /> -->
        <input type="image" src="/filebin/images/search_rentals.jpg" name="search_rentals" class="rentals_center_btn" />
    </div>
</form>
<?php
    function city($currentcity) {
// you probably want to use a boolean for `hidden` in the DB, but maybe you don't have control of it? 
// Also avoid "SELECT *" if possible.
        $sql = "SELECT `id`, `name` FROM `city` WHERE `hidden` != 'Yes' ORDER BY `sequence` ASC"; 
        if ($res = mysql_query($sql)) {
            $return = '<select name="city" id="city" class="small_input">'; // are you using the id here?
            $return .= '<option value="0" disabled="disabled">Select a City</option>';
            while ($data = mysql_fetch_array($res)) {
                $selected='';
                if($currentcity==$data['id']) $selected=' selected="selected"';
// you probably don't need stripslashes() here if the data in the DB is correct. You might want htmlspecialchars() though.
                $return .= '<option name="city" value="'.$data['id'].'"'.$selected.'>'.stripslashes($data['name']).'</option>'; 
            }
            $return .= '</select>';
        }else{
            die("Query failed! ".mysql_error());
        }
        return $return;
    }
?>
ed: don't use "name" on <option>s

Tad Naff fucked around with this message at 16:51 on Dec 8, 2009

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:
Yeah. As far as I can tell it's trying to do an AJAXy autosuggest, but without the AJAX. Without the AJAX you're stuck with 20000 lines of PHP-generated Javascript, so page load times will suck no matter what. The JS hunting through each element doing an indexOf is just icing on the cake. A more intelligent method would be to make a simple PHP script accepting a parameter (call it $fragment after sanitizing etc) to output the contents of the <select> based on a database query like "SELECT location_name, location_code FROM locations WHERE location_name LIKE '%$fragment%' LIMIT 100". And only have it kick in after three or so keystrokes. The the onkeyup event can just call a function that will replace the content of the <select> with whatever the server says: onkeyup="populate_select_with_suggestions(selectId,this.value)" or something like that.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

a foolish pianist posted:

I've got some php code that produces a table, and it leaves a large quantity of whitespace at the top of the page, such that I have to scroll down to see the table.

The code is as follows:
code:
...
</tr><br>
...
and it produces what you see here: http://www.dataintensive.org/sumtest/sumtest.php

Anybody know what's going wrong?

That's a plain old HTML question.

ed
darn,b

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:
Just to get this out of the way, I am an infra-gifted street-coder who has only held onto his job because of his looks. I am in the process of writing a CMS. Yes, this is a dumb thing to do, reinventing the reinvented wheel etc etc, but really this problem domain is pretty underrepresented out there. Anyhow, my recurring issue is that I often code myself into a corner where I'm, say, writing PHP that generates javascript that outputs HTML. Something like:
php:
<?
$html='<a href="foo">foo\'s link</a>';
echo('<script type="text/javascript">');
if($some_condition){
echo('$("#foo").html("<?php echo $html ?>");'); // of course this fails later on
}else{
echo('$("#bar")
.html("<?php echo magicalescapingfunction($html?>"
.'<scr'.'ipt type=javascript">alert(\'BAR\');</scr'.'ipt>");'); // ditto, probably
}
echo('</script>');
?>
Hopefully that illustrates the problem -- escaping through multiple levels/languages. Currently my issue is about using PHP to return HTML wrapped in JSON to client javascript that replaces an element on the page (and jQuery is rejecting it as invalid JSON). I'd be really interested in hearing some approaches. Is there maybe something out there that does for javascript what PDO does for SQL?

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

supster posted:

:psyduck:

I know. Help.

Tad Naff fucked around with this message at 05:30 on Mar 17, 2010

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:
Just checking in to say my mood has improved considerably since I discovered encode_json(). My snippet up there was intentionally awful btw; even I know that writing javascript with javascript is not a sane thing, and writing PHP that writes javascript that writes javascript is (not sane)^2.

I was 80% done and then my client aka coworker got impressed with a similar tool's interface, so I'm trying to salvage the backend while adding all this AJAX crap to the front, which involves lots of HTML snippets being requested from the server via JSON rather than full page loads. I was not having much success writing my own escaper -- still don't know what I was doing wrong, but that's moot now.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:
So, uh, not that anyone should ever do this, but why does

php:
<?
$foo="bar";
$foo();
?>
work, while

php:
<?
${"bar"}();
?>
doesn't?

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Thirteenth Step posted:

I'm trying to attach some basic Javascript validation using this code:

code:
		<input type='submit' onclick="isAlphanumeric(document.getElementById('lettersnumbers'), 'Letters and numbers Only Please')" value='Log In'><input type='reset' value='Reset'>
</form>

You need <form onsubmit="return isAlphanumeric(...);"

(returning false stops the submit from proceeding).

Edit: change onclick to onsubmit and add it to the form tag. I always forget that.

Edit2:
\/\/ It's been a long day. Also I think this is the first time I had to edit my "Edit:".

Tad Naff fucked around with this message at 03:56 on Apr 1, 2010

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Thirteenth Step posted:

like:

code:
<p>
                <form action='' method='post' onsubmit="return isAlphanumeric(document.getElementById('lettersnumbers'), 'Letters and numbers Only Please')">
		Username: <input type='text' name='username'><br>
		Password: <input type='password' name='password'><br>
</p>
		<input type='submit' value='Log In'><input type='reset' value='Reset'>
                </form>
? (thanks for the replies)

Looks reasonable, except for that crazy <form> and <p> intermingling. <form> and <p> are both blocks by default so probably you don't need the <p>.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

duz posted:

That's presentational, which is what CSS is for:

code:
[...]
#userdataForm label {
text-align:right;
width:125px;
display:block;
float:left;
white-space:nowrap;
}
Edit: I just noticed, this is the PHP thread. Why arn't we discussing this in the web design thread?

To continue derailing, I did this in a recent project but was never satisfied about making labels fixed-width, especially if they run over the allotted width. Also you can't do this trick which lets you have clickable labels without assigning everything an id:

code:
<label>Label: <input type="text" name="blarg" /></label>
\/\/ I thought it was kind of tidy, myself. Is
code:
<label for="fuckingIdIHaveToSupply">Label: </label><input id="fuckingIdIHaveToSupply" type="text" name="blarg" />
better somehow?

Tad Naff fucked around with this message at 06:11 on Apr 2, 2010

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:
Well I don't know about you guys, but I'm stuck with some pre-PDO-capable systems and I find ADOdb to be pretty capable and programmer-friendly. And I tend to avoid OO in Web situations, what with all that construction on each page load.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

N.Z.'s Champion posted:

They want to display them in a nice gallery with hierarchy, metadata, thumbnails derived from RAW images, etc.

They were considering PHP Gallery :pwn:

Just to anticontribute, if they suggest or mention "contentDM", run away shooting. Unfortunately I haven't found much else out there that has a lot of traction in the digital image repository world. Omeka perhaps, in a couple more point releases...

Adbot
ADBOT LOVES YOU

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

ShoulderDaemon posted:

If a user sends the request script.php?foo=a&foo=b then $_GET["foo"] will be an honest-to-god array. This is trivial for a user to do, and doesn't require any script or programming or anything on the user's end. If the script is expecting $_GET["foo"] to be a string, then bad things could happen because various operations will not perform as the programmer expected. Explicitly casting it to a string removes this possibility.

What, I always had to do script.php?foo[]=a&foo[]=b to get $_GET['foo']=array('a','b')... did things change? I know I've seen Perl work like the above...

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply