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
SimonNotGarfunkel
Jan 28, 2011
Massive thanks to those of you who recommend Laravel earlier in this thread.

I'm using the L4 beta and it's s real breath of fresh air, especially the Eloquent stuff. I love the way it handles pivot tables and the polymorphic relations stuff.

The documentation could be vastly improved in my opinion, but the community seems more than willing to help.

Adbot
ADBOT LOVES YOU

Sulla Faex
May 14, 2010

No man ever did me so much good, or enemy so much harm, but I repaid him with ENDLESS SHITPOSTING

McGlockenshire posted:

SQL assembly like that is perfectly fine as long as you have validated that the table name is indeed a valid table name. You can do this either by hard-coding the table list in your code, or looking at information_schema.tables or whatever your DB uses if it doesn't use information_schema.

Also assuming PDO here, you can't reuse the same placeholder name multiple times in a query. Just punt and use ?s instead as you're going to end up repeating the variable anyway.

The table names will definitely be hard-coded. I'll most likely be doing a switch($input), where the tables get filled (from a hardcoded list) based on a preg_match of the input word.

It's definitely PDO, sorry -- I was super tired and had to completely re-write the entire post because the first one was dumb.

When you say placeholder's can't be reused, does that mean I can only use :term once in a query? That sucks a little. If I have to insert that as a PHP variable, I'll have to fully sanitize it before hand. I wouldn't have expected that to be the case.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Sulla-Marius 88 posted:

When you say placeholder's can't be reused, does that mean I can only use :term once in a query? That sucks a little. If I have to insert that as a PHP variable, I'll have to fully sanitize it before hand. I wouldn't have expected that to be the case.

Yeah, it's kind of stupid. But no, don't just insert it as a variable, use positional placeholders instead.

php:
<?
$query = 'SELECT foo FROM bar WHERE baz = ? UNION ALL SELECT foo FROM butts WHERE baz = ?';
$sth = $dbh->prepare($query);
$sth->execute(array( $baz, $baz ));
?>
Unfortunately you can't mix and match positional and named. Also, whoever decided to make the php code tag short tags by default needs to be roughed up a little.

hypernova
Apr 12, 2005
This is so loving frustrating. I just want to get a bunch of urls generated from an array that's updated often to be processed by PHP. That's it. gently caress.

Right now the URLs are in JSON format like the following:

code:
{ id : "id", url : "url" }
There are 63 of the above (object, object) objects in my JSON array. Yet, for reasons unbeknownst to me, my loving AJAX POSTS are JUST. NOT. SHOWING. UP. IN. PHP. gently caress YOU PHP.

code:
divisionsJSON = JSON.stringify(divisions);

$.ajax({
   type: "POST",
   url: "test3.php",
   data: divisionsJSON,
   contentType: "application/json",
   success: function (data, textStatus, xhr) {
		alert("Timer request result: " + textStatus);
	}
 });
- My array is named divisions.
- I stringified the array.
- Firebug / NET panel tells me the POST is received, I get the success function to fire, the POST body contains all of my data, Firebug even says the data is JSON! [The POST is only received when I have <script type="text/javascript" src="application.js"></script> (i.e., the javascript file containing the AJAX POST above) in the PHP file - is this working as intended?]

YET, when I ask PHP to do the most basic of tasks:

code:
<?php 
	print_r($_POST);
?>
It tells me to go gently caress myself with an empty array (i.e., Array ()). WTF?

So I post on StackOverflow. Oh, just add $json_decode! Oh wait, you don't actually need to stringify the JSON before you AJAX it! (>setting data to just divisions breaks the POST). Try var_dump, nothing, try echo $_POST[1]['id'], nothing.

I have spent so many hours researching what I'm being told on SO, related questions to my questions on SO, searching Google, but the combination of not formally learning PHP + not having anybody to really ask questions like this is completely killing me at the moment. I keep getting basic answers, but NO results.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

hypernova posted:

So I post on StackOverflow. Oh, just add $json_decode! Oh wait, you don't actually need to stringify the JSON before you AJAX it! (>setting data to just divisions breaks the POST).

What do you mean, breaks the POST? What is the error message?

hypernova posted:

[The POST is only received when I have <script type="text/javascript" src="application.js"></script> (i.e., the javascript file containing the AJAX POST above) in the PHP file - is this working as intended?]

Not sure what you mean here, can you elaborate?

Have you tried looking at the raw post data?

hypernova
Apr 12, 2005

fletcher posted:

What do you mean, breaks the POST? What is the error message?


Not sure what you mean here, can you elaborate?


Have you tried looking at the raw post data?

1) If the only thing I change in the ajax is divisionsJSON -> divisions (which is the name of the array that is stringified to divisionsJSON), my POST body in Firebug changes all to undefined=undefined & undefined=undefined etc etc.

I tried doing $data = file_get_contents('php://input'); print_r($data); and that returned a blank page. Honestly it feels like something hidden is going on here. I use ASmallOrange shared hosting, would there be any kind of server settings that I would need to change before I can accept POSTs via PHP or something?

Nebulon Gate
Feb 23, 2013

hypernova posted:

1) If the only thing I change in the ajax is divisionsJSON -> divisions (which is the name of the array that is stringified to divisionsJSON), my POST body in Firebug changes all to undefined=undefined & undefined=undefined etc etc.

I tried doing $data = file_get_contents('php://input'); print_r($data); and that returned a blank page. Honestly it feels like something hidden is going on here. I use ASmallOrange shared hosting, would there be any kind of server settings that I would need to change before I can accept POSTs via PHP or something?


Pretty sure it's you sending the contentType that's loving with it. Drop it, or maybe try specifying the charset.

hypernova
Apr 12, 2005

Cartesian_Duelist posted:

Pretty sure it's you sending the contentType that's loving with it. Drop it, or maybe try specifying the charset.

With data set back to divisions and the contentType dropped, I still get a POST full of undefined.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

hypernova posted:

With data set back to divisions and the contentType dropped, I still get a POST full of undefined.

Try using something else to generate the POST to your test3.php script, like curl or resty.

Also, are there any rewrite rules in an .htaccess file at play here?

I still don't understand what you mean by this:

quote:

[The POST is only received when I have <script type="text/javascript" src="application.js"></script> (i.e., the javascript file containing the AJAX POST above) in the PHP file - is this working as intended?]

fletcher fucked around with this message at 08:30 on Feb 27, 2013

Sulla Faex
May 14, 2010

No man ever did me so much good, or enemy so much harm, but I repaid him with ENDLESS SHITPOSTING

McGlockenshire posted:

Yeah, it's kind of stupid. But no, don't just insert it as a variable, use positional placeholders instead.

php:
<?
$query = 'SELECT foo FROM bar WHERE baz = ? UNION ALL SELECT foo FROM butts WHERE baz = ?';
$sth = $dbh->prepare($query);
$sth->execute(array( $baz, $baz ));
?>
Unfortunately you can't mix and match positional and named. Also, whoever decided to make the php code tag short tags by default needs to be roughed up a little.

Ah jeez, I see. So I gotta pass it some dumb lookin' arrays so that the unions can function:

array("table1", "buttz", "table2", "buttz", "table3", "buttz", "table4", "buttz");

And just insert into the array as many pairs of "tablex" and "buttz" as there are SELECT statements.

So it'll wind up looking like:

php:
<?
$query = 'SELECT foo FROM ? WHERE baz = ? UNION ALL SELECT foo FROM ? WHERE baz = ?';
$sth = $dbh->prepare($query);
$sth->execute(array( $table1, $baz, $table2, $baz ));
?>
God that's messy! I might spend an extra ten minutes and see if I can't encapsulate that into a frustratingly-specific function.

Thanks for your help.

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

Sulla-Marius 88 posted:

Ah jeez, I see. So I gotta pass it some dumb lookin' arrays so that the unions can function:

array("table1", "buttz", "table2", "buttz", "table3", "buttz", "table4", "buttz");

And just insert into the array as many pairs of "tablex" and "buttz" as there are SELECT statements.

So it'll wind up looking like:

php:
<?
$query = 'SELECT foo FROM ? WHERE baz = ? UNION ALL SELECT foo FROM ? WHERE baz = ?';
$sth = $dbh->prepare($query);
$sth->execute(array( $table1, $baz, $table2, $baz ));
?>
God that's messy! I might spend an extra ten minutes and see if I can't encapsulate that into a frustratingly-specific function.

Thanks for your help.

Nope, because you can't insert tables like that! So you still need to whitelist tablenames and concat the sql.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Sulla-Marius 88 posted:

So it'll wind up looking like:

php:
<?
$query = 'SELECT foo FROM ? WHERE baz = ? UNION ALL SELECT foo FROM ? WHERE baz = ?';
$sth = $dbh->prepare($query);
$sth->execute(array( $table1, $baz, $table2, $baz ));
?>
God that's messy! I might spend an extra ten minutes and see if I can't encapsulate that into a frustratingly-specific function.

Thanks for your help.

Just to clarify what KARMA! said, you can't bind identifiers (table & column names). Only values can be bound. You'd need to SELECT foo FROM $table1 WHERE baz = ? UNION ALL SELECT foo FROM $table2 WHERE baz = ?

Sulla Faex
May 14, 2010

No man ever did me so much good, or enemy so much harm, but I repaid him with ENDLESS SHITPOSTING

KARMA! posted:

Nope, because you can't insert tables like that! So you still need to whitelist tablenames and concat the sql.

php:
<?
$tables = array("table1", "table2", "table3");
$column = "DBColumnName";

        $count = count($tables);
        $statement = "SELECT *, {$tables[0]} as table FROM {$tables[0]} WHERE {$column} LIKE ?";
        // ensure that it always passes at least one query table


        $i = 1; // skip the first table that we already accounted for
        while ($i < $count) {
            $statement .= " UNION ALL ";
            $statement .= "SELECT *, {$tables[$i]} as table FROM {$tables[$i]} WHERE {$column} LIKE ?";  
          // every extra table gets a UNION ALL then the query repeated     
        }
        
        $sth = $this->db->prepare($statement);
        $exec = array();
        $x = 0;

        while ($x < $count) {
            $exec[] = "searchterm"; // the search term that gets bound as each instance of ? above
            $x++;
        }
        // $exec now has as many "searchterms" as there are ?'s in the above

        $sth->execute($exec);
        
?>
This is what I've come up with. Is it horribly broken? I haven't tested it yet...

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker
The random tabbing and extraneous loops aside, yep.

php:
<?
$column      = "DBColumnName";
$statements  = array();
$bound_input = array(); 

foreach(array("table1", "table2", "table3") as $table)
{
    $statements[]  = "SELECT *, '{$table}' as table FROM {$table} WHERE {$column} LIKE ?";
    $bound_input[] = '%a search term%';
}

$sql = implode(' UNION ALL ', $statements);

$sth = $this->db->prepare($sql);
$sth->execute($bound_input);
?>

ATM Machine
Aug 20, 2007

I paid $5 for this

Sulla-Marius 88 posted:

php:
<?
$query = 'SELECT foo FROM ? WHERE baz = ? UNION ALL SELECT foo FROM ? WHERE baz = ?';
$sth = $dbh->prepare($query);
$sth->execute(array( $table1, $baz, $table2, $baz ));
?>

This is a minor nitpick I think, I just find ?'s throughout the queries annoying, but is there any reason no one has recommended using named params, then using an associative array?

php:
<?
$query = 'SELECT foo FROM :table WHERE baz = :baz UNION ALL SELECT foo FROM :table2 WHERE baz = :baz';
$sth = $dbh->prepare($query);
$sth->execute(array("table" => $table1,"baz" => $baz,"table2" =>$table2));
?>
Saves having the same variable in the array twice just to match the order in the query, plus it makes it slightly more obvious what the expected values are in the query.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I agree ATM Machine. When you go back to modify the code a year later you are stuck counting question marks and it's a big pain in the rear end. I definitely prefer the named parameters.

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.
Personally? I prefer to use the absolute long-form for prepared queries, which allows some... interesting code

php:
<?
$v = 1;

$query = $__CONNECTION->prepare("SELECT count(`id`) as count
                                 FROM `".DB_PREF."settings`
                                 WHERE `setting`=:setting
                                 AND `value`=:value
                                 GROUP BY `value`");

$query->bindValue(':hash', self::key(), PDO::PARAM_STR);
$query->bindParam(':visible', $v, PDO::PARAM_INT);

$vis = array('totalvisible'=>1,
             'killed'=>0,
             'autokilled'=>-1,
             'spam'=>-2);

$breakdown = array();
foreach ($vis as $k=>$v) {
    $query->execute();
    $breakdown[$k] = 0;
    
    if ($r = $query->fetch(PDO::FETCH_ASSOC)) {
        $breakdown[$k] = $r['count'];
    }
}
?>
In this example, I bind :hash to the value of self::key() as a string, and bind :visible to the variable $v as an integer. What this means is that I can run the query multiple times by updating the variable $v.

It's possibly a little confusing for people who are unfamiliar with the difference between "bindValue" and "bindParam", but I like it.

Vintersorg
Mar 3, 2004

President of
the Brendan Fraser
Fan Club



I'm freaking out over here. I was just handed a project to help with loading a database using CodeIgniter. The database has only about 2500 records but the previous guy made it so you can only load 20 records at a time. I am using the jQuery DataTables plugin for displaying records but the sort is broken since only 20 records come up per page. Pagination is being handled by CI as well.

If I try increasing the amount of records loaded it considerably slows down the page load. Any idea on how to load all records but not have the system crawl? DataMapper, which is being used, shows some alternate methods (right now get() is being used with 20 being thrown in for the $count but as mentioned, increasing that slows things down) like get_iterated() but it doesn't seem to increase performance.

Here is the code being used to query things from the Model.

PHP code:
public function search_by_trade_name ($trade_name, $cat = 0, $region = 0, $offset = 0, $count = 20)
	{
		$trades = $this->_name_search($trade_name, $cat, $region);	
		$total = $trades->count();
		//$trades->check_last_query();
		$trades = $this->_name_search($trade_name, $cat, $region);
				
		$trades->get($count, $offset);
		//$trades->check_last_query();
		
		$this->populate($trades);		

		$trades->totalrows = $total;

		return $trades;
	}

private function _name_search ($trade_name, $cat, $region)
	{
		$trades = new Trades_detail();
		
		//$trades->select('id, trade_name, region_id');
		if ($trade_name != "")
		{
			$trades->ilike('trade_name', $trade_name);
		}
		
		//$trades->join ()
		//$trades->where ("`trades_details`.`id` =  `trades`.`active_trades_details_id`");

		if ($cat != 0)
		{
			$trades->where_related_trades_category('id', $cat);
		}

		if ($region != 0)
		{
			$trades->where_related_region('id', $region);
		}
		
		return $trades;		
	}

// populate the relationships
	public function populate()
	{
		if ($this->result_count() > 1)
		{

			// Run through each result and populate their relationships
			foreach ($this as &$t)
			{
				$t->region->get();
				$t->trades_category->get();
				
				$cats = array();
				foreach ($t->trades_category as $cat)
				{
					$cats[] = anchor('trades/category/' . urlencode($cat->category), $cat->category );
				}
				
				// Also create a text entry for categories for easy display
				$t->categories = implode (', ', $cats);
			}
			
		} else {
			$this->region->get();
			$this->trades_category->get();
			
			$cats = array();
			foreach ($this->trades_category as $cat)
			{
				$cats[] = anchor('trades/category/' . urlencode($cat->category), $cat->category );
			}
			
			// Also create a text entry for categories for easy display
			$this->categories = implode (', ', $cats);			
		}

	}

Nebulon Gate
Feb 23, 2013

Vintersorg posted:

I'm freaking out over here.

The problem is most definitely in the model or some type of configuration. DataMapper is very fast. 2500 records is not very much at all. Can you post your model?

burnishedfume
Mar 8, 2011

You really are a louse...
I'm really new to PHP and I'm trying to create a simple script that generated a random number, gives the users 5 tries to guess it, and then generate a new number using a session, but I hit a bit of a bump; for whatever reason, in the middle of my first comparison, it just starts outputting the rest of the php to the screen. I make the comparison

PHP code:
if($_SESSION['guess'] > $_SESSION['num']) {
echo "Too high";
$_SESSION['guesses']++;
}
and instead of doing the comparison, it just prints out everything starting with $_SESSION['num']. It's also not printing out the result of an earlier line, which is supposed to print out the randomly generated number. Any ideas on why it's doing that? I suspect it's something really simple and I'm just being dumb right now, but I just can't seem to find it :(.

E: :downs: Wait, nevermind, I'm good. I was previewing an old version of the file while trying to debug a newer version of the file saved elsewhere. All good now, newer version of the file does not have this problem.

burnishedfume fucked around with this message at 23:04 on Mar 2, 2013

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker
Post the whole thing.

klem_johansen
Jul 11, 2002

[be my e-friend]
Suddenly, my server is returning pages with a blank line at the top of every page (only on PHP scripts). I assumed this had to do with my code, but even if I isolate a page away from the CMS I can see the blank line at the top- so this doesn't seem to do with WordPress or any other specific code if a completely independent script is returning the same error.

Test: With just simple HTML (no <?php ?> tags) in both an .html file and another with a .php extension, the source looks normal in html but with the php extension the output starts on line 2.

The config file looks like it hasn't changed. Any ideas?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
In your isolated script, try adding this to the type (do not do this on production or publicly accessible pages, some error messages will leak your database credentials and things like that):

code:
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting (E_ALL);
Also check the error logs for the web server that you are using, might be some clues in there.

klem_johansen
Jul 11, 2002

[be my e-friend]

fletcher posted:

In your isolated script, try adding this to the type (do not do this on production or publicly accessible pages, some error messages will leak your database credentials and things like that):

code:
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting (E_ALL);
Also check the error logs for the web server that you are using, might be some clues in there.

Thanks. I'll keep digging in the error logs. The php error code didn't reveal anything.

Nebulon Gate
Feb 23, 2013

klem_johansen posted:

Suddenly, my server is returning pages with a blank line at the top of every page (only on PHP scripts). I assumed this had to do with my code, but even if I isolate a page away from the CMS I can see the blank line at the top- so this doesn't seem to do with WordPress or any other specific code if a completely independent script is returning the same error.

Test: With just simple HTML (no <?php ?> tags) in both an .html file and another with a .php extension, the source looks normal in html but with the php extension the output starts on line 2.

The config file looks like it hasn't changed. Any ideas?

What are you encoding in? You're probably getting a byte-order-mark at the top of your page. Set the encoding to UTF-8 without BOM and it should go away.

qntm
Jun 17, 2009

klem_johansen posted:

Suddenly, my server is returning pages with a blank line at the top of every page (only on PHP scripts). I assumed this had to do with my code, but even if I isolate a page away from the CMS I can see the blank line at the top- so this doesn't seem to do with WordPress or any other specific code if a completely independent script is returning the same error.

Test: With just simple HTML (no <?php ?> tags) in both an .html file and another with a .php extension, the source looks normal in html but with the php extension the output starts on line 2.

The config file looks like it hasn't changed. Any ideas?

If you have a PHP script which looks like this:

code:
<?php ?> 

with a trailing space and line break after the ?>, the trailing whitespace will appear in the output. Maybe one of your PHP scripts has had some trailing whitespace added?

ATM Machine
Aug 20, 2007

I paid $5 for this

qntm posted:

If you have a PHP script which looks like this:

code:
<?php ?> 

with a trailing space and line break after the ?>, the trailing whitespace will appear in the output. Maybe one of your PHP scripts has had some trailing whitespace added?

From what I understand, his test was of a plain html file, renamed as a PHP file, and the output was altered despite no PHP being used.

I think it sounds like something is happening server side to alter the page by trying to insert something after a request for a PHP file is made, whatever its trying to insert has been removed or prevented, but whatever is doing it hasn't, so its adding in a blank newline.

Of course, maybe its something simple like a rogue php.ini file that's caused a setting to be overwritten somewhere.

If its possible, can you copy everything onto a local server like XAMPP or something similar and see if it produces the same results?

ATM Machine fucked around with this message at 14:52 on Mar 5, 2013

Vintersorg
Mar 3, 2004

President of
the Brendan Fraser
Fan Club



Cartesian_Duelist posted:

The problem is most definitely in the model or some type of configuration. DataMapper is very fast. 2500 records is not very much at all. Can you post your model?

There is 5 separate models being referenced. I'll link to them and see if that helps but I am not sure what we can do other then a total code re-write here. The way this thing was designed is that it's referencing 5 different tables.

trades
id
subscription_id

trades_details
id
trade_id
trade_name
email

ratings
trade_id

subscriptions
id
subscription_type

membership_types
id
membership_type

Table being displayed:


Here is the main controller (admin_trades.php)
http://pastebin.com/JpjxHLaU

This is the view (admin_trades_browse.php)
http://pastebin.com/QAq7j3j9

These are the various models being called (it's a mess, I hate them and wish I was never left with them)
Model->Trade
http://pastebin.com/DFDsF1TA

Model->Trades_Detail
http://pastebin.com/RDe49uvw

Model->Ratings
http://pastebin.com/jQ3rkLDG

Model->Membership_Type
http://pastebin.com/k49LdviN

Model->Subscription
http://pastebin.com/6qtrbCXH

I am pretty much posting out of desperation. Unsure why it's doing this. Am I asking too much by wanting to sort the fields by rating?

Zamujasa
Oct 27, 2010



Bread Liar

ATM Machine posted:

I think it sounds like something is happening server side to alter the page by trying to insert something after a request for a PHP file is made, whatever its trying to insert has been removed or prevented, but whatever is doing it hasn't, so its adding in a blank newline.

Of course, maybe its something simple like a rogue php.ini file that's caused a setting to be overwritten somewhere.

If its possible, can you copy everything onto a local server like XAMPP or something similar and see if it produces the same results?

Wordpress was mentioned; I'm starting to wonder if it's possibly a rogue file somewhere that's doing it. Maybe it's something like auto-prepend-file in a php.ini or .htaccess somewhere.


Try creating a page with just <?php phpinfo(); and see if it gives you any information.


If that doesn't, try this:

php:
<?
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting (E_ALL);

header("Content-type: text/plain");
print "Test";
?>
If the blank line is coming from before this and you don't have output buffering on somewhere, it'll throw an error with what file caused it to be output. Otherwise you'll just get a text page with "Test" on it.


This is all voodoo debugging, though. Good luck finding the cause.

teethgrinder
Oct 9, 2002

Does anyone have a suggestion for a(n API) documenter? Been messing around with phpDocumenter, but it's kind of low-rent. My boss wants something that looks like Yii's: http://www.yiiframework.com/doc/api/

Unfortunately it looks like Yii's is probably an app using their own framework or something. They released a version for others to create static pages, but it seems to only export the actual framework and nothing from our app. As well it hasn't been updated in two years, and isn't nearly as nice as what they have currently published.

ApiGen looks like it has a lot of potential followed by phpDocumenter2. I've also looked at Doxygen, HeaderDoc, ROBODoc, ThimbleDoc & TwinText.

I think I'm just going to have to beat either ApiGen or phpDocumenter2 into submission.

teethgrinder fucked around with this message at 23:10 on Mar 6, 2013

DaTroof
Nov 16, 2000

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

teethgrinder posted:

Does anyone have a suggestion for a(n API) documenter? Been messing around with phpDocumenter, but it's kind of low-rent. My boss wants something that looks like Yii's: http://www.yiiframework.com/doc/api/

Unfortunately it looks like Yii's is probably an app using their own framework or something. They released a version for others to create static pages, but it seems to only export the actual framework and nothing from our app. As well it hasn't been updated in two years, and isn't nearly as nice as what they have currently published.

ApiGen looks like it has a lot of potential followed by phpDocumenter2. I've also looked at Doxygen, HeaderDoc, ROBODoc, ThimbleDoc & TwinText.

I think I'm just going to have to beat either ApiGen or phpDocumenter2 into submission.

Zym has a nice template for phpDocumentor that's similar to Yii's design: http://zymengine.com/dev/news/30-phpdoc-extjs-converter-template

Fluue
Jan 2, 2008
Hi guys,

Can I get some help working through a 2D $_POST array and PDO insert queries?

Right now, I have a 2D Post array that looks like this:

code:

Array (
[numGuests] => 2
[cwid] => 10142585
[submit_check] => 1
[fName] => Array (
[0] => Bob
[1] => Cheese
)
[lName] => Array (
[0] => Dog
[1] => Sandwich
)
[phone] => Array (
[0] => 1243456789
[1] => 1243456789
)
[tixNumber] => Array (
[0] => 234236526
[1] => 3423526
)
[paymentType] => Array (
[0] => cash
[1] => cash
)
[check_number] => Array (
[0] =>
[1] =>
)
[submit] => Submit
) 

but I'm having trouble doing a loop that goes through the values (Except numGuests, CWID, submit_check, and submit), binds them to a param in a prepared query, then executes the query and reloops until the array is complete.

I've tried a foreach and a for, but it's not inserting and I'm getting a reference error in the error log.

Where am I going wrong here?

Fluue fucked around with this message at 06:42 on Mar 7, 2013

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

You should post your code first so we can tell you what's going wrong.

Fluue
Jan 2, 2008

KNITS MY FEEDS posted:

You should post your code first so we can tell you what's going wrong.

http://pastebin.com/LkQfNBUn

The commented out SQL statements are from an earlier version of this when the server didn't have support for PDO. I was thinking that looping for $i would do the trick (by binding, then executing), but the script never inserts data to the database.

klem_johansen
Jul 11, 2002

[be my e-friend]

Zamujasa posted:

Wordpress was mentioned; I'm starting to wonder if it's possibly a rogue file somewhere that's doing it. Maybe it's something like auto-prepend-file in a php.ini or .htaccess somewhere.


Try creating a page with just <?php phpinfo(); and see if it gives you any information.


If that doesn't, try this:

php:
<?
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting (E_ALL);

header("Content-type: text/plain");
print "Test";
?>
If the blank line is coming from before this and you don't have output buffering on somewhere, it'll throw an error with what file caused it to be output. Otherwise you'll just get a text page with "Test" on it.


This is all voodoo debugging, though. Good luck finding the cause.

I didn't see an error on either page. On the example above, I just see "test" with the source starting on line 2. As a workaround I used ob_get_clean to get the pdf exporters working again, but I'd really like to know why this happened.

Fluue
Jan 2, 2008

Fluue posted:

http://pastebin.com/LkQfNBUn

The commented out SQL statements are from an earlier version of this when the server didn't have support for PDO. I was thinking that looping for $i would do the trick (by binding, then executing), but the script never inserts data to the database.

I'm still getting an error saying my loop goes out of bounds when referencing the array. The 2D array, at most, has a $_POST['fieldname'][0] and $_POST['fieldname][1], yet the code seems to think I'm going to up to 2. I'm thinking it's maybe how I'm counting the loop, but I'm not sure. Errors aren't being very helpful.

Video Nasty
Jun 17, 2003

Fluue posted:

I'm still getting an error saying my loop goes out of bounds when referencing the array. The 2D array, at most, has a $_POST['fieldname'][0] and $_POST['fieldname][1], yet the code seems to think I'm going to up to 2. I'm thinking it's maybe how I'm counting the loop, but I'm not sure. Errors aren't being very helpful.

Here's where your code is going wrong:
code:
   $numGuests = $numGuests-1;
You will want to use a pre-decrementing operator if you want to re-use the same variable, so try this:
code:
   $numGuests = --$numGuests; 
Reason being, it will work through the original value, assigning the value of itself, to itself; then subtracting one. I do not believe it will retain the value for your loop, so you will be better off using a pre-decrement operator to subtract from the variable before assigning it a new value.

Sulla Faex
May 14, 2010

No man ever did me so much good, or enemy so much harm, but I repaid him with ENDLESS SHITPOSTING
Using PDO, why does "SELECT name FROM" work while "SELECT * FROM" doesn't...?

E.g.

php:
<?
$column = "columnname";
$table = array("table1", "table2");
$word = "blah";


        $statements = array();

        foreach ($tables as $table) {
            $statements[] = "SELECT * FROM {$table} WHERE {$column} LIKE :searchword";
        }

        $sql = implode(' UNION ALL ', $statements);
        try {
            $sth = $this->db->prepare($sql);
            $sth->execute(array("searchword" => $word));
            $data = $sth->fetchAll();
            return $data;
        } catch (Exception $e) {
            echo "devmode. error: " . $e->getMessage();
        }
    }
?>
I just filled in $table, $column, $word vars then although they are legitimately sourced and working in the original, so ignore any typos there.

If I change the asterisk to a column name it works, but using the asterisk a var_dump on $data returns array(0) {}.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Do the tables have the same columns in the same order? Union wants to combine things which have the same structure, which would explain why combining a single column from each table works, but trying to do it to everything fails.

Adbot
ADBOT LOVES YOU

McGlockenshire
Dec 16, 2005

GOLLOCKS!
You also forgot to tell us what you mean when you say that it "doesn't work."

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