Jump to content

zenlord

Members
  • Posts

    54
  • Joined

  • Last visited

    Never

Everything posted by zenlord

  1. I don't use MySQL, so I don't know if it is correct function. Just insert the ID's in an array and pick one element out of the array, not with rand(), but with array_rand()...
  2. That is a very basic login-form, so it probably is not safe enough. But a few pointers: stick to 1 page, index.php, in which you make 2 divisions (pseudo-code follows): if isset $_COOKIE['senha']: -> user is logged in and gets to see the page for logged users else -> visitor gets to see login form Next: read up on sessions, cookies and use a fwe of the examples out of the php.net-examples and user contributions... Vincent
  3. Indeed, you're doing it wrong. In a select-statement, after 'WHERE', a column-name has to be entered, followed by a '=' and a condition (constant or variable). I'm guessing 'rownum' is not a valid columnname in your table. If you want to display a random row out of a table, you're better of using the unique index of your table (f.e. 'id'). Use a query to gather all indexes in an array, pick 1 element ($chosen_element) of the array and then query the table with a 'WHERE id = $chosen_element'. Vincent
  4. Since I won't be able to work on my app until tomorrow evening, but I couldn't refrain myself from looking up some stuff, I'm posting this for my own convenience (and maybe someone can tell if this is a good idea or not before I start it). I found info about PDO, and it looks like it's the way to go. I even found a PDO-session-class (http://www.walterebert.com/code/session-pdo.html), which is something I tried to build myself (Postgresql session handler), but I failed miserably. The PDO-session-class instantiates a persistent connection to the dbase, in a way I should be able to re-use the connection inside every class until the session is ended. The PDO-docs on php.net describe 'prepared statements', something I had never heard about, in a way that it looks very interesting to use myself, since my app is merely a frontend to an extensive dbase, and uses a lot of dbase-transactions. To do these kind of changes, I will work on a copy of the code and dbase and test it extensively before moving to this class exclusively. I'm open to any opinions, but feel good about the info the answers in this thread have lead me to! THX! Vincent
  5. First off, I would like to say that I'm very cautious in 'converting' / translating the app to OOP: *everytime* I add new functionality, it is tested and if it doesn't work, I can easily go back to the working code. It is not copy/paste-job, except for a small amount of functions - I am using this conversion to make the best of my app, because most of the procedural code is 3 to 5 years old and I guess I have learned some things in the meanwhile Well, this is how I'm doing it now, and how it is working: $Us = new User; $userid = $Us->get_detail_by_uname( $_SESSION["username"], "proius_id" ); $Do4 = new Dossier; if ( $Do4->category( $fileNr ) === 1 ) { $Pr2 = new Prestatie; $Pr2->mk_new_pc( $open, "Aanmaak dossier", 1, $userid, $fileNr, 6); } $Pr3 = new Prestatie; $Pr3->mk_new_ph( $open, "Aanmaak dossier", 10, $userid, $fileNr, 0); unset ($Do4); unset ($Pr2); unset ($Pr3); unset ($Us); In all the examples I read about, it was possible to do a very simple: $U = new User; $Ua = $U->get_detail('a'); $Ub = $U->get_detail('b'); $D = new Dossier; $D->set_detail($Ua, $Ub); (for example). If I combine two classes in a function/method like this, I get errors that the dbase-connection is not a valid result resource, probably because I use $_conn in every class as the property to contain the dbase-link. Since I started combining classes, I have needed to instantiate new objects for every new method (in the above example I would have to instantiate a new object $U1 for the method $U1->get_detail('b'), or it wouldn't work. The unsetting of the variables is also something I was not doing until I was having problems. 2 options: * or, I'm doing nothing wrong and this is just how it's done, * or, I did read the books correctly, but I don't know how to make certain design choices and suffer from the consequences. Anyhow: I will read up on PDO - I know I have it installed on my server because davical needs it for my caldav server. Thank you for your concerns about me doing a lot of damage to my (working) app. I will report back tomorrow evening if PDO has helped me out or not. Vincent
  6. Look to the HTML of the form. It should be: <form action="" method=""> If 'method' is not defined, default it is set to 'get', and then you have to collect the variable with $_GET['id']. If the method is set to 'post', then you have to fetch the variable with *_POST['id']. You could also choose to fetch the variable with $_REQUEST['id'] - this predefined variable holds the content of $_POST, $_GET and $_COOKIE.
  7. You're right that that could make it easier to debug, but I don't think those are the problem, since they only suppress error output and leave it to my error handling (which is in place, albeit very rudimentary). I will try it and see how it goes. (ah, and I forgot to mention: the reason why I'm not trying the solutions I'm thinking of instead of asking here is that I really would like to be sure that I'm doing 'The Right Thing' - I want to add lots of functionality to this app, and starting of on the wrong foot is a recipe for lots of headaches...) V
  8. Hi, I have a working PHP app with limited functionality that I use daily. Some months ago I wanted to add functionality, but soon came to a conclusion I should convert my procedural code to OO PHP. So I read some books by David Powers and Matt Zandstra (the latter was sometimes a little bit too complex for me) and started converting. I now have converted some parts of my app and created new functionality and everything was working perfectly, until I started to use methods from class A inside methods of class B. I started getting irrational errors: sometimes it worked, sometimes it returned an error. I think I have narrowed it down to the use of __construct() and __destruct() in all of my classes, and I'm wondering what is the (better/best) solution. My classes at the moment are all built the same way: class A { function __construct() { $this->_conn = @ pg_connect( "host=localhost dbname=* user=* password=*" ); } function get_detail() { $this->_res = @ pg_query($this->_conn, "SELECT detail FROM table WHERE ph_id='$id'" ); } function __destruct() { @ pg_free_result( $this->_res ); @ pg_close( $this->_conn );} } I thought I was doing the correct thing by instead of repeating the setting of $this->_conn inside every method, setting that variable upon instantiating the object. But now, I have to make a $this->_conn2 and so on to circumvent the irrational errors (always the same: '5 is not a valid result resource', where '5' should be the '$this->_conn'. Is this a bad practice, or am I doing something else wrong? I also tried 'unset( $this->_conn )' after calling the method, but that didn't seem to work. I'm thinking of looking for a generic PostgreSQL-class so that I can establish the connection inside every method itself, rather than in the __construct() - do you think that would solve my problem? This might be an easy question for someone who is used to OO PHP, so I'm hoping to get an answer which helps me understand the problem. THX for all the help I can get!
  9. You forgot a '.' in your definition of $qry_str. Try '$qry_str.=' instead of '$qry_str=' The '.' adds the new content to the existing $qry_str. Without the '.' you're overwriting the content of $qry_str. Zl.
  10. I haven't tested your code, but if you want to generate .docx or .odt-files from PHP and insert all kinds of variables into a document template, I can very much vouch for 'opentbs', a plugin for the 'TinyButStrong'-templating engine. It is very easy to use: you make a template in f.e. openoffice, in which you place some fields and then you submit some variables to the opentbs-object to generate a new .docx or .odt. Don't go reinventing the wheel Zl.
  11. Did you try to base64-encode the file before adding it as an attachment? http://be.php.net/manual/en/function.base64-encode.php
  12. The code I posted above still doesn't work - just wanted to add that my 'session_set_save_handler' was originally put in a constructor for the class, but I also tried it like this because the php.net-manual stated that the open() and close() work as a constructor and destructor to the class. Reading what I posted above makes no sense: the session_set_save_handler should be outside the session-functions, maybe even outside the class. Zl.
  13. Hi, You probably know where I am right now: after reading and coding for about an hour, you are happy with the solution you've come up with and that is working 'so-and-so', and then you do some more reading and coding only to find that suddenly everything stops working. At this moment, my db-session-class doesn't do *zilch* anymore. Could someone please look through the code and point me at something probably to stupid to mention? <?php class Session { /* Required this Postgresql table: * CREATE TABLE session ( sessionid CHAR(32) NOT NULL, expiration INT NOT NULL, value TEXT NOT NULL, CONSTRAINT session_pk PRIMARY KEY(sessionid) ); */ public $sess_id; public $sess_data; public $sess_name; public $sess_life; public $sess_exp; private $_conn; /* open() * Opens a persistent server connection and selects the database. */ function open($sess_path, $sess_name) { if (! session_set_save_handler( array(&$this,'open'), array(&$this,'close'), array(&$this,'read'), array(&$this,'write'), array(&$this,'destroy'), array(&$this,'garbage_collect') )) { die('session_set_save_handler() failed'); } $this->sess_life = 18000; $this->_conn = @ pg_connect("host=localhost dbname=<snip> user=<snip> password=<snip>"); } // end function open() /* close() * Doesn't actually do anything since the server connection is * persistent. Keep in mind that although this function * doesn't do anything in this particular implementation, it * must nonetheless be defined. */ function close() { // Allegedly needed to write everything to db before closing // the object. session_write_close(); // On Debian and Ubuntu, garbage collection is not immediately // handled, so we call it here ourselves, just to make sure. $this->garbage_collect($this->sess_life); //pg_close($this->_conn); return 1; } // end function close() /* read() * Reads the session data from the database */ function read($sess_id) { $query = "SELECT value FROM session WHERE sessionid ='$sess_id' AND expiration > " . time(); $result = pg_query($this->_conn, $query); if (pg_num_rows($result)) { $row = pg_fetch_assoc($result); $value = $row['value']; return $value; } else { return ""; } } // end function select() /* write() * This function writes the session data to the database. * If that sessionid already exists, then the existing data will be updated. */ function write($sess_id, $sess_data) { $expiration = time() + $this->sess_life; $query = "INSERT INTO session VALUES('$sess_id', $expiration, '$sess_data')"; $result = pg_query($this->_conn, $query); if (! $result) { $query = "UPDATE session SET expiration = $expiration, value = '$sess_data' WHERE sessionid = '$sess_id' AND expiration >". time(); $result = pg_query($this->_conn, $query); } } // end function write() /* destroy() * Deletes all session information having input sessionid (only one row) */ function destroy($sess_id) { $query = "DELETE FROM session WHERE sessionid = '$sess_id'"; $result = pg_query($this->_conn, $query); } // end function destroy() /* garbage_collect() * Deletes all sessions that have expired. */ function garbage_collect($lifetime) { $lifetime = $this->sess_life; $old = time() - $lifetime; $query = "DELETE FROM session WHERE expiration < $old"; $result = pg_query($this->_conn, $query); return pg_affected_rows($result); } // end function garbage_collect() } ?> (I have been tinkering with that piece of code for more than 2 hours now, and I don't get any errors. Where at first, I got a row in my db (only the sessionid and expiration-columns were filled, no 'value' whatsoever...), now I don't get anything and NO errors... Anyway: This is how I initialize: require_once 'classes/cls_session.php'; $S = new Session; session_start(); session_regenerate_id(true); THX for any insights!
  14. zenlord

    Invoices

    THX for your reply. Since I was not able to get the money-type working (and since I learned it is deprecated anyway), I have switched to numeric(9,2). All I need it for is to store exact amounts - no calculations other than adding and subtracting need to be made, so I don't expect much trouble.
  15. 1. I kinda figured it out - see below // $billamount needs to be prepared for various situations: // 1. if currency symbols are inputted $billamount = trim(str_replace(array("$","€"),"",$_POST['bedrag'])); // 2. if grouping characters (',' or '.') are used in the number to group thousands $billamount = preg_replace('/(\.|\,)+([0-9][0-9][0-9])/', '$2', $billamount); // 3. if the decimal separator is a ',' $billamount = str_replace(",",".",$billamount); // 4. if no decimals are inputted //(1) $billamount = number_format($billamount,2,".",""); 2. I'm by far not a PHP guru - I just need it to work. The above method is not ideal, it would have been far more easy if the 'money'-data type worked for me. The function 'number_format()' works in the above configuration and without exceptions , even when the inputted number is less than zero and approximating 0 (which has proven to be a problem with the 'number_format()'-function according to the comments on the php.net-website). I want to thank you for reading my posts and taking the time to reply to it, but I think I have found a solution to my initial problem... EDIT: (1) After thinking a second time about the function, I realised that I don't need the 'number_format()'-function anymore, that's why I commented it out in the above php-block
  16. Only replying to give other people that encounter the same after this date some more info: 1. In my previous post I described a problem that I still have: in my locale, currencies are written as '€ 1.000,00', as as opposed to USD '$ 1,000.00'. If I trust my users never to input an amount with '.' as a grouping symbol, then the above function works. As I have no intentions of trusting *any* user, I have written the following regular expression to single out cases that will pose problems: if (preg_match('/\.[0-9][0-9][0-9]/',$billamount)){echo "troubles";} This works, but replacing the '.' with the following has not worked for me (but I will not give up on this one soon): preg_replace('/\.([0-9][0-9][0-9])/', '$1', $billamount) 2. In my previous post I talked about 'currency_format()' where this should of course be 'money_format()'. I briefly experimented with this function in conjunction with the 'money'-data type, but I encountered the same problem, i.e. a function that errors out without logging why. So I gave up on that one and returned to my solution sub 1.
  17. I switched the data type from 'money' to 'numeric(9,2)' and got something that works 90% of the time: For input I now use $billamount = trim(str_replace(array("$","€"),"",$_POST['bedrag'])); $billamount = number_format($billamount,2,".",""); For output, I use SELECT dos_nr, category, date, TO_CHAR(amount,\'L FM9G999G990D00\') AS amount2, status This works, unless my users input a number with '.' as a decimal separator. I'm looking into a regular expression to remove those, but have not found it yet. Once I get that one, my current problem is ***SOLVED*** - although it has nothing to do with the data type 'money' anymore... Vincent PS: stumbled across number_format() and also found out that there is a currency_format(), which might have been of use when using the 'money'-data type...
  18. Well, I tried all sorts of error levels, but I have not succeeded in generating an error regarding this pg_insert. I would like to upgrade my server, but the upgrade involves a lot of packages and I don't want to risk to break this server. The server uses PostgreSQL 8.3.8 and php 5.2.6 - fairly recent, but so is the 'money'-datatype in postgreSQL and the pg_insert() is experimental as per the php online documentation... So I changed the data type from 'money' to 'numeric(9,2)' as pointed out in another recent thread in this subforum, and now I can insert my rows like I'd want to. I have only 1 small problem: numeric has '.' as decimal separator. In our locale we use ','. changing this with regular expressions is not that hard, but I wonder if I can change a setting to make postgreSQL use ',' as a decimal separator. Anyone? THX!
  19. zenlord

    Invoices

    I have a question regarding the data type for 'cost'. You (btherl) said it to be numeric(9,2), but there is a data type 'money' available , as I found out this weekend. Using it has proven to be a challenge (that has not been met at this moment), but I wonder if it has advantages over your approach? Vincent
  20. THX for pointing me in the direction of the error-functions. I tried several: last_error, last_notice, result_error. Neither returned an error or any message whatsoever. I get the feeling that the single quotes solved the original problem, because the original problem could be seen in the logs. I've checked my postgresql config and the error level is at its default value: 'notice'. I'll try to lower that and see what it returns. Vincent
  21. That's interesting, because I tried it, it still doesn't work (I get the die()-statement), but there are no more errors in the main.log... I also tried $billamount = (string) "'$billamount'::text::money"; Because I have succeeded by entering the SQL-statement inside phppgadmin directly. Still no luck with this function, though... THX for your help!
  22. Yes, I'm sorry: I forgot to add the pg_insert(), so here you go: pg_insert(CNX_DOS,"dossiers_bills", $fields) or die("billNieuw: Nieuwe nota aanmaken mislukt"); pg_close(CNX_DOS); I tried adding single quotes, double quotes and casting as another type (string, object), but nothing worked. It has something to do with escaping, but I thought pg_insert did that automatically? Anyways - this is the error postgresql gives me when I try to insert a money value of 445,25 into my dbase: STATEMENT: INSERT INTO dossiers_bills (date,user_id,dos_nr,amount,category) VALUES ('2010-04-24','1','1031632',445,25::text::money,'seek'); Everything else is quoted automatically by pg_insert() - only the $billamount not. Out of the answers I'm getting, I get the feeling I've made a very basic error and I'm still overlooking it. AAARGH! THX already for your replies! Vincent
  23. Hi, I'm trying to use the money type with PHP and PostgreSQL. The following code works, but I cannot set decimals: a comma is treated as a list seperator, throwing an error there are more variables than there are columns and a . is neglected. $billdate = $_POST['date']; $billuser = $_POST['user']; $billfile = $_POST['dossier']; $billamount = (string) $_POST['bedrag']; $billamount = (string) $billamount."::text::money"; $billcat = $_POST['categorie']; // Insert nieuwe nota in dbase $fields = array('date' => $billdate, 'user_id' => $billuser, 'dos_nr' => $billfile, 'amount' => $billamount, 'category' => $billcat); ANyone? THX!
  24. Hmmm, added the pg_last_error(), ran it again and it worked. Don't know where I messed up yesterday. THX for your answer and making me try it again
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.