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
Sab669
Sep 24, 2009

First Time Caller posted:

The key to reading the PHP documentation is to just sit and read the first couple paragraphs of the page FOR COMPREHENSION and not be a tard who immediately scrolls to the examples at the bottom of the page.

I can't tell you how annoyed I am by junior developers at my job who do that.

I'll admit it, I'm a huge perpetrator of that. I am definitely getting better at reading all the notes, but it's so much easier to just look at sample code for some things :(

I think that as a student I've just read too many poorly written books.

Adbot
ADBOT LOVES YOU

revmoo
May 25, 2006

#basta
I've always thought PHP docs were very good. There have been plenty of weaknesses, but at the same time it is a very practical, comprehensive and easy to use reference. Key word. If you use it as a reference and not a learning tool you will be fine.

Doh004
Apr 22, 2007

Mmmmm Donuts...
I love the PHP docs. If I'm ever unsure of a function, I just goto php.net/whateverfunctionimlooking for. Usually, it gets to me what I actually need to see.

qntm
Jun 17, 2009

First Time Caller posted:

The key to reading the PHP documentation is to just sit and read the first couple paragraphs of the page FOR COMPREHENSION and not be a tard who immediately scrolls to the examples at the bottom of the page.

I can't tell you how annoyed I am by junior developers at my job who do that.

This is why I write my documentation so that if you just read the examples you still get the full picture.

This is also why I find the Perl documentation infuriating because they often provide no examples at all.

KuruMonkey
Jul 23, 2004
Really its a very good investment in time to just spend an evening or weekend afternoon quietly browsing around the PHP docs function reference, just to get an overview of what is in there, and roughly where it is.

Seriously; this list at a bare minimum:

http://www.php.net/manual/en/ref.var.php
http://www.php.net/manual/en/book.pdo.php
http://www.php.net/manual/en/ref.filesystem.php
http://www.php.net/manual/en/book.strings.php
http://uk3.php.net/manual/en/book.array.php
http://uk3.php.net/manual/en/ref.funchand.php
http://www.php.net/manual/en/book.math.php
http://www.php.net/manual/en/ref.datetime.php (might want to replace with the DateTime class...)
http://www.php.net/manual/en/ref.classobj.php

Every PHP programmer should have at least skimmed the functions listed on those pages, to at least be aware of what is in there.

Because its once you know what's in there that you can google 'php FUNCNAME' and go straight where you need to. Without that initial skim session, you're stuck with some random blogger's bodge of a solution.

Mindisgone
May 18, 2011

Yeah, well you know...
That's just like, your opinion man.
So this one has really been frying my brain and I think I just need a fresh set of eyes on it cause it seems like it should be simple. All I want is for a new text input box to be generated when the form is submitted (the input box can even just say "hello" I don't care). It does this but I want a new box (or string) on a new line for each time the button was clicked. Right now no matter how many times you submit the form, the box (or string) is only displayed once.

code:
if (isset($_POST['button']))
{
	skillSet();
	\n;
}

<form method='post' action='mypage.php'><input type='submit' name='button' value='Add Skill' /><br /><br /></form>

function skillSet()
{
	echo "Skill Name: <input type='text' maxlength='50' name='skillname' value='$skillname' /><br /><br />";
}
For simplicity lets just have the skillSet function echo "hello".

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
What's a good PHP/MySQL profiler? I'm tired of trying to find bottlenecks on my own.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
MySQL profiler? EXPLAIN EXTENDED.

PHP profiler? xdebug and anything that speaks with the resulting cachegrind files.

First Time Caller
Nov 1, 2004

Mindisgone posted:

For simplicity lets just have the skillSet function echo "hello".

HTTP is a stateless protocol, so no matter how many times you press the submit button, the web server forgets you may have done that already.

You'll need to start a session in order to count how many times the button has been pressed. Then you can iterate that number of times to display that many buttons.

code:
<?php
session_start();

if(!isset($_SESSION['counter']))
{
   $_SESSION['counter'] = 0;
}

if(isset($_POST['submit']))
{
   $_SESSION['counter']++;
}

?>

You have pressed submit <strong><?php echo $_SESSION['counter']; ?></strong> times!

<form action="" method="POST">
    <input type="submit" name="submit" value="Submit" />
</form>
Alternatively, you could pass a variable in the request.

code:
<?php
if(!isset($_POST['counter']))
{
    $counter = 0;
}
else
{
    $counter = $_POST['counter'] + 1;
}
?>

You have pressed the button <strong><?php echo $counter; ?></strong> times!

<form action="" method="POST">
    <input type="hidden" name="counter" value="<?php echo $counter; ?>" />
    <input type="submit" name="submit" value="Submit" />
</form>

First Time Caller fucked around with this message at 18:52 on Jun 12, 2012

Mindisgone
May 18, 2011

Yeah, well you know...
That's just like, your opinion man.
Excellent, thank you very much. The versatility of sessions has escaped me.

Mindisgone
May 18, 2011

Yeah, well you know...
That's just like, your opinion man.

First Time Caller posted:


code:
<?php
if(!isset($_POST['counter']))
{
    $counter = 0;
}
else
{
    $counter = $_POST['counter'] + 1;
}
?>

You have pressed the button <strong><?php echo $counter; ?></strong> times!

<form action="" method="POST">
    <input type="hidden" name="counter" value="<?php echo $counter; ?>" />
    <input type="submit" name="submit" value="Submit" />
</form>

I suppose this method still requires a session being open. I do have a session started and it only counts to 1...I am going to try the first method you suggested

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

Mindisgone posted:

I suppose this method still requires a session being open. I do have a session started and it only counts to 1...I am going to try the first method you suggested

That particular method doesn't need a session, no. The idea is that when it creates the form, it already sets the counter, so that when it's clicked, it returns that plus one, and regenerates the form with the new counter.

Dad Jokes
May 25, 2011

I'm a complete newbie to PHP, but does anyone have experience working with the Imagick module? I've been trying to teach myself PHP by doing a small image-processing/generation project, but I'm having a hell of a time trying to get Imagick to play nicely, and I'm at my wit's end.

Essentially, I can't read in images using a web URL. I can read in and display local images fine, but nothing with a URL, as I consistently get an "Invalid CRT parameters detected" error, and Googling turns up very little. The best lead I've got so far is that it may be a Windows specific bug, but I wanted to see if anyone could confirm this before I decide I'm SOL.

I've posted a way more comprehensive writeup of the problem (with examples) on Stackoverflow, but if anyone here is able to help out as well, I'd really appreciate it. :)

http://stackoverflow.com/questions/11025568/how-to-fix-invalid-crt-parameters-detected-error-when-using-imagicks-readimag

(For reference, I'm developing on 64-bit Windows 7 with XAMPP 1.7.7 and Imagemagick 6.6.2)

KuruMonkey
Jul 23, 2004

Dad Jokes posted:

Essentially, I can't read in images using a web URL. I can read in and display local images fine, but nothing with a URL, as I consistently get an "Invalid CRT parameters detected" error, and Googling turns up very little. The best lead I've got so far is that it may be a Windows specific bug, but I wanted to see if anyone could confirm this before I decide I'm SOL.

Do you know for sure that URL file access is allowed through fopen in your config?
(check by running phpinfo())

Do you have ALL error reporting on + shown?
if not; do so http://php.net/manual/en/function.error-reporting.php
fopen raises a warning, its quite easy to have PHP configured to ignore these without knowing, and that leaves failed fopen() just returning FALSE to you

I am, of course, partaking in the 'have you tried switching it off and on again' of file handling debugging, so feel free to ignore me if you know the file handle is opening correctly (though in your SO post; you aren't checking!)

Aside:
I always wrap up an fopen call like this now:
php:
<?
$fh = @fopen($path, $mode);
if($fh === FALSE) {
  throw new Exception("generic fopen failed message - replace with something better");
}
// use the handle
fclose($fh);
?>
I like to explicitly mask the error from fopen, and turn it into an exception. Because:
A - I know fopen is never going to raise a warning(edit: because the @fopen suppresses it), and no matter the config, that call will not halt execution unexpectedly.
B - I then know that I must always handle the fail case, and exceptions can be caught, or not, more elegantly than warnings.

Puts me in control, basically.

Dad Jokes
May 25, 2011

I never thought to check that (again, PHP newbie here), but yeah, I don't think it's fopen that's the issue. phpinfo() reports that "allow_url_fopen" is set to On, and I'm still getting the same "Invalid CRT Parameter" error message on the readImageFile line after changing my code to the following:

php:
<?php
    ini_set('display_errors''On');
    error_reporting(E_ALL E_STRICT);
    
    $im = new Imagick();
    
    //$im->newPseudoImage(1000, 1000, "magick:rose"); //this works!
    //$im->readImage("images\\wheels.jpg"); //this works!

    $handle = @fopen("http://www.google.com/images/srpr/logo3w.png""rb");
    if($handle === FALSE) {
      throw new Exception("generic fopen failed message - replace with something better");
    }
    
    $im->readImageFile($handle); //this crashes!
    fclose($handle);
    
    $im->setImageFormat("png");
    $type $im->getFormat();
    header("Content-type: $type");
    echo $im->getImageBlob();
?>
Thanks for trying to help, though. :)

Doh004
Apr 22, 2007

Mmmmm Donuts...
What OS are you running this on? If it's Windows, the Googles say this happens a lot on it.

Dad Jokes
May 25, 2011

Yeah, I'm developing on 64-bit Windows 7, and I was kind of afraid that was the case. The only google info I could come up with was that it was something possibly Windows related, and I was really hoping that it would turn out to be something fixable without changing OS's, but I guess I'm kind of screwed in that regard, then.

Doh004
Apr 22, 2007

Mmmmm Donuts...
Maybe try out something other than fopen? http://us2.php.net/file_get_contents could possibly work?

*edit* Also, make sure there aren't any firewall rules preventing this from working (not sure if it has anything to do with it, can't hurt to be sure)

Doh004 fucked around with this message at 19:27 on Jun 14, 2012

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!
Use curl, some places have allow_url_fopen disabled in PHP. I do some development on my Windows 7 64-bit machine using XAMPP and curl works everytime no matter what I am doing.

revmoo
May 25, 2006

#basta
I have a database of every zip code w/ long/lat and a php lib that does the math to calc distance. This all works fine, though it takes half a second per query and I often want to run 20+ at once which mildly affects UX.

Would it be possible to take a set of zip codes and pre-calculate the distance from that zip to every zip in the US and then dump those numbers into a new (massive?) table to query against? I'm fairly certain the queries would be much faster but I'm not sure on how big that would make the DB. Is this one of those O(n) problems I'm always hearing about? I think I could write the code to generate the new table but I'm worried that might make for an impossibly-sized db. The current zip DB is 11mb and I would need 250 or so pre-generated 'zip rainbow tables' which seems to me would be like 2.5gb total but I suck at math.

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.

revmoo posted:

I have a database of every zip code w/ long/lat and a php lib that does the math to calc distance. This all works fine, though it takes half a second per query and I often want to run 20+ at once which mildly affects UX.

Would it be possible to take a set of zip codes and pre-calculate the distance from that zip to every zip in the US and then dump those numbers into a new (massive?) table to query against? I'm fairly certain the queries would be much faster but I'm not sure on how big that would make the DB. Is this one of those O(n) problems I'm always hearing about? I think I could write the code to generate the new table but I'm worried that might make for an impossibly-sized db. The current zip DB is 11mb and I would need 250 or so pre-generated 'zip rainbow tables' which seems to me would be like 2.5gb total but I suck at math.

First, I would look into optimizing those queries and seeing why they're slow. Since a list of zip codes is a table that very rarely gets updated or inserted to, you can probably index just about everything.

Next, I wouldn't pre-compute all of the zip codes. That's a nightmare to deal with and takes up unnecessary space. Why not just cache the calculations? Rather than pre-compute them, every time someone requests the distance between two zip codes, first check if it's in a cache (either in a table or in a Redis/memcache database), and if so, quickly return that value, otherwise do the full computation.

Bob Morales
Aug 18, 2006


Just wear the fucking mask, Bob

I don't care how many people I probably infected with COVID-19 while refusing to wear a mask, my comfort is far more important than the health and safety of everyone around me!

revmoo posted:

I have a database of every zip code w/ long/lat and a php lib that does the math to calc distance. This all works fine, though it takes half a second per query and I often want to run 20+ at once which mildly affects UX.

Would it be possible to take a set of zip codes and pre-calculate the distance from that zip to every zip in the US and then dump those numbers into a new (massive?) table to query against? I'm fairly certain the queries would be much faster but I'm not sure on how big that would make the DB. Is this one of those O(n) problems I'm always hearing about? I think I could write the code to generate the new table but I'm worried that might make for an impossibly-sized db. The current zip DB is 11mb and I would need 250 or so pre-generated 'zip rainbow tables' which seems to me would be like 2.5gb total but I suck at math.

How accurate do they need to be?

butt dickus
Jul 7, 2007

top ten juiced up coaches
and the top ten juiced up players

revmoo posted:

I have a database of every zip code w/ long/lat and a php lib that does the math to calc distance. This all works fine, though it takes half a second per query and I often want to run 20+ at once which mildly affects UX.

Would it be possible to take a set of zip codes and pre-calculate the distance from that zip to every zip in the US and then dump those numbers into a new (massive?) table to query against? I'm fairly certain the queries would be much faster but I'm not sure on how big that would make the DB. Is this one of those O(n) problems I'm always hearing about? I think I could write the code to generate the new table but I'm worried that might make for an impossibly-sized db. The current zip DB is 11mb and I would need 250 or so pre-generated 'zip rainbow tables' which seems to me would be like 2.5gb total but I suck at math.

It might be faster to do it in the database instead of PHP. This query completes for me in < 100 milliseconds.
SQL code:
SELECT vendors.*,
  round(acos(sin(radians(vendors.latitude)) *
  sin(radians(sites.latitude)) +
  cos(radians(vendors.latitude)) *
  cos(radians(sites.latitude)) *
  cos(radians(sites.longitude-vendors.longitude))) * 3956.6, 1) as distance
FROM
  sites,
  vendors
WHERE sites.id = :site
HAVING distance <= 200
ORDER BY distance
If you're going to store the distance from each zip to every other zip, it's going to be n(n-1)/2 pairs, and with ~ 44000 zip codes, you're looking at about a billion records. Assuming 26 bytes per record (5 for each zip and 16 for distance) that's close to 25 GB of uncompressed data not even counting indexes.

revmoo
May 25, 2006

#basta

Doctor rear end in a top hat posted:

It might be faster to do it in the database instead of PHP. This query completes for me in < 100 milliseconds.
SQL code:
SELECT vendors.*,
  round(acos(sin(radians(vendors.latitude)) *
  sin(radians(sites.latitude)) +
  cos(radians(vendors.latitude)) *
  cos(radians(sites.latitude)) *
  cos(radians(sites.longitude-vendors.longitude))) * 3956.6, 1) as distance
FROM
  sites,
  vendors
WHERE sites.id = :site
HAVING distance <= 200
ORDER BY distance
If you're going to store the distance from each zip to every other zip, it's going to be n(n-1)/2 pairs, and with ~ 44000 zip codes, you're looking at about a billion records. Assuming 26 bytes per record (5 for each zip and 16 for distance) that's close to 25 GB of uncompressed data not even counting indexes.

Very helpful. I'm actually doing the math in SQL now but it takes about .5 seconds per request(6-7 distance calculations per request). I'll have a look at the query in the morning and see if it's different than the one you posted. Thanks.

butt dickus
Jul 7, 2007

top ten juiced up coaches
and the top ten juiced up players

revmoo posted:

Very helpful. I'm actually doing the math in SQL now but it takes about .5 seconds per request(6-7 distance calculations per request). I'll have a look at the query in the morning and see if it's different than the one you posted. Thanks.
It's a Haversine formula and takes the curvature of the earth into account. Mine gives miles and that query is just to find eligible vendors within a set distance. If you want something other than miles, you will have to change the 3956.6 number to the radius of the Earth in whatever unit you want. Depending on the distances involved and the necessary accuracy, there are a number of different methods you can use to calculate distance over a sphere (more accurate) or a sphere projected on plane (less accurate). Zip codes aren't too terribly precise to begin with, so maybe try a simpler algorithm and see if it goes faster.

revmoo
May 25, 2006

#basta

Doctor rear end in a top hat posted:

It's a Haversine formula and takes the curvature of the earth into account. Mine gives miles and that query is just to find eligible vendors within a set distance. If you want something other than miles, you will have to change the 3956.6 number to the radius of the Earth in whatever unit you want. Depending on the distances involved and the necessary accuracy, there are a number of different methods you can use to calculate distance over a sphere (more accurate) or a sphere projected on plane (less accurate). Zip codes aren't too terribly precise to begin with, so maybe try a simpler algorithm and see if it goes faster.

Wow thanks a ton for this insight. Accuracy is not very important since it's rare than I'd even be querying in two states at the same time. I'd be happy to trade accuracy for speed in this case.

Dad Jokes
May 25, 2011

Doh004 posted:

Maybe try out something other than fopen? http://us2.php.net/file_get_contents could possibly work?

*edit* Also, make sure there aren't any firewall rules preventing this from working (not sure if it has anything to do with it, can't hurt to be sure)

Sorry about the non-response, I got a bit swamped with work for the last few days, but I just wanted to give an update and say that file_get_contents totally worked for me, and I'm no longer getting the "Invalid CRT Parameters" error.

Working code:

php:
<?php
    ini_set('display_errors''On');
    error_reporting(E_ALL E_STRICT);
    
    $im = new Imagick();
    
    //$im->newPseudoImage(1000, 1000, "magick:rose"); //this works!
    //$im->readImage("images\\wheels.jpg"); //this works!
    
    $url "http://www.google.com/images/srpr/logo3w.png";
    $source = @file_get_contents($url);
    if(!$source){
        throw new Exception("failed to retrieve contents of $url");
    }

    $im->readImageBlob($source);
    
    $im->setImageFormat("png");
    $type $im->getFormat();
    header("Content-type: $type");
    echo $im->getImageBlob();
?>

DarkLotus posted:

Use curl, some places have allow_url_fopen disabled in PHP. I do some development on my Windows 7 64-bit machine using XAMPP and curl works everytime no matter what I am doing.

However, considering this possibility, I'm probably going to update my code to use curl and see how that turns out. Edit: Works just fine!

Thanks for the help, guys! :)

Dad Jokes fucked around with this message at 17:53 on Jun 16, 2012

Revitalized
Sep 13, 2007

A free custom title is a free custom title

Lipstick Apathy
I see an ad for some amazon e-book about learning PHP for 2.99. Anyone here know if it's a really good starter book? Or did one of you guys write it?

revmoo
May 25, 2006

#basta
Get PHP Objects, Patterns and Practice.

Doh004
Apr 22, 2007

Mmmmm Donuts...

Dad Jokes posted:

Sorry about the non-response, I got a bit swamped with work for the last few days, but I just wanted to give an update and say that file_get_contents totally worked for me, and I'm no longer getting the "Invalid CRT Parameters" error.

Working code:

php:
<?php
    ini_set('display_errors''On');
    error_reporting(E_ALL E_STRICT);
    
    $im = new Imagick();
    
    //$im->newPseudoImage(1000, 1000, "magick:rose"); //this works!
    //$im->readImage("images\\wheels.jpg"); //this works!
    
    $url "http://www.google.com/images/srpr/logo3w.png";
    $source = @file_get_contents($url);
    if(!$source){
        throw new Exception("failed to retrieve contents of $url");
    }

    $im->readImageBlob($source);
    
    $im->setImageFormat("png");
    $type $im->getFormat();
    header("Content-type: $type");
    echo $im->getImageBlob();
?>
However, considering this possibility, I'm probably going to update my code to use curl and see how that turns out. Edit: Works just fine!

Thanks for the help, guys! :)

Glad you ended up getting it to work :)

Mindisgone
May 18, 2011

Yeah, well you know...
That's just like, your opinion man.
code:
$result6 = queryMysql("SELECT numbers FROM numbertable WHERE user='$user'");
	$num6 = mysql_num_rows($result6);
	
	for ($x = -1 ; $x < $num6 ; ++$x)
	{
		$v = mysql_fetch_row($result6);
	}
	echo array_sum($v[$num6]) . " total";
When I run the mysql command directly it correctly returns rows with a number based on what user it is coming from. On the php page though I am not getting any number returned. What I want displayed by the php page is the total of all rows (they will definitely be numbers). Any help is greatly appreciated.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Mindisgone posted:

code:
$result6 = queryMysql("SELECT numbers FROM numbertable WHERE user='$user'");
	$num6 = mysql_num_rows($result6);
	
	for ($x = -1 ; $x < $num6 ; ++$x)
	{
		$v = mysql_fetch_row($result6);
	}
	echo array_sum($v[$num6]) . " total";
When I run the mysql command directly it correctly returns rows with a number based on what user it is coming from. On the php page though I am not getting any number returned. What I want displayed by the php page is the total of all rows (they will definitely be numbers). Any help is greatly appreciated.

Well, you seem to have three principal problems. Firstly, you are overwriting the variable $v on each pass through the loop, so each time you go through the loop you are discarding the information from the previous passes. From the call to array_sum() it seems like you are trying to build an array, so I suggest changing the code as follows: add $v = array(); before the loop, and change $v = ... to $v[] = ... inside the loop.

Secondly, why are you initialising $x to -1 instead of 0? This is causing you to go through the loop one extra time. (This overrides the data from the final row of the resultset in $v.)

Thirdly, you want to sum all of the values in $v, so you want array_sum($v), not array_sum($v[$num6]). $v[$num6] isn't even an array.

Aside from these three principal problems, you are using the mysql_ extension, which is obsolete. Read this.

And turn on error reporting for development. If you had error reporting turned on then PHP would tell you about your nonsensical array_sum() call itself.

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.
And, lets take a look at where $user came from. Aside from not using PDO, that's just screaming SQL injection.

Mister Chief
Jun 6, 2011

This might just be throwaway test code but you should be using self documenting variable names. Result6 and num6 are not descriptive in the slightest and would create confusion for anyone else reading your code or even for yourself if you come back to it at a later date.

Mindisgone
May 18, 2011

Yeah, well you know...
That's just like, your opinion man.

musclecoder posted:

And, lets take a look at where $user came from. Aside from not using PDO, that's just screaming SQL injection.

I am putting $user through a sanitizing function. Handling it as sensitive as possible.

Hammerite posted:

Lots of great information

First off I don't know what I was thinking with setting $x to -1, I should know better (and originally had it set to 0 before I lost my mind on this problem). The same really goes for $v[$num6]. So really my code should look like the following:
code:
$result6 = queryMysql("SELECT hours FROM cwerkskills WHERE user='$user'");
	$num6 = mysql_num_rows($result6);
	
	$v = array();
	
	for ($x = 0 ; $x < $num6 ; ++$x)
	{
		$v[] = mysql_fetch_row($result6);
	}
	echo array_sum($v) . " Hours used";
Right now the mysql command returns 3,3,3,0 per row respectively for this user. So 9 is obviously my desired output.

Also I never learned PDO apparently I should get on that. For now I would like to finish the project (which is close to completion) than make the necessary changes to make it PDO and not mysql extension.

EDIT:The above code returns 0 instead of 9, but I may be loving something up still.

Mindisgone fucked around with this message at 02:50 on Jun 19, 2012

Dad Jokes
May 25, 2011

I'm not exactly sure if this is PHP-specific or more of a web-development question, but I'm using PHP, so I figured that I'd post it here:

I posted a little while ago about the hipster-image generator I'm working on, and I've run into a little bit of an issue regarding passing data between the PHP file and the html file that will be hosting it.

Here's an excerpt of my imagecomposer.php showing how I'm currently trying to output the data URI of the generated image. However, both ways have issues, and I'm not sure of the best way to resolve it.

php:
<?
// output as image data URI
$blobData = $im->getImageBlob();
$type = $im->getImageFormat();

// for debugging (saving will not work here)
if(SHOW_DEBUG_FORMAT){
    header('Content-Type: text/html; charset=utf8');
    $encodedBlob64 = base64_encode($blobData);
    $srcData = "data:image/{$type};base64,{$encodedBlob64}";
    $output = array("image"=>$srcData);
    echo json_encode($output);
}
else{
    // for actual image output
    header("Content-type: image/{$type}");
    echo $blobData;
}
?>
As you can see in the SHOW_DEBUG_FORMAT clause, I'm directly reading the data URI for the image and sending it through JSON. In my html, I'm using jQuery's ajax function to call this php file, grabbing the uri string and setting it as the source of an <img> element. However, doing this causes problems with rightclicking and saving the image in Chrome (I'm not exactly sure why, but Googling suggests it may have something to do with the file size), and it doesn't even display in IE9. However, the advantage of doing this is that not only can I use JSON to output any extra info I might need later, currently, when I catch errors, I have the php file return the following in JSON format: array("error" => <error message here>) so that I can display a pretty error message in my html by using jQuery.

The other format that I've tried, which you can see in the else clause, is directly outputting the image and setting the MIME type of the php file as an image. By doing this, if I set "imagecomposer.php" as the src of an <img> element in my html, I can rightclick and save the image with no problem in all browsers. (I got this idea from seeing how http://infinitecomic.com/ handled displaying their generated images.) However, the issue comes from the fact that I have no way to send any extra information or pass along error message through JSON by doing this.

Currently, I'm considering writing a separate validator PHP file to check the MIME type of imagecomposer.php's result and sending along JSON based on that to the html indicating whether or not to display an error or set the <img> element's source to "imagecomposer.php". However, considering that I'm still a newbie to PHP, I was wondering if anyone could give me some advice and could point out whether I'm on the right track or going about this in the wrong way?


tl;dr version:
How can I send either image data or error JSON information from this php file (in a way I'd be able to detect in a jQuery Ajax call) in different formats depending on whether I got an error or not? Also, am I being retarded in my approach?

Doh004
Apr 22, 2007

Mmmmm Donuts...

Mindisgone posted:

I am putting $user through a sanitizing function. Handling it as sensitive as possible.


First off I don't know what I was thinking with setting $x to -1, I should know better (and originally had it set to 0 before I lost my mind on this problem). The same really goes for $v[$num6]. So really my code should look like the following:
code:
$result6 = queryMysql("SELECT hours FROM cwerkskills WHERE user='$user'");
	$num6 = mysql_num_rows($result6);
	
	$v = array();
	
	for ($x = 0 ; $x < $num6 ; ++$x)
	{
		$v[] = mysql_fetch_row($result6);
	}
	echo array_sum($v) . " Hours used";
Right now the mysql command returns 3,3,3,0 per row respectively for this user. So 9 is obviously my desired output.

Also I never learned PDO apparently I should get on that. For now I would like to finish the project (which is close to completion) than make the necessary changes to make it PDO and not mysql extension.

EDIT:The above code returns 0 instead of 9, but I may be loving something up still.

Sum up the hours in SQL:

PHP code:
$sql = 
"SELECT SUM(hours) as totalHours 
FROM cwerkskills 
WHERE user='$user'
GROUP BY user";

$query = mysql_query($sql);
$result = mysql_fetch_assoc($query);
echo $result['totalHours'].' hours used';
Keep in mind, you should be using PDO, checking to make sure you have results and blah blah blah, but seriously do your aggregation in SQL if you can. It'll make your life much easier.

Doh004 fucked around with this message at 15:46 on Jun 19, 2012

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
Are SSDs up to the task of running databases, specifically MySQL databases, now? How long will they last, isn't that going to be tons of writing?

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.

Golbez posted:

Are SSDs up to the task of running databases, specifically MySQL databases, now? How long will they last, isn't that going to be tons of writing?

Yes, they are. Some have 1 million hours of estimated life. They're not cheap, of course. There's even a YCombinator company (who's name escapes me) building a MySQL engine specifically for SSD's.

Adbot
ADBOT LOVES YOU

butt dickus
Jul 7, 2007

top ten juiced up coaches
and the top ten juiced up players

Golbez posted:

Are SSDs up to the task of running databases, specifically MySQL databases, now? How long will they last, isn't that going to be tons of writing?
Modern SSDs have enough write cycles to where you could write at full speed 24/7 to the drive for decades and they will be fine. We switched to SSDs for our databases and it's made quite a difference in terms of speed.

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