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
Null Set
Nov 5, 2007

the dog represents disdain

Adraeus posted:

Why would a single table be a bad idea?

code:
User Table
id  |  fname  |  lname  |  address  |  city  |  zip  |  phone  |  website  |  etc.
I was thinking of just storing multiple values as an array, like so:

code:
User Table
id  |  fname  |  lname  |  address            |  website      |
1   |  John   |  Smith  |  1234 Columbus, OH  |  www,www,www  |
I suppose having separate tables would be easier to manage though. Any other reasons?

Every time you do that, a DBA shoots themselves in the head. Unless you have a good reason (and 99.9% of the time you won't), don't do that. Anyone that has to maintain that will curse your name.

Granted, it might not be a big deal in this one instance, but you shouldn't get in the habit of doing that, because it is very, very wrong.

If you ever need to query on that field, you're hosed because you'll have to do string operations, which are slow as all hell on non-trivial data sets.

You're using a relational database. Store your data as relations, don't do comma separated fields. Reference tables are your friend, and make whoever comes after you not hate you.

Adbot
ADBOT LOVES YOU

IT Guy
Jan 12, 2010

You people drink like you don't want to live!
Everything that he said ^

At any time if you find yourself storing values into a single field with a delimiter, then 99.9% of the time, your database design is wrong and you need to rethink your strategy.

You can't query off it like the above poster mentioned without doing slow string functions.

Let's say you wanted to count how many websites a user has.

code:
SELECT COUNT(*) FROM `websites` WHERE `websites`.`user_id` = :uid
is so much easier than whatever query would be needed to explode your array from the delimiter.

Zamujasa
Oct 27, 2010



Bread Liar

DaTroof posted:

Close. If they have the same name, the value in $_GET/$_POST will simply be the last one received; but if you bracket the end of it (e.g., <input type="text" name="website[]" />), all the values will be appended to an array.

You can also do fun things like this:

code:
<form ...>
 <input name="data[1][name]" type="text" value="Name">
 <input name="data[1][addr]" type="text" value="Address">

 <input name="data[2][name]" type="text" value="Name 2">
 <input name="data[2][addr]" type="text" value="Address 2">
</form>
It makes it a great deal easier to work with dynamic forms where you can have multiple rows or columns of input. :)



IT Guy posted:

Everything that he said ^

At any time if you find yourself storing values into a single field with a delimiter, then 99.9% of the time, your database design is wrong and you need to rethink your strategy.

You can't query off it like the above poster mentioned without doing slow string functions.

Let's say you wanted to count how many websites a user has.

code:
SELECT COUNT(*) FROM `websites` WHERE `websites`.`user_id` = :uid
is so much easier than whatever query would be needed to explode your array from the delimiter.

We have an instance which I thought was part of the 0.1%; we store a CSV-list of numbers for a set that we use when adding a new object to the database. e.g. "object_defn [ id=1, something="such and such", subobject_ids="1,2,3,4,17,18,19,20" ]". When the code creates a new object, it pulls out the list of subobjects to make (and each one of those is a new row, so the CSV is only for the definition).


After some thought, though, even that could probably be handled better, since a lot of object definitions have the same subobject_ids and we could skip the explode-insert loop in code using INSERT INTO ... SELECT. :aaa:

(The original designers used a lot of this CSV-in-a-database stuff for things that really should have been normalized, and we've fixed all but this one.)

Adraeus
Jan 25, 2008

by Y Kant Ozma Post
I have a new unrelated array_search() problem.

PHP code:
<?php
function get_social_icons($services) {

	$dir = str_replace(get_bloginfo('url') . '/', '', get_bloginfo('template_directory')) . '/icons/sharing/';
	$icons = glob($dir . '*_16.png', GLOB_NOCHECK);

	/*
		[0] => wp-content/themes/2013/icons/sharing/digg_16.png
		[1] => wp-content/themes/2013/icons/sharing/email_16.png
		[2] => wp-content/themes/2013/icons/sharing/facebook_16.png
		[3] => wp-content/themes/2013/icons/sharing/linkedin_16.png
		[4] => wp-content/themes/2013/icons/sharing/reddit_16.png
		[5] => wp-content/themes/2013/icons/sharing/twitter_16.png
	*/
	
	foreach($services as $service) {
		if($service == 'linkedin') {
			$label = str_replace('linkedin', 'LinkedIn', strtolower($service));
		} else {
			$label = ucfirst(strtolower($service));
		}
		$id = array_search(strtolower($service), array_map('strtolower', $services));
		$url = '#';
		echo '<a class="icon" href="'.$url.'" title="'.$label.'"><img class="icon" src="/'.$icons[$id].'" /></a>
			  <a class="link" href="'.$url.'" title="'.$label.'">'.$label.' '.$id.'</a>';
	}
}
?>
This function is supposed to output social icons/links in the order provided with the function call.

PHP code:
<?php get_social_icons(array('email', 'twitter', 'facebook', 'linkedin', 'digg', 'reddit')); ?>
Unfortunately, while the order of the links is correct, the order of the icons is not.

quote:

Email 0 Twitter 1 Facebook 2 LinkedIn 3 Digg 4 Reddit 5

I think that array_search() is the wrong solution, but I'm not sure where to go from here.

nachos
Jun 27, 2004

Wario Chalmers! WAAAAAAAAAAAAA!
I'm tasked with trying to evaluate frameworks to build APIs. Haven't really dealt with them before so is performance a concern with any of the major ones like Yii, Laravel, Symfony, etc? What makes a framework fast or slow? Is performance even a legitimate concern or am I correct in thinking that has less to do with framework and more do to with web server configuration/query optimization?

Mister Chief
Jun 6, 2011

Adraeus posted:

I have a new unrelated array_search() problem.

Just cut out all of the directory and file operations?

<a class="icon" href="'.$url.'" title="'.$label.'"><img class="icon" src="' . $service . '_16.png" /></a>

Mister Chief fucked around with this message at 05:20 on Jan 26, 2013

Adraeus
Jan 25, 2008

by Y Kant Ozma Post

Mister Chief posted:

Just cut of all of the directory and file operations?

<a class="icon" href="'.$url.'" title="'.$label.'"><img class="icon" src="' . $service . '_16.png" /></a>

I guess that is simpler. I was trying to be fancy. Thanks!

musclecoder
Oct 23, 2006

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

nachos posted:

I'm tasked with trying to evaluate frameworks to build APIs. Haven't really dealt with them before so is performance a concern with any of the major ones like Yii, Laravel, Symfony, etc? What makes a framework fast or slow? Is performance even a legitimate concern or am I correct in thinking that has less to do with framework and more do to with web server configuration/query optimization?

For the most part, it has to do with your hardware, I/O, SSL handshaking, HTTP pipelining and the like. Yes, some frameworks are faster than others, but you'll have other areas to look into before you have to worry about the framework. Just use APC to cache your objects, and memcache or Redis for a memory store and then you can concentrate on speeding up your actual code.

I assume you're building REST APIs with these frameworks. If so, I've got a really handy bundle that makes it pretty easy: https://github.com/brightmarch/BrightmarchRestfulBundle

Strong Sauce
Jul 2, 2003

You know I am not really your father.





php:
<?php
  if (array_key_exists('test',$_GET)) $_GET['test']();
  function a() { echo "hello"; }
?>

So I saw some code similar to this when I was reviewing resumes.

Basically my question is, is this exploitable? I assumed that the answer was yes but it seems like you can't get anything to exploit this. This may be because I'm running the Suhosin patch but I can't tell if that makes a difference. The only negative I see is that you can run phpinfo and see what the server is running.

Adraeus
Jan 25, 2008

by Y Kant Ozma Post
I'm trying to help some WordPress plugin developers troubleshoot a faulty plugin. Here's the relevant section of the code:

PHP code:
// PHP<5.3 compatibility layer.
if (!function_exists('preg_filter')) {
	function preg_filter($pattern, $replace, $subject, $limit = -1 , &$count = null) {
		if(!is_array($subject)) {
			$noArray = 1 ;
			$subject = array($subject);
		}

		$preg = preg_replace($pattern, $replace, $subject, $limit, &$count);

		$diff = array_diff($preg, $subject);

		if($noArray == 1) $diff = implode($diff) ;

		return $diff ;
	}
}
When I try to activate the plugin with this code, I get the following error:

quote:

Fatal error: Call-time pass-by-reference has been removed in /var/www/html/wp-content/plugins/recent-custom-post-type/recent-custom-post-type.php on line 392

Line 392 refers to:

PHP code:
$preg = preg_replace($pattern, $replace, $subject, $limit, &$count);
If I remove the ampersand from $count, I can activate the plugin. I don't know if the plugin functions correctly after that though. I've reported this problem to the developers, but they're being fairly insistent that nothing's wrong with their plugin because the plugin installs correctly on their server.

I'm not at all familiar with reference variables, so I can't tell what's the best practice here.

Any ideas?

The Gripper
Sep 14, 2004
i am winner

Adraeus posted:

I'm trying to help some WordPress plugin developers troubleshoot a faulty plugin. Here's the relevant section of the code:
http://php.net/manual/en/language.references.pass.php

PHP posted:

Note: There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.
Pretty much remove the & from &$count in preg_replace, since the function definition for preg_replace makes the argument pass by reference without you specifying at the call site.

Adraeus
Jan 25, 2008

by Y Kant Ozma Post

The Gripper posted:

http://php.net/manual/en/language.references.pass.php

Pretty much remove the & from &$count in preg_replace, since the function definition for preg_replace makes the argument pass by reference without you specifying at the call site.

Wow. Thanks! That was perfect. Maybe now they'll stop insisting that something's wrong with my server.

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

Strong Sauce posted:

php:
<?php
  if (array_key_exists('test',$_GET)) $_GET['test']();
  function a() { echo "hello"; }
?>

So I saw some code similar to this when I was reviewing resumes.

Basically my question is, is this exploitable? I assumed that the answer was yes but it seems like you can't get anything to exploit this. This may be because I'm running the Suhosin patch but I can't tell if that makes a difference. The only negative I see is that you can run phpinfo and see what the server is running.

Same reason why reqister_globals is really dumb.

Turkeybone
Dec 9, 2006

:chef: :eng99:
Hello thread, I am a new student of php with a probably easy/dumb question. I was doing a feature for a little text manipulator that would preg_replace a word with a randomly chosen string from an array. I thought to use rand_array for this, but it seemed that it would pick a random string once, and use that same string in all instances. It seemed to work if I did
code:
rand(0,($stringArray)-1);
ANYWAY so the question is, would this work if I just skipped the rand altogether and wrote
code:
preg_replace('StringToReplace',shuffle($myArray)[0],$string)
or something like that? Thanks in advance.

Doh004
Apr 22, 2007

Mmmmm Donuts...

Turkeybone posted:

Hello thread, I am a new student of php with a probably easy/dumb question. I was doing a feature for a little text manipulator that would preg_replace a word with a randomly chosen string from an array. I thought to use rand_array for this, but it seemed that it would pick a random string once, and use that same string in all instances. It seemed to work if I did
code:
rand(0,($stringArray)-1);
ANYWAY so the question is, would this work if I just skipped the rand altogether and wrote
code:
preg_replace('StringToReplace',shuffle($myArray)[0],$string)
or something like that? Thanks in advance.

I think that would work, but I believe your first code didn't work because you left out count:

PHP code:
rand(0,count($stringArray)-1);

Turkeybone
Dec 9, 2006

:chef: :eng99:
Oh yes, sorry. I did include that in the code, just an oversight in my copying. Thanks!

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.

Turkeybone posted:

Hello thread, I am a new student of php with a probably easy/dumb question. I was doing a feature for a little text manipulator that would preg_replace a word with a randomly chosen string from an array. I thought to use rand_array for this, but it seemed that it would pick a random string once, and use that same string in all instances. It seemed to work if I did
code:
rand(0,($stringArray)-1);
ANYWAY so the question is, would this work if I just skipped the rand altogether and wrote
code:
preg_replace('StringToReplace',shuffle($myArray)[0],$string)
or something like that? Thanks in advance.

If you're not using regular expressions to match the string, don't use preg_replace, instead use str_replace.

Also, shuffle doesn't return an array - it returns a bool. It actually modifies the original array:

php:
<?
$a = array(1,2,3,4);
echo implode(', ', $a)."\n"; // 1, 2, 3, 4
echo $a[0]."\n"; // 1
shuffle($a);
echo implode(', ', $a)."\n"; // 3, 2, 1, 4
echo $a[0]."\n"; // 3
?>
It's a pretty expensive operation to be performing repeatedly, especially just to pull out a random element, so perhaps this would be better:

php:
<?
$a = array(1,2,3,4);
echo $a[rand(0, count($a)-1)]."\n"; // 3
echo $a[rand(0, count($a)-1)]."\n"; // 2
echo $a[rand(0, count($a)-1)]."\n"; // 3
echo $a[rand(0, count($a)-1)]."\n"; // 1
echo $a[rand(0, count($a)-1)]."\n"; // 4
?>
Which could be better optimised by taking the length of the array once:

php:
<?
$a = array(1,2,3,4);
$lastElem = count($a)-1;
echo $a[rand(0, lastElem)]."\n"; // 1
echo $a[rand(0, lastElem)]."\n"; // 3
echo $a[rand(0, lastElem)]."\n"; // 3
echo $a[rand(0, lastElem)]."\n"; // 1
echo $a[rand(0, lastElem)]."\n"; // 4
?>

Turkeybone
Dec 9, 2006

:chef: :eng99:
Great, thanks! I did use a very basic regex, but I didn't know about str_replace so that's good, and the rest also makes sense. Thanks again.

Adraeus
Jan 25, 2008

by Y Kant Ozma Post

Turkeybone posted:

Great, thanks! I did use a very basic regex, but I didn't know about str_replace so that's good, and the rest also makes sense. Thanks again.

Your best friend:
http://www.php.net/manual/en/index.php

If you search for "replace," you'll get results showing you every way to replace something.

e: Also, arrays are the coolest thing ever. You can do so much with arrays. And you can learn quite a bit about PHP by doing what you'd normally do with a few DB calls with only array functions. This is an example of what not to do, but it was great fun, too.

Adraeus fucked around with this message at 08:06 on Feb 5, 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
I've been reading up on MVC but what I've found really helpful are the youtube videos by JREAM to understand how an implementation works in practice. I'm still getting through his videos but wanted to make sure I understand the core concept before I get bogged down in details.

Is it perfectly acceptable to have two sub-controllers in an MVC rollout, one for static, one for dynamic? For example:

Core website loads via index.php, which calls the bootstrap file, which parses the URL and determines which controller to load, and the model and view (which depends upon default controller behaviour as well as the initial URL call, e.g. domain.com/controller/action/query, action + query being method($args), which would then call the view.

That then remains static until a new MVC-link requires a new controller, which loads the entire page again based on the link.

Any smaller changes would be done though jquery, referring to divs created during the view. So a jquery command would connect to a separate page with the business logic, process it, and output a view which would replace (or append) upon the target <div> -- without needing to go through the MVC again and reload everything.

Does this make sense? I'm designing a website that will have a whole bunch of content that will be manipulated by the user (and saved to/retrieved from an sql database) and need to be updated real-time in small and distinct portions of the screen, without affecting the other data by a reload etc.

Is this how MVC websites generally handle both static and dynamic features?

Turkeybone
Dec 9, 2006

:chef: :eng99:

Adraeus posted:

Your best friend:
http://www.php.net/manual/en/index.php

If you search for "replace," you'll get results showing you every way to replace something.

e: Also, arrays are the coolest thing ever. You can do so much with arrays. And you can learn quite a bit about PHP by doing what you'd normally do with a few DB calls with only array functions. This is an example of what not to do, but it was great fun, too.

Thanks. Yeah this is where the class is going, our next project is to make a catalog, I assume primarily with arrays. The DB stuff will come in the 2nd half.

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.

Turkeybone posted:

Thanks. Yeah this is where the class is going, our next project is to make a catalog, I assume primarily with arrays. The DB stuff will come in the 2nd half.

If they don't teach you with PDO, scream "YOU'RE DOING IT WRONG!" and throw a table.

Seriously, though, no modern PHP course should be teaching database stuff with anything other than PDO.

Turkeybone
Dec 9, 2006

:chef: :eng99:

bobthecheese posted:

If they don't teach you with PDO, scream "YOU'RE DOING IT WRONG!" and throw a table.

Seriously, though, no modern PHP course should be teaching database stuff with anything other than PDO.

Well, it's "Intermediate Web Design", so hopefully it's relevant to reality. I'll report in.

Doh004
Apr 22, 2007

Mmmmm Donuts...

Turkeybone posted:

Well, it's "Intermediate Web Design", so hopefully it's relevant to reality. I'll report in.

Don't worry, it won't ;)

(Graduated from a 4 year IT degree and learned more from outside experience :saddowns:)

SimonNotGarfunkel
Jan 28, 2011
I've just made the switch from CodeIgniter to Laravel 4 beta and boy does the documentation seem to contradict itself a lot.

I'm really confused as to whether I should use the routes to handle most the logic or the actual controller themselves.

I'm currently playing with Form Validation and the example adds logic to the routes.php file, rather than the actual Controller.

php:
<?
Route::get('register', function()
{
    return View::make('user.register');
});

Route::post('register', function()
{
    $rules = array(...);

    $validator = Validator::make(Input::all(), $rules);

    if ($validator->fails())
    {
        return Redirect::to('register')->withErrors($validator);
    }
});
?>
What's generally considered "best practise" or how do you guys like to set it up?

Coming from CI, I would expect the routes.php to simply map to a controller function and build all the logic into there. :confused:

PleasantDilemma
Dec 5, 2006

The Last Hope for Peace
I haven't used Laravel as extensively as others have, but generally if the logic is small enough that you can do all of it in routes.php then it is OK. It seems this is common when your Laravel code is minimal and most of the work is done in the frontend and Laravel is just there to provide an interface to a database or something.

If you have a lot of logic or it has lots of separate parts, then split it up into controllers.

Is the beta out yet? Laravel 3 is pretty sweet and 4 seems like a big chance with the reliance on composer and being more broken up.

nachos
Jun 27, 2004

Wario Chalmers! WAAAAAAAAAAAAA!
Best practice is to map it to a controller. Writing your logic inside the route itself is very handy for prototyping something or developing a simple tiny website, but know that you're essentially using Laravel as a microframework (think Silex) at that point. It's a really nice feature but definitely not what an MVC framework like Laravel is meant for.

SimonNotGarfunkel
Jan 28, 2011
Thanks guys. I'll go down that route then.

EDIT: You can download the latest beta here and documentation is here.

Apparently full release is imminent.

SimonNotGarfunkel fucked around with this message at 18:49 on Feb 6, 2013

Long John Power
Sep 11, 2001

I am having what feels like a pretty basic trying to use PDO for some SQL that I have totally hit a brick wall on

From what I have read PDO is adding quotes to the LIMIT command eg '3','10' which is making it not work correctly as it needs to be an integer.

From looking around what feels like 100s of sites, I have tried various binds and prepared statements as a solution but I cannot get this LIMIT to work correctly.

Everything else works perfectly. Surely there must be a really simple solution for this that I am missing?

The basic code is:

php:
<?

$sql= "SELECT * FROM [db].[dbo].[Tb] ORDER by ID LIMIT 3,10 DESC";   

foreach ($db->query($sql) as $id) {                    
  $page[$count]=$id[1];
  $count=$count+1;                        
}

?>

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.

Long John Power posted:

php:
<?

$sql= "SELECT * FROM [db].[dbo].[Tb] ORDER by ID LIMIT 3,10 DESC";   

foreach ($db->query($sql) as $id) {                    
  $page[$count]=$id[1];
  $count=$count+1;                        
}
?>

Which database engine are you using? The [db].[dbo].[Tb] looks like a MSSQL-ism, which doesn't (so far as I'm aware) support LIMIT 3,10 syntax.

In short, though, you answer should be this:

php:
<?
$sql= "SELECT * FROM [db].[dbo].[Tb] ORDER by ID LIMIT 3,10 DESC";   

$result = $db->query($sql);

foreach ($result->fetchAll() as $id) {                    
  $page[$count]=$id[1];
  $count ++;
}
?>
or, altenately:

php:
<?
$sql= "SELECT * FROM [db].[dbo].[Tb] ORDER by ID LIMIT 3,10 DESC";   

$result = $db->query($sql);

while ($id = $result->fetch()) {                    
  $page[$count]=$id[1];
  $count ++;
}
?>
PDO::query returns a result set as a PDOStatement Object.

To get the actual data from that, you need to either fetch each row, or fetchAll to get all the rows.

As a note, it's not good practice to do a SELECT *, and then access specific, un-named columns. That sets you up for future problems if someone decides to change the schema. Even if this is a once-off project that won't get used again, don't do it because it's a bad habit.

bobthecheese fucked around with this message at 11:45 on Feb 7, 2013

Long John Power
Sep 11, 2001

bobthecheese posted:

Which database engine are you using? The [db].[dbo].[Tb] looks like a MSSQL-ism, which doesn't (so far as I'm aware) support LIMIT 3,10 syntax.

In short, though, you answer should be this:

php:
<?
$sql= "SELECT * FROM [db].[dbo].[Tb] ORDER by ID LIMIT 3,10 DESC";   

$result = $db->query($sql);

foreach ($result->fetchAll() as $id) {                    
  $page[$count]=$id[1];
  $count ++;
}
?>
or, altenately:

php:
<?
$sql= "SELECT * FROM [db].[dbo].[Tb] ORDER by ID LIMIT 3,10 DESC";   

$result = $db->query($sql);

while ($id = $result->fetch()) {                    
  $page[$count]=$id[1];
  $count ++;
}
?>
PDO::query returns a result set as a PDOStatement Object.

To get the actual data from that, you need to either fetch each row, or fetchAll to get all the rows.

As a note, it's not good practice to do a SELECT *, and then access specific, un-named columns. That sets you up for future problems if someone decides to change the schema. Even if this is a once-off project that won't get used again, don't do it because it's a bad habit.

Thanks for that!

We are using PDO but it is through a Quercus install which is basically PHP on Java (don't ask), that is why (I think) it has to be in that format.

I scaled down the code from what I am actually using, just to keep it simple. I am actually using named cols on the code.

The code still has the problem with the LIMIT being converted to a string by what I am assuming is PDO?

http://stackoverflow.com/questions/7772648/php-pdo-limit-clause-issue
http://stackoverflow.com/questions/2269840/php-pdo-bindvalue-in-limit/2269931#2269931

They mention various solutions using a bind like this...

php:
<?
$statement->bindValue(':start', $start, PDO::PARAM_INT); 
$statement->bindValue(':limit', $per, PDO::PARAM_INT);
?>
But I didn't have any joy getting that to work at all. :(

Long John Power fucked around with this message at 12:11 on Feb 7, 2013

-JS-
Jun 1, 2004

code:
ORDER by ID LIMIT 3,10 DESC
This could just be a case of typoing the test case, but shouldn't this be:

code:
ORDER by ID DESC LIMIT 3,10
Otherwise, I can't see anything wrong with that. If you're actually including the 3, 10 directly in your SQL statement and not using placeholders I have no idea why PDO would be interfering with it.

Long John Power
Sep 11, 2001

-JS- posted:

code:
ORDER by ID LIMIT 3,10 DESC
This could just be a case of typoing the test case, but shouldn't this be:

code:
ORDER by ID DESC LIMIT 3,10
Otherwise, I can't see anything wrong with that. If you're actually including the 3, 10 directly in your SQL statement and not using placeholders I have no idea why PDO would be interfering with it.

Unfortunately not (I just triple checked). Simply adding the LIMIT 3,10 to the end of a working SQL statement causes the error:

"Fatal Error: 'fetchAll' is an unknown method of false."

Eventually I do want to use placeholders, but I wanted to ensure the LIMIT is working correctly. I guess it could be something going on behind the scenes in the way quercus is running that I might have to look at.

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.

Long John Power posted:

Unfortunately not (I just triple checked). Simply adding the LIMIT 3,10 to the end of a working SQL statement causes the error:

"Fatal Error: 'fetchAll' is an unknown method of false."

Eventually I do want to use placeholders, but I wanted to ensure the LIMIT is working correctly. I guess it could be something going on behind the scenes in the way quercus is running that I might have to look at.

Once again, makes me think that MySQL isn't the database that you're talking to.

Try this:

php:
<?
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "SELECT * FROM [db].[dbo].[Tb] ORDER by ID DESC LIMIT 3,10";

try {
    $result = $db->query($sql);
} catch (PDOException $e) {
    die ('SQL Error: '.$e->getMessage());
}

while ($id = $result->fetch()) {                    
    $page[$count]=$id[1];
    $count ++;
}
?>

Long John Power
Sep 11, 2001

bobthecheese posted:

Once again, makes me think that MySQL isn't the database that you're talking to.

Try this:

php:
<?
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "SELECT * FROM [db].[dbo].[Tb] ORDER by ID DESC LIMIT 3,10";

try {
    $result = $db->query($sql);
} catch (PDOException $e) {
    die ('SQL Error: '.$e->getMessage());
}

while ($id = $result->fetch()) {                    
    $page[$count]=$id[1];
    $count ++;
}
?>

Thanks again for the help, I guess that is easily possible given the setup here!

That comes back with the errors when limit is used:

Warning: function 'PDOException' has 2 required arguments, but only 1 were provided
SQL Error: SQLSTATE[SQLSTATE[42000]: Incorrect syntax near 'LIMIT'.]: null

and no errors when it isn't used.

EDIT: Just found out that this is a MSSQL server that I am connecting to, so that will explain why LIMIT isn't working, lets file this whole thing under schoolboy errors.

Long John Power fucked around with this message at 13:21 on Feb 7, 2013

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.

Long John Power posted:

Thanks again for the help, I guess that is easily possible given the setup here!

That comes back with the errors when limit is used:

Warning: function 'PDOException' has 2 required arguments, but only 1 were provided
SQL Error: SQLSTATE[SQLSTATE[42000]: Incorrect syntax near 'LIMIT'.]: null

and no errors when it isn't used.

EDIT: Just found out that this is a MSSQL server that I am connecting to, so that will explain why LIMIT isn't working, lets file this whole thing under schoolboy errors.

Learning is learning.

You will learn to hate MSSQL :P

Get into the practice of using PDO with exceptions, and handling exceptions intelligently (just dying and spitting out the error message isn't really intelligent handling of the error - ideally you should be logging it, and then stopping execution of the code gracefully, but hey - we don't always live in that ideal fantasy world)

Tei
Feb 19, 2011
Probation
Can't post for 17 hours!
I am a bad person, tryiing to make PHP do things is not designed to do.

I have this happy idea to implemente "prototype oop" to php.

Something like this:

php:
<?

$Hail = function(){

    function monday(){
         return "monday";
    }   

    $hello_world = function(){
          echo "hello world";
    };

    $hello_monday = function(){
         echo "what a beatiful ".monday()."!";
    };

    return compact("hello_world","hello_monday");
};

$hoi = $Hail();

$hoi["hello_monday"]();

?>
Do people here know of effort like this, to write funny "prototype oriented" php code?

I want my PHP to look more like Javascript, and less like Java or C++

Tei fucked around with this message at 16:57 on Feb 7, 2013

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.

Tei posted:

I am a bad person, tryiing to make PHP do things is not designed to do.

I have this happy idea to implemente "prototype oop" to php.

Something like this:

php:
<?

$Hail = function(){

    function monday(){
         return "monday";
    }   

    $hello_world = function(){
          echo "hello world";
    };

    $hello_monday = function(){
         echo "what a beatiful ".monday()."!";
    };

    return compact("hello_world","hello_monday");
};

$hoi = $Hail();

$hoi["hello_monday"]();

?>
Do people here know of effort like this, to write funny "prototype oriented" php code?

I want my PHP to look more like Javascript, and less like Java or C++

Just learn how to use PHP objects properly, or change to NodeJS.

If this is anything more than a 'just for fun'/hobby project, then you're a horrible person, and I'll point you out to YOSPOS.

PHP gets a bad enough rap without being JavaScript too :(

By the way, "Prototype OOP" is literally poop.

CabaretVoltaire
Jun 10, 2003
Better than Turin Brakes.
php:
<?
class Hail
{
    public function __call($method,$args)
    {
        $f = $this->$method;
        return $f();
    }

    public function __construct()
    {
        $this->monday = function(){
            return "monday";
        };

        $this->hello_monday = function(){
            echo "what a beautiful ".$this->monday()."!";
        };
    }
}
    
$hoi = new Hail();
$hoi->{"hello_monday"}();
?>
Does sort of what you want I guess (in 5.4 anyway)??
The __call magic method is needed because for some reason with these anonymous functions

$object->anonymousFunction();
Fails

but

$function = $object->anonymousFunction;
$function();

works "ok".

CabaretVoltaire fucked around with this message at 18:20 on Feb 7, 2013

Adbot
ADBOT LOVES YOU

CabaretVoltaire
Jun 10, 2003
Better than Turin Brakes.
This is even better / stupider.

Have a class like this:

php:
<?
    class C
    {
        function __call($m, $a = array())
        {
            if (is_callable($this->$m)) {
                $a[] = $this;
                return call_user_func_array($this->$m, $a);
            } else {
                return $this->m;
            }
        }
        
        function __construct($f) 
        {
            foreach ($f as $k => $v) {
                $this->$k = $v;
            }    
        }
    }
?>
And use it to make crap like this:
It just requires the last param of each method to be a pretend "$this"
php:
<?
    
    $o = new C(
        array(
            'monday' => function($th1s){
                return "monday";
            },
            'hello_monday' => function($th1s){
                echo 'hello '.$th1s->monday().'!';
            },
            'hello' => function($day, $th1s){
                echo 'hello '.$day.'!';
            }
        )
    );

    $o->{'hello_monday'}();
    $o->{'hello'}('tuesday');
?>
Maybe someone better at PHP can do something even worse

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