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
Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
When writing code for a single system (this will never be distributed) where the database is controlled and set (it will always be mysql as long as I work here), is there any reason at all to use database abstraction instead of simply mysqli?

Adbot
ADBOT LOVES YOU

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



KuruMonkey posted:

\w Matches characters with accents which the original didn't, and \s matches all whitespace, so tab etc, which the original didn't.

I didn't think of that, but if he has any non-English users, then those extra letters are going to help.

KuruMonkey
Jul 23, 2004
Yeah, if it were me...I'd probably use '/[\w\d-\ ]+/', making the presumption that usernames would not want tab in, but that accents might be OK. But obviously I stuck to matching the same as he had.

Its still in my mind that you can probably match the no leading space and the no multiple spaces with a suitably arcane regex though.

But as you say; there is a regex thread.

KuruMonkey
Jul 23, 2004

Golbez posted:

When writing code for a single system (this will never be distributed) where the database is controlled and set (it will always be mysql as long as I work here), is there any reason at all to use database abstraction instead of simply mysqli?

1; does mysqli use bound parameters?

2; are you only ever going to write that one system? if not learn to write portably as soon as possible.

3; its NO EASIER to use mysqli than, say, PDO; so why not use the one thats more abstracted?


If the answer to 1 is yes, and you WANT to use mysqli, then its probably OK from a technical POV? (he said fishing for anyone who knows otherwise...)

SuckerPunched
Dec 20, 2006

Yep, it certainly does.

I like mysqli on it's own personally. While I don't use it "naked" in any personal projects - I don't see why you couldn't, given Golbez's situation remaining true.

SuckerPunched
Dec 20, 2006

quote != edit.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Golbez posted:

When writing code for a single system (this will never be distributed) where the database is controlled and set (it will always be mysql as long as I work here), is there any reason at all to use database abstraction instead of simply mysqli?

Basically emphasizing what KuruMonkey said. The real question to ask yourself is there any reason to use mysqli over PDO? One is not "easier" than the other, writing in them is almost exactly the same, so why not use the one that has a major advantage over the other (PDO).

SuckerPunched
Dec 20, 2006

fletcher posted:

Basically emphasizing what KuruMonkey said. The real question to ask yourself is there any reason to use mysqli over PDO? One is not "easier" than the other, writing in them is almost exactly the same, so why not use the one that has a major advantage over the other (PDO).

You just said they're practically identical. What's the major advantage for using what boils down to a framework, when he doesn't need the abstraction?

LP0 ON FIRE
Jan 25, 2006

beep boop
I haven't been able to get a cookie work from a page in one directory to another page in the root directory. If it's in the root directory, it works page to page in the root directory.

I use:
$expire=time()+60*60*24*30;
setcookie('user', $_POST["user"], $expire, '/', '.example.com');

LP0 ON FIRE fucked around with this message at 08:26 on Feb 27, 2009

KuruMonkey
Jul 23, 2004

SuckerPunched posted:

You just said they're practically identical. What's the major advantage for using what boils down to a framework, when he doesn't need the abstraction?

I wrote my 3 points in general ignorance of whether mysqli would do bound params (I took a year out 07-08, and mysqli seems to have arrived in that gap; and PDO along with it - certainly I dodn't know of either when I was working before, and now PDO is my new choice, so I never really looked at mysqli; so a thanks to SuckerPunched for taking my bait and helping me learn something with zero effort :))

As far as I'm concerned, as long as you can insulate yourself from embedding variables into strings for your query by hand, and there's something binding them and sanitising for you, whatever that is has already covered the 'must have' feature of an abstraction layer (the one you either had to do yourself or write lovely insecure code all day 2-3 years ago)

The rest of abstracting the DB is, IMO, niceties. If you really want the DB/data storage Abstracted (with a capital A) you'd be writing models on top of whatever abstraction layer you chose anyway...

So at that point the weighting I might be inclined to give 'already know it' goes way up.

KuruMonkey fucked around with this message at 09:40 on Feb 27, 2009

xiNickix
Oct 31, 2007
:DS< Ascii Titles = Poverty Avatars

quote:

Hi, I've got a question. I've stored a bunch of images in a database which I thought was a super cool idea, but now the web browser doesn't cache them. The images will never be modified or updated so I just want them to be cached and stay there but I'm not sure why they arn't. Anyways here's my code thanks a lot guys.

code:
header('Last-Modified: Wed, 28 Jan 1970 02:39:02GMT'); 
header('Expires: '.gmdate("D, d M Y H:i:s", time() + (3600 * 24)). ' GMT');	
header('Content-Control: cache, max-age='.(3600*24));
header('ETag: '.md5($Data->File->File));
header('Content-length: '.strlen($Data->File->File));
header('Pragma: cache');
header("Content-type: {$Data->File->Type}");
echo $Data->File->File;

Got it working now with... header("Cache-Control: public",true);
Not exactly sure what it does but whatevers.

xiNickix fucked around with this message at 13:47 on Feb 27, 2009

KarmaticStylee
Apr 21, 2007

Aaaaaughibbrgubugbugrguburgle!
I had to do work on a project where the header and footer includes were in the root as were the pages that they contained links to. The links were relative i.e. a href='contact.php'... to be able to refer to the links from pages several directories up, while referring to the same header file, i needed to dynamically return the path to the root... i know that the header shouldnt be in the root etc etc but... the real question i have, is there an easier way to return to root?

i hope i made clear my question with my crumby example

here is the code i made for what i was referring to above

code:
<? 
//FIND PATH TO ROOT, PASS PATH TO VAR $change_root
$current_dir = getcwd();
$root = $_SERVER['DOCUMENT_ROOT'];
if ($current_dir !== $root) {
	$folders_in_path = explode('/', $current_dir);
	foreach ($folders_in_path as $folder) {
		$i++;
		if ($folder == 'html') {
			$n = $i;
		}
	}
	$folders_above_the_root = $i - $n;
	while ($folders_above_the_root > 0) {
		$change_root.='../';
		$folders_above_the_root--;
	}
} 
?>
then for links in the header
code:
<a href="<? echo $change_root ?>page.php"</a>
again, i know i probably did things the hard way but yeah... how is the best way to change directory to root dynamically?

KarmaticStylee fucked around with this message at 03:48 on Mar 1, 2009

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker
Add a slash. <a href="/contact.asp">contact</a>.

Halo_4am
Sep 25, 2003

Code Zombie
Working with images in php is absolutely mindfucking me. I'm trying to auto-create thumbnails based on user uploaded images. I don't want to do this on view which is pretty well every example script out there, but rather create on upload, and then ftp the file to my webserver.

Spent a couple hours trying to put it all together, ended up just getting jpg only and pretty well copying the code from php's man page for imagecopyresampled.

Here's what I have thus far, (working, but jpg only).
php:
<?
//Usage example: $fileforftp = CreateThumb($user_submitted_file['tmp_name'],150,150);
//$$fileforftp will == something like '/tmp/img23ffsa3'


function CreateThumb($filename,$new_w,$new_h) {
    $width = $new_w;
    $height = $new_h;

    // Get new dimensions
    list($width_orig, $height_orig) = getimagesize($filename);

    // Resample
    $image_p = imagecreatetruecolor($width, $height);
    $image = imagecreatefromjpeg($filename);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

    // Capture Output instead of send to browser
    ob_start(); // Start capturing stdout. 
        imagejpeg($image_p, null, 80); // As though output to browser. 
        $img = ob_get_contents(); // the raw jpeg image data. 
    ob_end_clean();
    
    // Send Captured output to temp file
    $tmpfname = tempnam('/tmp','img');  //generate random tmp file : if /tmp not there, will default to system tmp
    $handle = fopen($tmpfname, "w");   //open new tmp file for writing
    fwrite($handle, $img); //write generated img data from ob_ capture
    fclose($handle);
    return $tmpfname;
}

?>
Ok, so no detection or anything. I started looking at mime-type detection and my mind pretty well melted. Can anybody take a shot at explaining how to detect if the image uploaded is png/gif/tiff and act accordingly? It's really this line: $image = imagecreatefromjpeg($filename); I'm concerned with. I don't particularly care if thumbnails go out in jpg only... as they're only thumbnails.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Halo_4am posted:

Ok, so no detection or anything. I started looking at mime-type detection and my mind pretty well melted. Can anybody take a shot at explaining how to detect if the image uploaded is png/gif/tiff and act accordingly? It's really this line: $image = imagecreatefromjpeg($filename); I'm concerned with. I don't particularly care if thumbnails go out in jpg only... as they're only thumbnails.

r1ch's image upload script in the first post does header based detection.
Also, why are you writing the thumbnail to the output buffer, then writing the buffer to a temp file? Why not just write the thumbnail directly there?

KarmaticStylee
Apr 21, 2007

Aaaaaughibbrgubugbugrguburgle!

Mercator posted:

Add a slash. <a href="/contact.asp">contact</a>.

hmm why does this not work for me? i am forced to use "../" for each level i need to travel down

BubbaGrace
Jul 14, 2006

Im writing to .xml using DOMDocument for interaction with JW Media Player. I am required to use this for my project. Anyway the player accepts an xml style format for its playlists. When I save out the xml file using DOMDocument Save the file is started with <?xml version="1.0"?>. Is there anyway that I can write my xml file without that?

code:
EDIT: CODE NO LONGER RELEVENT

BubbaGrace fucked around with this message at 02:23 on Mar 2, 2009

Mug
Apr 26, 2005
I'm having some trouble convincing cURL to use a cookiejar, and I'm not getting any help out of google or any of my usual support avenues as it seems that once file permissions are confirmed to be correct, COOKIEJAR should just magically work. I know I've got permissions all good because the first 3 lines of my code create the file successfully. My code is as follows, the my_cookies.txt file just remains blank no matter what I do.

code:
	$cookiejar = "./cookies/my_cookies.txt";
	$fp = fopen($cookiejar, 'w');
	fclose($fp);
	$url = "http://login.website.com.au/?&action=login";
 
	$postfields["username"] = "A username";
	$postfields["password"] = "A password";
 
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiejar);
	curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiejar);
	curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_TIMEOUT, 100);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
	$data = curl_exec($ch);
	echo(">>>". curl_error($ch) ."<<<");
	curl_close($ch);

gibbed
Apr 10, 2006

Enable curl's verbose mode to see if it's actually returning any cookies to you.

Mug
Apr 26, 2005

gibbed posted:

Enable curl's verbose mode to see if it's actually returning any cookies to you.

Turned out that although fopen likes the filename format, cURL wanted absolute file location. Works fine now.
thanks for your suggestion.

MrMoo
Sep 14, 2000

Halo_4am posted:

Can anybody take a shot at explaining how to detect if the image uploaded is png/gif/tiff and act accordingly?
code:
list($src_w, $src_h, $src_type) = getimagesize ($src);

switch ($src_type) {
case IMAGETYPE_JPEG:	$original = imagecreatefromjpeg ($src); break;
...
default: throw new Exception ("Image type $type is unsupported.");
}
Using ImageMagick is easier:

code:
$im = new Imagick();
try {
  $im->readImage($file_name);
} catch (ImagickException $e) {
  throw new Exception(_('Invalid or corrupted image file, please try uploading another image.'));
}

MrMoo fucked around with this message at 04:23 on Mar 2, 2009

Fangs404
Dec 20, 2004

I time bomb.
I'm a PHP noob. I'm writing my first major PHP app right now, and I have what's most likely the single most popular question in this thread. However, search has been down since the dawn of time, so I can't find the answer (and it's not in the last couple pages).

What's the best way to sanitize input? I've got some POST input coming into a PHP page, and I want to make sure it's clean. Googling "php sanitize" returns a billion different ideologies and theories. http://us2.php.net/manual/en/function.filter-input.php paired with FILTER_SANITIZE_STRING or FILTER_SANITIZE_SPECIAL_CHARS looks pretty nice, but I want to make sure that does a good enough job.

Fangs404 fucked around with this message at 08:02 on Mar 2, 2009

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Fangs404 posted:

I'm a PHP noob. I'm writing my first major PHP app right now, and I have what's most likely the single most popular question in this thread. However, search has been down since the dawn of time, so I can't find the answer (and it's not in the last couple pages).

What's the best way to sanitize input? I've got some POST input coming into a PHP page, and I want to make sure it's clean. Googling "php sanitize" returns a billion different ideologies and theories. http://us2.php.net/manual/en/function.filter-input.php paired with FILTER_SANITIZE_STRING or FILTER_SANITIZE_SPECIAL_CHARS looks pretty nice, but I want to make sure that does a good enough job.

When I want to make sure it's safe to output to a browser, I use htmlspecialchars()

When I want to make sure it's safe to put in a database, use prepared statements.

php:
<?
//good idea to do some basic checks on $_POST['username'] and $_POST['age'] 
//to make sure it's the right length, age is actually a number, etc
//and return a useful error message to the user
$database = new PDO("connection;string");
$query = $database->prepare("insert into user (username, age) values (:username, :age)");
//PDO will automatically handle sanitizing it for us
$query->bindParam(":username", $_POST['username']);
$query->bindParam(":age", $_POST['age']);
if ($query->execute()) {
} else {
}
?>

fletcher fucked around with this message at 10:05 on Mar 2, 2009

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH

fletcher posted:

When I want to make sure it's safe to output to a browser, I use htmlspecialchars()

When I want to make sure it's safe to put in a database, use prepared statements.

php:
<?
//good idea to do some basic checks on $_POST['username'] and $_POST['age'] 
//to make sure it's the right length, age is actually a number, etc
//and return a useful error message to the user
$database = new PDO("connection;string");
$query = $database->prepare("insert into user (username, age) values (:username, :age)");
//PDO will automatically handle sanitizing it for us
$query->bindParam(":username", $_POST['username']);
$query->bindParam(":age", $_POST['age']);
if ($query->execute()) {
} else {
}
?>
Just make sure you understand the difference between sanitizing for database input and sanatizing for browser output. When fletcher says "PDO will automatically handle sanitizing it for us" he means for database input, not for browser output.

You may also want to consider input-time sanitization vs render-time sanitization - there are advantages and disadvantages with both.

supster fucked around with this message at 10:16 on Mar 2, 2009

blitrig
Jul 2, 2003
I'm still a PHP noob, so this is probably a ridiculous question. I've googled and dicked around with the code for a long time now, and I can't really figure it out. It's starting to bug me a lot.

So far, my script generates an array of URLs that point to XML documents. I'm trying to figure out a way to pull chunks of info out of each doc, and display them in html.

For example,

The array looks like this:

Array ( [0] => http://example/1.xml [1] => http://example/2.xml [2] => http://example/3.xml => etc etc etc)


I want to pull out the following elements (user info, one per doc) from each XML doc:

<user>
<uid>352</uid>
<name>John Farfleton</name>
<phone>415-555-1212</phone>
<location>San Francisco, CA</location>
</user>

and then output a list of users, with their UID/name/phone/location to the browser.


I really appreciate any help with this, if what I'm trying to do actually makes any sense.

gibbed
Apr 10, 2006

php:
<?php
    foreach ($urls as $url)
    {
        $content = @file_get_contents($url); // note the @ will supress error/warnings that would normally be outputted
        if ($content === false)
        {
            // failed to obtain content of xml
        }
        else
        {
            $xml = new SimpleXMLElement($content);
            $name = (string)$xml->name// it might be $xml->user->name if user isn't the root element.
            // etc...
        }
    }
?>

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
I just watched this talk by Rasmus on PHP optimization and thought it was pretty interesting, even if it was just 60 minutes of repeating what you already know or suspected. There are some cool notes and comparisons in there. Maybe some of you will find it worth watching.

http://www.archive.org/details/simple_is_hard

Aredna
Mar 17, 2007
Nap Ghost
For my Web Development class we are creating projects for real world companies and organizations that will be put into production.

We're currently researching tools to use for the project as we are allowed to use anything necessary to get the job done.

Our project is to create a custom survey building tool along the lines of Survey Monkey. It will be used to create surveys, tests, and feedback forms, both internally and externally. Surveys will be taken by over 5000 employees and many more (request out for estimates) customers.

It will be ran on an LAMP environment. We do not have to worry about log-in authentication, but will need to validate the user can access the current page and survey they are trying to access.

No one in our group has used PHP previously, however we have used many other languages. I have fairly extensive database knowledge which will help quite a bit.

Currently we are looking at using CodeIgniter as our Framework and building everything else ourselves. As of today we have approximately 7 working weeks to complete the project to be ready for deployment.

A Google search turns up LimeSurvey as a possible tool to use. Has anyone used this product before? Are there any other FOSS solutions that I'm overlooking that would greatly simplify the project?

KarmaticStylee
Apr 21, 2007

Aaaaaughibbrgubugbugrguburgle!
oops figured out the problem.. was retarded.

KarmaticStylee fucked around with this message at 02:47 on Mar 6, 2009

Fangs404
Dec 20, 2004

I time bomb.
Ok, this is loving weird enough and long enough that I think it needs its own thread.

Fangs404 fucked around with this message at 08:50 on Mar 7, 2009

nitrogen
May 21, 2004

Oh, what's a 217°C difference between friends?
First off, I'm a complete newb at PHP. Like, I started playing with it about 2 hours ago to solve a specific problem.

I have an application I hacked up that queries my electric meter for the current power usage, and puts the information into a mysql database.

I'm now working on a web page that will display this information as it gets updated

I'd like to autorefresh this every time "ID" (the primary key for the table) changes, or at least every few second or so.

code:
<?php
mysql_connect(".", "..", "...") or die(mysql_error());
mysql_select_db("METERDB") or die(mysql_error());

$result=mysql_query("SELECT kwnowdsp,VrmsNowDsp  FROM meter  ORDER BY ID DESC LIMIT 1;");
echo "<p>";
$row = mysql_fetch_array( $result );
echo "Current Usage: ".$row['KWUsage']."<br />";
echo "Current Voltage: ".$row['VRMS-Usage']."<br />";
?>
This is what I have so far.
Can anyone point me to a method to do what I want to do? I'd love for it to be neat and use AJAX (which I also know nothing about) so the page isn't autorefreshing all the time. I can use that as I build out the page more to show historical usage, graph things, etc.

Please go easy on this PHP newb. I appreciate the help.

Rat Supremacy
Jul 15, 2007

The custom title is an image and/or line of text that appears below your name in the forums

Golbez posted:

When writing code for a single system (this will never be distributed) where the database is controlled and set (it will always be mysql as long as I work here), is there any reason at all to use database abstraction instead of simply mysqli?

I'd personally use PDO or something and a SQL wrapper class to avoid using actual SQL statements in your PHP code (as they can be messy).

$statement->select("whatever")->from("tablename") etc.

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH

haywire posted:

I'd personally use PDO or something and a SQL wrapper class to avoid using actual SQL statements in your PHP code (as they can be messy).

$statement->select("whatever")->from("tablename") etc.

You really think that is less "messy" than "select whatever from tablename"?

Zorilla
Mar 23, 2005

GOING APE SPIT

nitrogen posted:

This is what I have so far.
Can anyone point me to a method to do what I want to do? I'd love for it to be neat and use AJAX (which I also know nothing about) so the page isn't autorefreshing all the time.
You can either do what my cable modem diagnostics page does and use meta refresh tags in the HTML head (which is really annoying and makes nonstop clicking noises in IE) or look into jQuery for really simplified AJAX calls. I made a sloppy example:

php:
<?php
mysql_connect(".""..""...") or die(mysql_error());
mysql_select_db("METERDB") or die(mysql_error());

$result mysql_query("SELECT kwnowdsp, VrmsNowDsp FROM meter ORDER BY ID DESC LIMIT 1;");
$row mysql_fetch_array$result );

if ($_GET["ajax"] == "true") { // Simplified AJAX response
?>
<p>Current Usage: <?php echo $row['KWUsage']; ?><br />
Current Voltage: <?php echo $row['VRMS-Usage']; ?></p>
<?php
} else { // Full synchronous response
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Meter</title>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<div id="info">
    <p>Current Usage: <?php echo $row['KWUsage']; ?><br />
    Current Voltage: <?php echo $row['VRMS-Usage']; ?></p>
</div>
<script type="text/javascript">
//<![CDATA[
setInterval(function() {
    $.ajax({
        type: "GET",
        url: "<?php echo basename(__FILE__); ?>",
        data: "ajax=true",
        success: function(response) {
            $('#info').html(response);
        }
    });
}, 10000); // Every 10 seconds
//]]>
</script>
</body>
</html>
<?php
}
?>

More jQuery help can be found here. I definitely think it's the way to go, especially if you're going to be doing charts.

Zorilla fucked around with this message at 04:19 on Mar 8, 2009

nitrogen
May 21, 2004

Oh, what's a 217°C difference between friends?
Thanks for your example, but it's not working; it's not refreshing.

Remember, I'm a complete newb when it comes to this, how can I troubleshoot what the problem might be?

Thanks again.

I do have jquery installed in js/jquery.js; its a symlink to the real version I downloaded.

Internet Headache
May 14, 2007

haywire posted:

I'd personally use PDO or something and a SQL wrapper class to avoid using actual SQL statements in your PHP code (as they can be messy).

$statement->select("whatever")->from("tablename") etc.

SQL abstraction layers in PHP are completely pointless. I can't think of any reason to use them except if you have some mortal fear of COBOL-like syntax or if you're trying to kill your script performance. Once you get to any level of complexity, COBOL begins to look like a less "messy" language.
php:
<?
$statement->select("whatever")->from("tablename")->as('t')->join('left','butt')->as('b')
          ->on('b.butt_id','t.butt')->on('b.butt_id','null',-1)->where('b.butt_butt','1')
          ->group('b.butt_butt')->order('b.butt_id')
?>

Internet Headache fucked around with this message at 20:19 on Mar 7, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

nitrogen posted:

Thanks for your example, but it's not working; it's not refreshing.

Remember, I'm a complete newb when it comes to this, how can I troubleshoot what the problem might be?

Thanks again.

I do have jquery installed in js/jquery.js; its a symlink to the real version I downloaded.

Open Firefox's error console. Clear the errors and watch what comes in when you refresh the page. I never tested my example, so it could be full of typos. Ignore "Error in parsing value for property 'filter'" if you see it. jQuery just does that sometimes for some reason.

Also, on the line that says url: "<?php echo basename(__FILE__); ?>", is the resulting output correct? i.e., if your page is index.php, does that line say url: "index.php" when you view source?

edit: I just found and fixed a missing comma, so yeah, full of typos. All it takes is something like this for Javascript to completely stop, so if something isn't working, check for fatal errors first.

Zorilla fucked around with this message at 23:22 on Mar 7, 2009

nitrogen
May 21, 2004

Oh, what's a 217°C difference between friends?

Zorilla posted:

Open Firefox's error console. Clear the errors and watch what comes in when you refresh the page. I never tested my example, so it could be full of typos. Ignore "Error in parsing value for property 'filter'" if you see it. jQuery just does that sometimes for some reason.

Also, on the line that says url: "<?php echo basename(__FILE__); ?>", is the resulting output correct? i.e., if your page is index.php, does that line say url: "index.php" when you view source?

edit: I just found and fixed a missing comma, so yeah, full of typos. All it takes is something like this for Javascript to completely stop, so if something isn't working, check for fatal errors first.

Rock on, I'm closer. It refreshes once, but then quits. NOthing in the error console when it does.
EDIT: I got it working by removing the ajax test at the top, and just using the jquery bits at the bottom. As I progress with this project, I'm sure I'll have more stupid questions. I appreciate your patience so far.

nitrogen fucked around with this message at 03:45 on Mar 8, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

nitrogen posted:

Rock on, I'm closer. It refreshes once, but then quits. NOthing in the error console when it does.
EDIT: I got it working by removing the ajax test at the top, and just using the jquery bits at the bottom. As I progress with this project, I'm sure I'll have more stupid questions. I appreciate your patience so far.

Oops, I used setTimeout when I should have used setInterval. I was cribbing from old code of mine where I was calling setTimeout recursively to get something to run on an interval instead (needed to reset the timer when the user clicked something). This is why it was only updating once. I'll change my example.

When you said you got rid of the ajax test, you mean the line that says if ($_GET["ajax"] == "true")? If so, I'm not sure I'm following. The idea was to call index.php?ajax=true, and it would return just the part inside <div id="info">, and then only that section would get updated.

Zorilla fucked around with this message at 04:25 on Mar 8, 2009

Adbot
ADBOT LOVES YOU

DaTroof
Nov 16, 2000

CC LIMERICK CONTEST GRAND CHAMPION
There once was a poster named Troof
Who was getting quite long in the toof

supster posted:

You really think that is less "messy" than "select whatever from tablename"?

SQL abstraction can be useful when applications need to insert clauses dynamically, assuming it's smart enough to let you define clauses in an arbitrary order.

php:
<?
// Select all invoices in the past thirty days if the user is an administrator,
// or select invoices on which the user is designated a manager otherwise
$select = new Select();
$select->fields("invoice.id, customer.name");
$select->from("invoice");
$select->innerJoin("customer", "invoice.customer = customer.id");
$select->where("invoice.datecreated > ?", $thirty_days_ago);
if ($user_is_not_administrator) {
    $select->innerJoin("invoice_manager", "invoice_manager.invoice = invoice.id");
    $select->where("invoice_manager.manager = ?", $user_id);
}
?>
You could build the same query as a string, but abstraction puts the focus on application logic over SQL syntax.

DaTroof fucked around with this message at 18:48 on Mar 8, 2009

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