|
Hanpan posted:If I have an array, which contains a bunch of assoc arrays, is there a way to pass this array directly to the execute function without having to bind each param? Nope. The problem is that PDO thinks that there can be one and only one value for every placeholder, and is intentionally not smart enough to flatten arrays. Your best bet is to create classes that inherit from PDO and PDOStatement (use $db->setAttribute(PDO::ATTR_STATEMENT_CLASS, 'Classname') to set it up) to wrap query() / execute() so that it flattens arrays and/or finds the placeholder and expands it as required. Using question mark placeholders instead of named placeholders can make this much easier. Creating something that inherits from PDO is not a bad idea anyway, as then you can add happy convenience functions that PDO is missing.
|
# ? Sep 25, 2009 01:15 |
|
|
# ? May 16, 2024 21:01 |
|
haywire posted:Yep, because doing things in a better way and having organised code and/or working with other people are strictly reserved for people in big enterprisey corporations and a simple hobbyist would have no intention of improving themselves ever, now would they? I don't see how this retort has any bearing on what I said, given that my comment was clarificatory in nature and addressed to two posters who appeared to think I might be a programmer by trade. The "you can bet my attitude to this and other things would be different" part is an offhand comment rather than an approach to defending said attitude. n.b. That OOP is "a better way [to do things]" is an opinion that, popular though it appears to be here, I need not share.
|
# ? Sep 25, 2009 02:01 |
|
Hammerite posted:Oh dear, have I unwittingly stumbled into a part of these forums reserved for aspiring IT professionals?! If I decide to choose programming as a career path rather than a hobby, you can bet my attitude to this and other things would be different. It shouldn't be surprising that the people who frequent a forum for programmers take programming seriously and care enough to encourage good practices. Even the hobbyists. I only made that remark about staffing to show how strongly I felt about the subject. When you ask a question that implies a fundamental problem with your approach, people are going to point it out. And when your project starts with that kind of deficit, any questions you might ask later will be more complicated and difficult to answer.
|
# ? Sep 25, 2009 02:39 |
|
Hammerite posted:n.b. That OOP is "a better way [to do things]" is an opinion that, popular though it appears to be here, I need not share. You're certainly entitled to your opinion and OOP certainly isn't the only game in town (but it's the biggest). But the culture in a forum like this is generally 1) ask for help, or 2) trade around informed or at least semi-informed opinions. The statement "I don't understand X and <opinion>" sort of declassifies the opinion if you know what I mean. As for your original question, php is one of the most accommodating languages out there for offering non-OO alternatives. But offering it for a PHP Data Object is stretching things a bit. Prepared statements are a very good example of something that works well under an OO design and not so much in a "procedural" one.
|
# ? Sep 25, 2009 02:43 |
|
Could always write a sql($query, $arrParameters) or sql($query, ...) style wrapper for PDO to make it procedural-friendly. You'd have to touch that icky OOP code once but only once. Then the answer would be "absolutely, there is a way to use prepared statements that isn't long-winded."
|
# ? Sep 25, 2009 07:57 |
|
Hanpan posted:If I have an array, which contains a bunch of assoc arrays, is there a way to pass this array directly to the execute function without having to bind each param? I tried this: Following on from what McGlockenshire said, I recently extended the balls off MySQLi to do a similar thing, so I figure this will work for PDO too. In the below code we're extending the PDO class and creating a new query() function which we will pass both an SQL statement and an array of variables which will be bound to the ? characters in the statement, and then it'll return the executed result object. I havn't used PDO before or tested this code, so it probably doesn't work or use the PDO functions correctly from the get-go. php:<? /** * My PDO Class * Extends PDO, so we can use all its functions and add our own. */ class myPDO extends PDO { /** * Constructor * Needed to pass values on class creation up to the parent (PDO) class */ public function __construct($dsn, $username=null, $password=null, $driver_options=null) { parent::__construct($dsn, $username, $password, $driver); } /** * Query * Creates a prepared statement and binds the values */ public function query($query, $values=array()) { // Create the parepared statement $query = parent::prepare( $query ); // Go through values array and bind them to the prepared statement // $key is used to tie each value to each "?" in the SQL statement, in order. $key = 0; foreach ($values as $value) { $key++; // Doesn't specify the datatype for the value - erk. $query->bindParam($key, $value); } // Actually run the constructed query. return $query->execute(); } } // Example execution // Connect to PDO then use the object to run the query $db = new myPDO( "blah", "blah", "blah"); $result = $db->Query("SELECT * FROM ? WHERE ? = ?", array("table", "column", "value")); // Print out the returned rows.. I don't know if any of this in correct. while ($row = $result->fetchAll()) { print_r($row); } ?> php:<? // Set up an object with the prepared statement // Then use execute() to find the values on the fly. $query = $db->prepare('SELECT * FROM ? WHERE ? = ?'); $query->execute(array('table', 'column', 'value')); // Output, etc. while ($row = $query->fetchAll()) { print_r($row); } // You can then do execute() again with different values to run multiple queries. $query->execute(array("yams", "yams", "yams")) ?> Fun stuff, I don't know why we don't use PDO. Hammerite posted:I find OO programming ideas difficult to understand (partly because of unfamiliarity but partly because they seem to add complexity that I don't see the need for), so I dislike and avoid them. Just because you're doing PHP on a hobby level doesn't mean you shouldn't still learn new ways to improve your code. It's almost as if you've become stuck in your ways and have a misguided faith for procedural methods just because of your fear and apprehension about OOP. You have absolutely no experience or proof that your procedural methods are better than potential OOP solutions, whereas everyone here recommending OOP will have started off in your procedural shoes and worked through to object oritentation and formed their own independent opinions - seemingly all pointing to you at least learning to use OOP even if you choose not to use it. Please, for the love of god, stop defending your position and ask us about object orientated programming and the things which confuse you. Don't understand extends, the use of -> and ::? Don't see why it makes sense to put something into a class over its procedural counterpart? Ask us, and we'll happily explain without further remarks. v1nce fucked around with this message at 10:42 on Sep 25, 2009 |
# ? Sep 25, 2009 09:28 |
|
Thanks for the above code, I'll give it a try. At the moment I am doing this:code:
|
# ? Sep 25, 2009 11:05 |
|
As far as I'm aware you can't do multiple updates in a single query (at least where the values are unique to the item being updated) so the query and loop you've got right there is about as efficient as you're going to get for this task.
|
# ? Sep 25, 2009 11:29 |
|
Sorry, I didn't know where else to ask but is there a open source PHP file drop utility that looks nice? It'd need to be multi-user too.
|
# ? Sep 25, 2009 12:20 |
|
Bhaal posted:You're certainly entitled to your opinion and OOP certainly isn't the only game in town (but it's the biggest). But the culture in a forum like this is generally 1) ask for help, or 2) trade around informed or at least semi-informed opinions. The statement "I don't understand X and <opinion>" sort of declassifies the opinion if you know what I mean. Okay sure, but that's what gets me, because I did ask for help, or at least I asked a question. I asked is there a way of using prepared statements that allows me to minimise my use of OO approach? Even if the answer was a straightforward "No, not really", that would have been informative. I know that the responses of "That's not the approach you should be taking, and here's why" are offered in the spirit of helping me be a better programmer, but I feel they're also incomplete as responses to the question that induced this whole discussion. Bhaal posted:As for your original question, php is one of the most accommodating languages out there for offering non-OO alternatives. But offering it for a PHP Data Object is stretching things a bit. Prepared statements are a very good example of something that works well under an OO design and not so much in a "procedural" one. Thanks, your answer is helpful. Mind you, PDO is not the only thing in PHP that supports prepared statements, or am I wrong? For example, doesn't mysqli also support them? Supervillin posted:Could always write a sql($query, $arrParameters) or sql($query, ...) style wrapper for PDO to make it procedural-friendly. You'd have to touch that icky OOP code once but only once. Then the answer would be "absolutely, there is a way to use prepared statements that isn't long-winded." This is also an idea I might consider. Please don't think I have some kind of dark hatred of OO approaches; I just haven't seen anything I want to do with my web application that makes me think "guess using some objects belonging to a custom class would make my life a lot easier right now, better go back to learning basic OOP". As it stands, I understand intuitively how just about everything I've written for my application works, which surely is helpful from an effectiveness standpoint. I probably started out too defensive in this discussion, which doesn't help. Now the discussion has probably gone too far from the original purpose of this thread to answer "questions that don't need their own thread", so I suggest that the topic be dropped.
|
# ? Sep 25, 2009 12:52 |
Hammerite posted:Please don't think I have some kind of dark hatred of OO approaches; I just haven't seen anything I want to do with my web application that makes me think "guess using some objects belonging to a custom class would make my life a lot easier right now, better go back to learning basic OOP". Believe me, I understand. All I'm saying is that you will be rewriting the entire thing in 6 months when you go back to try to put in new features.
|
|
# ? Sep 25, 2009 18:33 |
|
v1nce posted:As far as I'm aware you can't do multiple updates in a single query (at least where the values are unique to the item being updated) so the query and loop you've got right there is about as efficient as you're going to get for this task. If you're using the MDB2 layer you can use the executeMultiple() method to run a query several times for each row of an array. Don't know if vanilla PDO has anything similar.
|
# ? Sep 25, 2009 18:50 |
|
duz posted:If you're using the MDB2 layer you can use the executeMultiple() method to run a query several times for each row of an array. Don't know if vanilla PDO has anything similar. That isn't any more efficient though, all its doing is looping through the array and running a single update statement for each row, just like he is doing in his loop. PDO doesn't have it, but it can be added by extending the class in a few lines of code as was shown previously.
|
# ? Sep 25, 2009 19:02 |
|
I am in the middle of rewriting some of my SQL queries and scripts in preparation to correct the poor design of my database (when I designed it I did my best to make sure it was a sensible schema, but inevitably made some poor choices as I'd never designed a database before). It occurred to me that it might be a sound idea to carry out certain common SELECT queries using a stored procedure. So I went to the MySQL website and read up again on how to do stored procedures. The stuff there suggested you can do this, but didn't appear to say how. Then I twigged that you just put the SELECT statement in as the body of the procedure, and do nothing else. As in "BEGIN / SELECT blah / END". (This might seem obvious but it initially wasn't to me.) So I tested this and it worked. So now we get to the bit I don't understand. The obvious thing that occurs to you after you make the leap to "just give the SELECT command as the body of the procedure" is: what if I issue two SELECT queries in the body of the procedure? Does it do both and present you with some kind of queue of result sets? I redefined the query to do two different SELECTs (they were both just SELECT * FROM tablename, where tablename in each case is a table with only a handful of rows and columns that happens to exist in my database). The page I typically use to do queries just executes them using mysqli_query() (provided you enter a correct user name and password to the database, of course). So I used it to CALL my procedure and it came back with the result set I would have expected to see had I run the first of my two queries. I reasoned that after the query was run, the script must have had the second result set "stored somewhere". I'd heard of the mysqli_multi_query() function, although I'd not used it as I've never had a reason to and understood it to be vulnerable to worse types of injection attacks than mysqli_query (if inadvertently used in an insecure fashion). So I went to the online PHP manual to see how mysqli_multi_query() is used. There are several companion functions that you're meant to use in order to get multiple result sets after doing a multi query. I succeeded in getting a TRUE response from mysqli_more_results() (so suggesting that there were more result sets), but couldn't work out how to get these result sets into a mysqli resource variable (whatever it's called). One thing that puzzles me is that the help pages for these companion functions all seem to assume that the only way you'll get multiple result sets is by using mysqli_multi_query() - i.e. that you'll never get that from mysqli_query(). I changed the command in my script used to send the CALL query to mysqli_multi_query(), but still couldn't get it to work. So I gave up at this point, although I'm still curious. If I run a stored procedure that issues multiple SELECT queries, does it return multiple result sets? If so, is there a mechanism in the MySQLi extension for getting hold of the 2nd and later result sets? Do you need to use mysqli_multi_query()? This post was quite long but I'm wondering now how this might work. I fully expect it to get no replies to be honest as it's a fairly esoteric question.
|
# ? Sep 25, 2009 21:26 |
|
PDO issue:php:<? $ids = array( 1, 2 ); for( $i = 0; $i < count( $ids ); $i++ ) { $id_params[] = ":id".$i; } $id_params = implode( ",", $id_params ); $sth = $db->prepare( " SELECT id, n, cb, SEC_TO_TIME(tl) AS tl, cp, bv FROM auctions WHERE id IN( " . $id_params . " ) AND a = 1 LIMIT 1" ); for( $i = 0; $i < count( $ids ); $i++ ) { $sth->bindParam( ":id" . $i, $ids[ $i ] ); } $e = $sth->execute(); print_r( $sth->fetchAll( PDO::FETCH_ASSOC )); ?> Edit: Oh christ, I had a LIMIT 1 for no reason. Well that's a waste of half an hour. Rat Supremacy fucked around with this message at 22:28 on Sep 26, 2009 |
# ? Sep 26, 2009 22:11 |
|
Let's pretend I've been writing PHP for a decade now. Let's also pretend that almost none of it has been OOP. Let's then pretend that I want to learn OOP. Is there a great tutorial/book/etc that will point me in the right path? I can use PEAR classes and poo poo with no problems.. I just want to write my own
|
# ? Sep 28, 2009 17:48 |
|
karma_coma posted:Let's pretend I've been writing PHP for a decade now. Let's also pretend that almost none of it has been OOP. Let's then pretend that I want to learn OOP. Is there a great tutorial/book/etc that will point me in the right path? If you want to learn OOP, PHP is not the best language to learn it in. I've messed around with Ruby a little and it seems to be a nice language with a better take on OOP. In PHP, it's more like there's a set of OO features rather than it being an OO language from the ground up. Once you understand OOP, learning how to do it in PHP won't be a problem.
|
# ? Sep 28, 2009 17:59 |
|
rt4 posted:If you want to learn OOP, PHP is not the best language to learn it in. I've messed around with Ruby a little and it seems to be a nice language with a better take on OOP. In PHP, it's more like there's a set of OO features rather than it being an OO language from the ground up. Java or C# wouldn't be a bad choice either. I'm not particularly a fan of either (Java specifically), but both are strict OOP and would teach you the concepts. If I understand Ruby correctly (and I'm a Python guy myself), it's very loose OOP.
|
# ? Sep 28, 2009 18:36 |
|
rt4 posted:If you want to learn OOP, PHP is not the best language to learn it in. I've messed around with Ruby a little and it seems to be a nice language with a better take on OOP. In PHP, it's more like there's a set of OO features rather than it being an OO language from the ground up. The only problem is that I know PHP pretty well. The procedural part of it, anyways. I want to stick with PHP because it's so widely available & there are tons of jobs for PHP programmers. Not so much for Ruby guys .. in my area at least.
|
# ? Sep 28, 2009 20:24 |
karma_coma posted:The only problem is that I know PHP pretty well. The procedural part of it, anyways. I want to stick with PHP because it's so widely available & there are tons of jobs for PHP programmers. Not so much for Ruby guys .. in my area at least. I don't see any reason to need to switch languages just to learn about OOP as others have suggested. What in particular do you find challenging about dealing with objects? How is your code currently organized?
|
|
# ? Sep 28, 2009 21:28 |
|
fletcher posted:I don't see any reason to need to switch languages just to learn about OOP as others have suggested. What in particular do you find challenging about dealing with objects? How is your code currently organized? mysql.inc.php data.inc.php serial_generate.inc.php auth.inc.php Basically all my functions are in different includes files. So, let's say I have a function that generates a serial number... instead of generate_new_serial($link, etc, etc, etc) I would rather... code:
I've heard good things about Ruby ... but I like PHP soooo much. Maybe I should be shot?
|
# ? Sep 28, 2009 21:49 |
|
I am getting annoyed with charsets. I've been working on an email archiver, but it seems like there are more encodings than there are email clients. So far I've got a bunch of heuristics about uppercasing, making "utf8" into "UTF-8" etc., falling back to whatever mb_detect_encoding says and then iconv, but it's still missing a lot and/or getting it wrong. Here's a link to a log. Anyone out there have experience with this sort of thing? Some sort of PEAR module maybe?
|
# ? Sep 29, 2009 05:48 |
|
FeloniousDrunk posted:Here's a link to a log. How can you mess up gb2312? iconv has oodles of aliases already setup for each encoding, e.g. utf8, UTF8, UTF-8, etc.
|
# ? Sep 29, 2009 06:05 |
|
MrMoo posted:How can you mess up gb2312? iconv has oodles of aliases already setup for each encoding, e.g. utf8, UTF8, UTF-8, etc. Are you suggesting using iconv before mbstring? Because I could do that too; mbstring just seemed more 'mature' at first glance, mostly because I could actually get a list of its supported encodings. ... unless you're joking about gb2312.
|
# ? Sep 29, 2009 06:13 |
|
FeloniousDrunk posted:Are you suggesting using iconv before mbstring? Because I could do that too; mbstring just seemed more 'mature' at first glance, mostly because I could actually get a list of its supported encodings. Actually I'd try recode first considering the source material. The other modules are more strict on character set names. Run recode -l on the command line for supported sets and aliases.
|
# ? Sep 29, 2009 06:22 |
|
MrMoo posted:Actually I'd try recode first considering the source material. The other modules are more strict on character set names. PHP is like a series of tunnels, endlessly twisting. Thanks, I'll definitely be giving that a try tomorrow. E: Any tips on getting the PHP extension installed on RHEL5? Not seeing it in any of my current repos. E2: Scratch that, had PHP excluded from yum (5.3 breaks every drat thing). Tad Naff fucked around with this message at 06:44 on Sep 29, 2009 |
# ? Sep 29, 2009 06:29 |
|
karma_coma posted:I can use objects okay but I'm clueless on how to make my own. This is not good. I don't meant to sound condescending, but that phrasing makes it sound like you havn't really read any tutorials on PHP OOP to begin with, so in case of that here are a couple I pulled off google with the search term "php, oop, tutorial"; http://us.php.net/manual/en/language.oop5.basic.php http://www.phpdeveloper.org/news/5719 http://net.tutsplus.com/tutorials/php/oop-in-php/ If thats not what you meant, can you clarify what aspects you're having trouble understanding? It would suprise me if you don't get how to create a class, so maybe you mean how exactly to apply the use of a class to your current situation? In the example you gave its reasonable to say that a class with a multitude of methods doesn't always suit some situations and its a matter of knowing the best tool for the job. For instance, your situation seems to call for a very simple class called "serial" which only has the one public method (for now) which creates an SHA1 hash, like this: php:<? /** * Serial generation class */ class Serial { /** * GenerateSerial * Generates a serial key based off the input string * * @param string Input data to base the serial off */ public function generateSerial( $input ) { return sha1($input); } } $myClass = new Serial(); $x = $myClass->GenerateSerial("woop woop"); // $x == "abcdefghijklmnopqrstuvwx" ?> php:<? $x = Serial::generateSerial("woop woop"); ?> v1nce fucked around with this message at 09:53 on Sep 29, 2009 |
# ? Sep 29, 2009 09:51 |
|
When I sit down to create some new classes, I usually start out on paper and write down some requirements. Lets say you need to create a new address book, your requirements might be - Need to add contacts - Need to be able to remove contacts - A contact needs to have a name, birthdate (optional), company name (optional) - A contact can have multiple phone numbers and addresses - Need to be able to edit a person and save changes - Each contact should have a unique id - Need to be able to search contacts and get results as an array There would probably be more, but I am stopping there. Then I write out how I would like to use my class, this will also allow me to see where I might need to expand my requirements code:
Unit testing isn't a bad idea either. If you wanted to do unit tests, the first thing would be to create your objects and have them do nothing, then write all your tests which should all fail. Then you will start adding code to your classes and running your tests until everything passes, adding more tests where necessary.
|
# ? Sep 29, 2009 14:07 |
|
v1nce posted:stuff Begby posted:more stuff Both of these posts helped me out a ton. On my way now.. thanks.
|
# ? Sep 29, 2009 14:48 |
|
N.Z.'s Champion posted:Sorry, I didn't know where else to ask but is there a open source PHP file drop utility that looks nice? It'd need to be multi-user too. Last try, I'm looking for something like dropbox to install on my own server.
|
# ? Sep 29, 2009 23:25 |
|
Google, man. "php file manager, user" http://extplorer.sourceforge.net/ http://www.gerd-tentler.de/tools/filemanager/ http://www.solitude.dk/filethingie/ In order of crapiness, best to worst, based entirely on screenshots.
|
# ? Sep 30, 2009 00:32 |
|
Tell me about unit testing please. My general method has been to write the entire class, throw up a test page, load it up, read the error, edit the PHP file, upload it, and hit F5, and repeat until it works.
|
# ? Sep 30, 2009 16:47 |
|
Golbez posted:Tell me about unit testing please. My general method has been to write the entire class, throw up a test page, load it up, read the error, edit the PHP file, upload it, and hit F5, and repeat until it works. Unit testing is a way where when you create classes, you write tests for every method to make sure the methods do what they are supposed to do and fail like they are supposed to (throw the right exceptions when given bad input or what not). Often I have more unit testing code than I do actual program code, but I have found my software to be a ton less buggy and easier to maintain. Unit testing also helps to make sure that each class can function by itself with as few dependencies as possible. It helps make sure your code is not an intertwined rats nest of poo poo with dependencies all over. You need a testing suite. For PHP PhpUnit is pretty good. I use NUnit for C#. You can download Zend Framework for an example of unit tests. The source includes all the tests which you can run and see how they did the testing. Personally I don't like Zend Framework, however under the hood it is a good example of properly written and tested code with very few dependencies. Basically you write tests for all of your classes and methods. Then every time you make a change you add tests for your new change, then run all of your tests for all of your code after you are done making changes. This makes sure that your changes don't break anything by introducing new bugs. When you find a bug, the first thing you do is write a new unit test to catch said bug at the lowest level possible and make sure the test fails. Then you make changes and run your new test until it passes. This keeps the bug from reoccurring in the future due to your new test. To have this be most effective all logic possible should be in classes and objects. Then you would have some sort of presentation layer that uses your tested objects to retrieve and display data. There is a lot more detailed info out there on the web on how to unit testing and a lot of books.
|
# ? Sep 30, 2009 17:17 |
|
Why is this code returning "Hello missing"? It should find Hello in the array and thus not return anything.php:<? $aa = 0; do { $bb = 0; do { $cc = 0; do { $SystemArray[$aa][$bb][$cc]='xx'; $cc++; } while ($cc < 3); $bb++; } while ($bb < 3); $aa++; } while ($aa < 3); $SystemArray[0][1][2]='Hello'; $str = "Hello"; if (array_search($str, $SystemArray)=== false) echo "\n$str missing\n"; ?>
|
# ? Oct 1, 2009 00:06 |
|
What does a var_dump($SystemArray) show?
|
# ? Oct 1, 2009 00:23 |
Agrikk posted:Why is this code returning "Hello missing"? It should find Hello in the array and thus not return anything. First of all, use for loops. Second of all, $SystemArray only contains 0, 1, 2. It does not contain "Hello". The array $SystemArray[0][1] does contain "Hello" though.
|
|
# ? Oct 1, 2009 00:24 |
|
fletcher posted:First of all, use for loops. Second of all, $SystemArray only contains 0, 1, 2. It does not contain "Hello". The array $SystemArray[0][1] does contain "Hello" though. if I do a print_r($SystemArray) I get: code:
|
# ? Oct 1, 2009 18:52 |
|
Golbez posted:What does a var_dump($SystemArray) show? code:
|
# ? Oct 1, 2009 19:02 |
|
Agrikk posted:Which is expected. "Hello" is in there. What's the best way to verify that is actually is in there? I think what fletcher is saying is, no, the array doesn't contain "Hello". It contains an array that contains an array that contains "Hello". array_search returns the key; what would the key in this case be? It's key 0 of the array located in key 1 of the array located in key 1. There's no way for it to return a valid key. A recursive foreach loop may be what you need. Though I'd be surprised that there's no nested array search function in PHP. in_array may help more, since that doesn't return a key, just a boolean.
|
# ? Oct 1, 2009 19:13 |
|
|
# ? May 16, 2024 21:01 |
Agrikk posted:if I do a print_r($SystemArray) I get: array_search is not recursive, it will only search the first level of $SystemArray. "Hello" is in the 3rd level.
|
|
# ? Oct 1, 2009 19:14 |