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
duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Wrote yourself a fancy image uploading script and want us to point out the problems? Can't figure out how to get rid of the mysterious slashes in the data from your form? Don't know why the slashes should probably be there? Need help writing OOP in PHP5? This thread will be for all that and any other PHP related issue. It does not have to be web related to be asked in here.
The official site has extremely useful documentation.



itskage has written up a handy guide to getting a useful dev environment setup on windows. If you're a *nix user, you should know which steps to skip.

itskage posted:

This has become less of a "copy the guide from these mark down files" and more of a "Retype the jist of stuff into a forums post". Sorry but there's more company specific stuff in them than I remembered, and it was quite long and I was fighting with the lack of md formatting, so I cut it down a lot, and now it is like a text dump, but hopefully it's useful to someone.

To be clear this is for windows.

Install NGINX
  1. Download the NGINX/Windows binaries http://nginx.org/en/download.html
  2. Make a folder for nginx and unzip there E.g.: C:\nginx\
  3. Run nginx.exe to start. You can verify installation by going to http://localhost/ and you should get the nginx welcome page.

Some notes:
If you have something else listening on 80 (XAMPP IIS Express) then you need to stop it or configure NGINX to listen on another port.
To stop NGINX after running it this way you have to taskkill it.

Install PHP
  1. Download the PHP binaries for windows. http://php.net/downloads.php
  2. Extract them to a folder. E.g.: C:\php\
  3. Start PHP and listen on 9000 `c:\PHP\php-cgi.exe -b 127.0.0.1:9000

Test PHP
In nginx's folder /conf/nginx.conf un-comment the php location, and alter the SCRIPT_FILENAME per below.
code:
     # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

     location ~ \.php$ {
       root           html;
       fastcgi_pass   127.0.0.1:9000;
       fastcgi_index  index.php;
       fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
       include        fastcgi_params;
     }
- This is telling NGINX that any requests ending in .php should be forwarded to PHP and for PHP to execute the file at $document_root + relative path to the file.
- Add a test phpfile to the nginx root E.g.: nginx/html/phpinfo.php with
code:
<?php phpinfo();
- Restart the nginx process to load the changes.
- Now you should see php info when you navigate to http://localhost/phpinfo.php

Tweaking configs
Now I have a bunch of poo poo about tweaking nginx.conf, sites-available/yourside.conf and php.ini for our CMS and whatnot, that I won't touch here. NGINX is like apache with sites-availabe and sites-enabled and with that above snippet getting phpinfo working you should be able to figure it out, otherwise just ask.

Some stuff I will mention:
- Setup your SSL and hostnames if you are developing with https (which I don't know why you wouldn't in tyool 2018)
- Change your the root for your site in NGINX unless you plan to workout of C:\nginx\html or wherever you installed it.
- in php.ini be sure to uncomment any extensions you need (and ensure you have the .dlls for them in php\ext\) so like if you need curl just uncomment extension=php_curl.dll in the ini.
- Xdebug will be needed to debug in VSCode (does any IDE not need this?): dump your phpinfo() output into https://xdebug.org/wizard.php and it should result in you downloading a dll that you put in php\ext\ and then referencing in php.ini (zend_extension = php_xdebug-2.5.4-7.0-vc14-x86_64.dll)
- Confgure Xdebug in PHP ini. You can google a bunch of the options but minimum I do this for local development:

xDebug v3
code:
; Start in debug mode
xdebug.mode=debug
; Specify host if not using autodetect 
xdebug.client_host=127.0.0.1
xdebug.client_port=9003 
; Set to yes to always start instead of when triggered
;xdebug.start_with_request=yes 
; I don't know if this is actually needed
xdebug.idekey = VSCODE 
xDebug v2
code:
[debug]
; Always xdebug
xdebug.remote_autostart=1 
; Enable...
xdebug.remote_enable=1
; Debug at the start of every request
xdebug.remote_mode=req
; What host to send debugging info to (your local)
xdebug.remote_host=127.0.0.1
; Port to connect to VSCode on... be sure this is not your PHP port!
xdebug.remote_port=9003
; Auto start can be disabled and this can be enabled if you want to use a browser extension to enable/disable debugging, (from any machine even) but since it's local I don't see the point.
xdebug.remote_connect_back=0
Working files
Next I have directions about git cloning our projects down. It should be the same. Clone yours to where you set your NGINX site's root, (I'll just use C:\nginx\html\ for this). Once done or if starting from scratch you can open a workspace in vscode there. (ctrl+k ctrl+o). VSCode also has bulit in terminal (ctrl+`) so you can just run git commands there, or use the built in commands (F1 to open the command pallet, type git clone, follow prompts).

At this point if you have your site in the folder and all of your site's configs and any database connections or anything configured then your site should run under localhost (or if you need a hostname to serve multiple sites from one CMS like I do you can overwrite your hosts file).

Last thing is unless you want to run NGINX and PHP locally as a service (I don't) you will want something to start and stop them, so here's a bat file that kills any running nginx and php processes and then restarts them (and leaves the window open).
code:
@ECHO OFF

taskkill /f /IM nginx.exe
cd c:\nginx
start nginx

taskkill /f /IM php-cgi.exe
cd c:\php

Echo running php...
c:\php\php-cgi.exe -b 127.0.0.1:9000
You can add a task in vscode if you'd rather run that from the IDE.

Anyway that's the most rudimentary way to run NGINX and PHP locally on windows.


VS Code part:
Basic PHP support:
You still need PHP downloaded even if not running it locally because you will need to point your extensions at the .exe.
Microsoft will recommend you the: https://marketplace.visualstudio.com/items?itemName=felixfbecker.php-pack which includes the debugger and IntelliSense, but I wasn't big on the intelliSense. Fortunatley you can get them seperately, so for me I just grab the debugger. https://marketplace.visualstudio.com/items?itemName=felixfbecker.php-debug
Then instead I use Intelephense: https://marketplace.visualstudio.com/items?itemName=bmewburn.vscode-intelephense-client
Now you have to add some user/workspace settings (ctrl+,). I recommend putting these php specific things into workspace so they aren't trying to phpmd my node.js projects or dotnet core.
code:
    "php.suggest.basic": true, (disabling this will stop the double suggestions from the native VSCode's and the intelephens/IntelliSense)
    "php.validate.enable": true,
    "php.validate.run": "onSave", (I haven't tryied onType, but I'm constantly hitting ctrl+s from years of doing this so...)
    "php.validate.executablePath": "C:\\php\\php.exe", (or wherever you installed)
VS Code is pretty good and will autocomplete options and what not if you want to play with the settings.

Debugging:
This should work now, so open the debugging pane (ctrl+shift+d) then up at the top you have some profiles. Click the gear to get started and edit some:
Here's the most basic:
code:
 
     {
            "name": "Local",
            "type": "php",
            "request": "launch",
            "port": 9003,
            "pathMappings": {
                "C:/nginx/html/" : "${workspaceRoot}"
            }
        },
Listens on port 9003 for xdebug. Just set a break point in your index.php or wherever is easy to test, hit F5 to start debugging the current profile, and then open that page in a browser and it should halt on your breakpoint.

I keep four profiles: local, remote (to debug a test server), tests (to halt on exceptions when running a bunch of tests), and current file (which I think is built in and is quite useless to me since we use a CMS with a dispatcher).

Composer:
https://getcomposer.org/download/ (recommend just using the EXE)
There is a VS Code extension. You don't need it, but it adds composer commands to the command pallet, and will validate your composer.json so I recommend it: https://marketplace.visualstudio.com/items?itemName=ikappas.composer
Back to workspace settings (crtl+,):
code:
    "composer.enabled": true,
    "composer.executablePath": "C:\\ProgramData\\ComposerSetup\\bin\\composer.bat",
If you have a composer.json in your project. You should be able to run composer install now (ctrl+` composer install to do it from the command line, or F1 composer install to do it from the command pallet). If not you will need to make one (and the necessary git/vcs exclusions).

Anyway add and run composer install/update and it should install PHPMD, PHPCS, and PHPUnit with a Code coverage plugin.
code:
    "require-dev": {
        "phpmd/phpmd" : "@stable",
        "squizlabs/php_codesniffer": "3.*",
        "phpunit/phpunit": "@stable",
        "phpunit/php-code-coverage": "@stable"
    },
You can generate xml for PHPMD and PHPCS rules easily here with this:
http://edorian.github.io/php-coding-standard-generator/#phpcs
You can even paste your XML back in later if you need to make adjustments

PHPCS: https://marketplace.visualstudio.com/items?itemName=ikappas.phpcs
This is the less finicky of the two linters.
Workspace settings:
Where to find the rules to enforce, and where the cs script is. You're SUPPOSED to be able to go to vendor/bin/phpcs for this instead of the full path but that never worked for some reason.
code:
    "phpcs.standard": ".\\phpcs.xml",
    "phpcs.executablePath": "vendor/squizlabs/php_codesniffer/bin/phpcs",
PHPMD: https://marketplace.visualstudio.com/items?itemName=ecodes.vscode-phpmd
There's a couple of these. As of about August of last year that one was the best one, but PHPMD still tends to jam up sometimes on large projects/files espcially when the debugger is running.
If you notice this, just restart the debugger. You can also see at the bottom stuff like "PHP is linting document..." with a spinner and it hangs. Usually restart the debugger fixes that too.
What I think is the process to lint is getting locked behind an actual request you want to debug for some reason, and even though you finish in the GUI, VSCode debugger isn't communicating that back, and it just gets stuck. If someone knows better, by all means, please share.
code:
    "phpmd.verbose": true,
    "phpmd.rules": ".\\phpmd.xml",
If you don't use verbose then it doesn't tell you what rule the line is violating.

Once you get those setup you can see what horrors are lurking in the code base you've inherited:
The function getConfigJSONResponse() has an NPath complexity of 1773066240. The configured NPath complexity threshold is 200.
The function getConfigJSONResponse() has a Cyclomatic Complexity of 74. The configured cyclomatic complexity threshold is 10.
:allears:

PHP Unit: https://marketplace.visualstudio.com/items?itemName=emallin.phpunit
Only needed if you want to run tests in VSCode while developing.
code:
    "phpunit.execPath": ".\\vendor\\bin\\phpunit.bat",
    "phpunit.args": [
        "--configuration", ".\\Tests\\phpunit.xml",
        "--coverage-text=.\\Tests\build\\coverage.txt"
    ],
    "phpunit.preferRunClassTestOverQuickPickWindow": false, // Default false
Not going to cover the phpunit.xml and setup of tests unless someone needs it.

To run tests in VS Code hit F1 and type PHPUnit Test with nothing open or selected will run all tests in the listed configuration.
With a test file/case open and selected hit F1 and type PHPUnit Test to run all tests for that file.
To run a specific test, double clock the function to highlight it, then do the F1 type PHPUnit Test (this autocompletes after the first time) and then it will just run that single test.


Webpack:
Be sure you've installed node and npm. I'm assuming you know what this is and how it works outside of VSCode. If not, ask but don't just add it because it's here.
Then open a terminal and npm install webpack, or I recommend using a package.json for your project:
code:
{
    "name": "",
    "version": "",
    "description": "",
    "dependencies": {
        "webpack": "3.10.0"
    }
}
Then just npm install.

Now you just make a webpack.config like any other webpack project, and the cool thing is you can just make some tasks to run this for you:
Under Tasks -> Configure Tasks...
You can add these:
code:
        {
            "label": "webpak build",
            "type": "shell",
            "command": "${workspaceRoot}/node_modules/.bin/webpack",
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "args": [
                "--colors",
                "--progress"
            ]
        },
        {
            "label": "webpak watch",
            "type": "shell",
            "command": "${workspaceRoot}/node_modules/.bin/webpack",
            "args": [
                "--colors",
                "--progress",
                "--watch"
            ]
        }
First one just runs a build. But you can have that set as default so it auto builds whenever you run a build task which you can even have it do when you start the debugger.
2nd one adds --watch so it will auto update with any changes you make.

Probably would be better breaking it down into multiple posts (it's 3 different guides in our private github) but there you go.

Summary
Anyway it's a bit janky for PHP, but it works fine when you know the quirks. I think NGINX+php-fpm is better than apache-php and VS Code is the best IDE in general. So if this helps some people try it out then great.

If you're like me and jump between dotnet core and node as well as PHP (and frontend js) then it's nice just being in one IDE. It's not perfect (sometimes even for dotnet core I have to open VS2017), but I like it.

Finally one last thing is you can now write the js for your PHP site in here with ts which has fantastic vs code support.

duz fucked around with this message at 15:09 on Jan 18, 2021

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
Excellent call on the thread.

PHP Frameworks:
what lots of us use is: CodeIgniter
A PHP5 only alternative: Kohana

Link to the CodeIgniter Thread

csammis
Aug 26, 2003

Mental Institution
Added to the stickied list

Imminent
Jul 27, 2004
Might want to mention these two frameworks:

Zend Framework
symphony

Couple of php ORM's

Propel (1.3 is soon to be released which is a lot better than 1.2)
php doctrine

Ned
May 23, 2002

by Hand Knit
We should probably put the major CMSs in here as well.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
YES! A php megathread. I was tempted to ask why there wasn't one the other day.

Can you combine a function call that returns an array with the array index you want like:

$something = $this->arrayReturningMethod()[0];

I tried it and it didn't work. Am I doing it wrong or can you not do this in PHP? Are there languages where this does work?

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


fletcher posted:

Can you combine a function call that returns an array with the array index you want like:
$something = $this->arrayReturningMethod()[0];
I tried it and it didn't work. Am I doing it wrong or can you not do this in PHP? Are there languages where this does work?

Naw, can't do that in PHP. Javascript can do what you want, don't know off hand what else could.

hey mom its 420
May 12, 2007

You also can't do
php:
<?
$bla = new Something()->method();
?>
and I don't know why the hell PHP doesn't allow that.

duck monster
Dec 15, 2004

Bonus posted:

You also can't do
php:
<?
$bla = new Something()->method();
?>
and I don't know why the hell PHP doesn't allow that.

If your just after the output of the method, couldnt you just do something like

$bla = Something::method()

or are you after an initialised object?

Ie $address = new Customer('Dr Philodimo')->address()

PHP *does* have a few holes in that regard.

edit: Also x = thingo()[0] is a fairly common python idiom, as is the above, opening up awesomeness like
tag = xml('file.xml').parse().findtags('customers')[3].tag('name')

Maybe php6 will support it? One can only hope.


edit2: Add to the php orm's , ADODB 's Active Record.

duck monster fucked around with this message at 00:13 on Mar 20, 2008

gibbed
Apr 10, 2006

Imminent posted:

Might want to mention these two frameworks:
I've recently been trying Agavi,

There's also these, which I have tried...
Don't like any of those? Find more here.

There Will Be Penalty
May 18, 2002

Makes a great pet!

duz posted:

Naw, can't do that in PHP. Javascript can do what you want, don't know off hand what else could.

Perl does this.

code:
sub foo {
        return ("zero", "one", "two", "three", "four");
}
print((foo())[2]);
print("\n");
If your function returns a list reference:

code:
sub bar {
        return ["cero", "uno", "dos", "tres", "cuatro"];
}
print(bar()->[2]);
print("\n");
I can't speak for Python or Ruby.

hey mom its 420
May 12, 2007

duck monster posted:

or are you after an initialised object?

Ie $address = new Customer('Dr Philodimo')->address()
Yeah, that's what I was thinking of. It makes no sense that you can't do it because it's not like you can juggle classes in PHP like you can with Python so that there would be ambiguity as to what the new keyword refers to. It always refers to the thing closest to it, so I really don't see a reason why you can't do stuff like that.

Standish
May 21, 2001

Bonus posted:

You also can't do
php:
<?
$bla = new Something()->method();
?>
and I don't know why the hell PHP doesn't allow that.

You also can't do
php:
<?
empty(someFunctionThatReturnsAString())?>
which bit me earlier today.

Scarboy
Jan 31, 2001

Good Luck!

Standish posted:

You also can't do
php:
<?
empty(someFunctionThatReturnsAString())?>
which bit me earlier today.

I hate this so much, it's stupid having to use empty() sometimes and strlen(whatever()) == 0 other times. I understand why you can't chain calls together in PHP since it sucks at OOP, but it terrible that you can't do basic things like [index] on a function that returns an array.

oRenj9
Aug 3, 2004

Who loves oRenj soda?!?
College Slice
Don\\'t should be Don\\\'t ;).

Jayzer
Dec 16, 2003

fletcher posted:

$something = $this->arrayReturningMethod()[0];

I tried it and it didn't work. Am I doing it wrong or can you not do this in PHP? Are there languages where this does work?

Python can do this as well.

gi-
Aug 18, 2004
So I just upgraded my hosting environment. Went from PHP4 to PHP5 and getting this error 'Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource'

for this piece of code:



$rs = mysql_query($query);
if (mysql_num_rows($rs)>0)
{
if($rsdata = mysql_fetch_object($rs))
{
if($rsdata->catalog_number == "")
$catalogid = "---";
else
$catalogid = "$rsdata->catalog_number";

$catarr = explode(",",$rsdata->category);
$imgarr = explode(",",$rsdata->picture);

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

gi- posted:

So I just upgraded my hosting environment. Went from PHP4 to PHP5 and getting this error 'Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource'

for this piece of code:


Is the mysql_query failing? Add this after it.

php:
<?
if (!$rs) {
    die('Invalid query: ' . mysql_error());
}
?>

Xenos
Jun 17, 2005

I've been writing PHP for my job for over a year now, and we don't use a framework. I'm going to recommend two tools that make using PHP less messy.

The first is Smarty, a templating language for PHP. It's overkill for small projects, but if you're working on something bigger than one page, it can really help you avoid poo poo like "echo '<html><head>...'". If you've ever hated mixing a ton of PHP code in with gigantic blocks of HTML, you'll probably want to try Smarty.

The second tool is MDB2. It's a database abstraction layer, and it has a ton of drivers, including PostgreSQL, Oracle, MSSQL, and MySQL. If you use its built in prepare and execute methods, it will escape data for you, which is very handy. Another positive feature is that it will help you avoid the multitude of mysql_real_add_slashes_im_serious_this_time_i_mean_it methods. I'm also a fan of its placeholder functions, which some databases don't support natively.

Also, if you can, turn off magic quotes. It still comes turned on by default and the only thing that's magic about it is how much it pisses people off.

Scarboy
Jan 31, 2001

Good Luck!

Xenos posted:

I've been writing PHP for my job for over a year now, and we don't use a framework. I'm going to recommend two tools that make using PHP less messy.

The first is Smarty, a templating language for PHP. It's overkill for small projects, but if you're working on something bigger than one page, it can really help you avoid poo poo like "echo '<html><head>...'". If you've ever hated mixing a ton of PHP code in with gigantic blocks of HTML, you'll probably want to try Smarty.

The second tool is MDB2. It's a database abstraction layer, and it has a ton of drivers, including PostgreSQL, Oracle, MSSQL, and MySQL. If you use its built in prepare and execute methods, it will escape data for you, which is very handy. Another positive feature is that it will help you avoid the multitude of mysql_real_add_slashes_im_serious_this_time_i_mean_it methods. I'm also a fan of its placeholder functions, which some databases don't support natively.

Also, if you can, turn off magic quotes. It still comes turned on by default and the only thing that's magic about it is how much it pisses people off.

Isn't PHP a good enough templating language that you shouldn't have to use another one? What's wrong with:

<?

//domain/controller logic

//template

?>

You can just declare all the variables you're going to use in your template(s) in the logic section and just present in the template.

I also agree that MDB2 is super useful, I love that thing.

Xenos
Jun 17, 2005

Scarboy posted:

Isn't PHP a good enough templating language that you shouldn't have to use another one? What's wrong with:

<?

//domain/controller logic

//template

?>

You can just declare all the variables you're going to use in your template(s) in the logic section and just present in the template.

I also agree that MDB2 is super useful, I love that thing.

It does a little more than that, it has built in validation, pagination, it auto-generates drop-down menus, radio groups, checkbox groups as well as templating. I know it seems kinda goofy to have a templating language inside of a templating language at first, but I really like it.

Scarboy
Jan 31, 2001

Good Luck!

Xenos posted:

It does a little more than that, it has built in validation, pagination, it auto-generates drop-down menus, radio groups, checkbox groups as well as templating. I know it seems kinda goofy to have a templating language inside of a templating language at first, but I really like it.

Ah, ok, that seems useful then. Coming from Rails, at my last job I wrote a lot of functions similar to the ones in Rails to works with form elements. Generating select boxes without having an array of options and an array of selected items is a nightmare.

SmirkingJack
Nov 27, 2002
Here is a tip that I just had occasion to learn. If you are uploading relatively large files you not only have to make sure that in php.ini not only is upload_max_filesize set high enough but also post_max_size. I could not figure out for the life of me why there was no $_POST variable when I clicked submit until I learned of post_max_size's existence.

Standish
May 21, 2001

"Unexpected T_PAAMAYIM_NEKUDOTAYIM" is my favourite PHP wtf, what do you mean not everybody speaks Hebrew?

functional
Feb 12, 2008

SmirkingJack posted:

Here is a tip that I just had occasion to learn. If you are uploading relatively large files you not only have to make sure that in php.ini not only is upload_max_filesize set high enough but also post_max_size. I could not figure out for the life of me why there was no $_POST variable when I clicked submit until I learned of post_max_size's existence.

Thanks for this. I knew about upload_max_filesize but never heard of this. It would've had me frustrated for days.

Super 3
Dec 31, 2007

Sometimes the powers you get are shit.

functional posted:

Thanks for this. I knew about upload_max_filesize but never heard of this. It would've had me frustrated for days.

php_value max_execution_time X

Is also another good one to throw in there. Those three are my standard .htaccess file upload fix.


I was wondering if anyone could point me to a php progress bar script of some kind. I need it to be able to display sales for about 12 different entities on one page. I've been digging around quite a few sites to no avail. Im about to install Joomla to use an extension they offer, as well as Sugar CRM but both seem to be a bit of an overkill at this point for what I want.

minato
Jun 7, 2004

cutty cain't hang, say 7-up.
Taco Defender

Super 3 posted:

php_value max_execution_time X

Is also another good one to throw in there. Those three are my standard .htaccess file upload fix.
I don't put these into .htaccess because .htaccess isn't parsed if you're running a CLI script. I always either set them explicitly in my bootstrap, or in php.ini if that particular var doesn't allow it.

Super 3 posted:

I was wondering if anyone could point me to a php progress bar script of some kind. I need it to be able to display sales for about 12 different entities on one page. I've been digging around quite a few sites to no avail.
I'm not sure whether you're after a progress bar or some charting tools. Which is it?

Jabab
Feb 25, 2006

Standish posted:

"Unexpected T_PAAMAYIM_NEKUDOTAYIM" is my favourite PHP wtf, what do you mean not everybody speaks Hebrew?

That one made me shout WTF out loud

Super 3
Dec 31, 2007

Sometimes the powers you get are shit.

minato posted:

I don't put these into .htaccess because .htaccess isn't parsed if you're running a CLI script. I always either set them explicitly in my bootstrap, or in php.ini if that particular var doesn't allow it.

I'm not sure whether you're after a progress bar or some charting tools. Which is it?

Dont have access to the php.ini over here.


More like a charting tool.

Essentially it's 12 stores that all have a sales goal, that I want to show via a progress bar/graph/visual thing.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Super 3 posted:

Dont have access to the php.ini over here.


More like a charting tool.

Essentially it's 12 stores that all have a sales goal, that I want to show via a progress bar/graph/visual thing.

http://code.google.com/apis/chart/

I used this for a project recently and absolutely loved it. Let me know if you have any questions about it.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Super 3 posted:

Dont have access to the php.ini over here.


More like a charting tool.

Essentially it's 12 stores that all have a sales goal, that I want to show via a progress bar/graph/visual thing.

code:
<div style="width:100px;border solid 1px #666;">
<?php
foreach($salesThing as $thing){
 echo '<div style="height:10px;width:'. $salesThing->percentTowardsGoal . 'px;background-color:#0f0;">&nbsp;</div>';
}
?>
</div>
Just make DIVs and width them based on the data. You can even use a fancy pants CSS background image for striping and whatnot.

beerinator
Feb 21, 2003

fletcher posted:

http://code.google.com/apis/chart/

I used this for a project recently and absolutely loved it. Let me know if you have any questions about it.

Normally I wouldn't recommend anything flash based in a php thread, but these graphs are waaay too sweet to pass over if someone is doing something in php that will need charts.

http://www.maani.us/charts/index.php?menu=Gallery

Super easy to configure (as easy or easier than google charts), they're free to use, but they cost 45 bucks to remove the "click on graph go to php/swf charts site". Well worth the money and the effort to get them set up if you are working on a professional project.

When I got them working on one of my projects, my bosses eyes lit up.

other people
Jun 27, 2004
Associate Christ
I want to parse an html file. For example, say I want to know what is contained inside an <h1> tag. I can do this with strstr and substr but it is ugly.

Roloc
Apr 6, 2005
We may want to throw in some IDE's too, I dunno.

PDT - http://www.eclipse.org/pdt/ - This is what I use
Aptana - http://www.aptana.com/php - I haven't used this but it looks slick.
Zend Studio - http://www.zend.com/en/products/studio/ - They have an eclipse plugin now too I think

Edit: ohh yeah and about the DIVs and the widths... screw static graphics use GD and draw them :) http://us3.php.net/gd

Roloc fucked around with this message at 08:59 on Mar 22, 2008

nbv4
Aug 21, 2002

by Duchess Gummybuns

Lumpy posted:

code:
<div style="width:100px;border solid 1px #666;">
<?php
foreach($salesThing as $thing){
 echo '<div style="height:10px;width:'. $salesThing->percentTowardsGoal . 'px;background-color:#0f0;">&nbsp;</div>';
}
?>
</div>
Just make DIVs and width them based on the data. You can even use a fancy pants CSS background image for striping and whatnot.

Since we're on the topic, I really wish there was a method built into HTML/CSS that sets the widths and things automatically based on a "scale" value. For instance:

code:
while($rows = mysql_fetch_array($result))
{
    $return .= "<tr>
                    <td style=\"text-align:right;width:10em\">{$rows['title']}</td>
                    <td style=\"width:{$row['value']};background-color: pink\">{$row['value']}</td>
               </tr>\n\n";
}
...wound automatically scale each cell in the second row. As it is now, I'll have to go through each row in the SQL result, find the highest value, then on the second time around, divide each value by the largest value to get percentage.

nbv4 fucked around with this message at 09:14 on Mar 22, 2008

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

nbv4 posted:



...wound automatically scale each cell in the second row. As it is now, I'll have to go through each row in the SQL result, find the highest value, then on the second time around, divide each value by the largest value to get percentage.

Or you could add ' MAX(myValue) as theBiggest ' to your query and have it available in each row already....

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Kaluza-Klein posted:

I want to parse an html file. For example, say I want to know what is contained inside an <h1> tag. I can do this with strstr and substr but it is ugly.

If you are using PHP5, and your HTML is valid XML (which it might (probably?) not be) you can do it easily like so:

php:
<?
$xml = simplexml_load_file('myHTML.html');
echo $xml->h1;
?>
(Assuming there is only one H1 tag, otherwise $xml->h1 would return an array that you can loop over or just do $xml->h1[0] for the first, etc.)

Otherwise check out the DOM and XML methods in the manual, they are pretty self explanatory.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Kaluza-Klein posted:

I want to parse an html file. For example, say I want to know what is contained inside an <h1> tag. I can do this with strstr and substr but it is ugly.

You can use a combination of HTMLTidy to clean up the HTML and SimpleXML to search the document.

php:
<?
$config = array(
 'indent'         => true,
 'output-xhtml'   => true,
 'wrap'           => 200);
$tidy = new tidy;
$url = 'http://www.example.com/index.html';
$tidy->parseFile($url, $config);
$tidy->cleanRepair();
$doc = new DOMDocument();
$doc->loadHTML($tidy);
$html = simplexml_import_dom($doc);
$h1 = $html->xpath('//h1[@id="main"]');
?>

admiraldennis
Jul 22, 2003

I am the stone that builder refused
I am the visual
The inspiration
That made lady sing the blues

duz posted:

You can use a combination of HTMLTidy to clean up the HTML and SimpleXML to search the document.

php:
<?
$config = array(
 'indent'         => true,
 'output-xhtml'   => true,
 'wrap'           => 200);
$tidy = new tidy;
$url = 'http://www.example.com/index.html';
$tidy->parseFile($url, $config);
$tidy->cleanRepair();
$doc = new DOMDocument();
$doc->loadHTML($tidy);
$html = simplexml_import_dom($doc);
$h1 = $html->xpath('//h1[@id="main"]');
?>

That's useful if you are parsing an entire html document or a whole bunch of different tags, but if it was a one-time thing I'd probably just use
php:
<?
preg_match("/<h1>(.*?)<\/h1>/s",$string,$h1);
$contents = $h1[1];?>
or something for simplicity

Adbot
ADBOT LOVES YOU

Daddy Fantastic
Jun 22, 2002

For the glory of FYAD
Are there any benefits to using MDB2, assuming I'm already using mysqli prepared statements, won't be switching away from mySQL, and I'm not already using PEAR?

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