Jump to content

Andy123

Members
  • Posts

    134
  • Joined

  • Last visited

Everything posted by Andy123

  1. Hello and sorry for the late reply. Thank you for your post. I couldn't get your regex to work, at least not on regexpal.com. I wrote a very simple regex myself that will match almost anything. <!DOCTYPE\s.*>
  2. Hello, I have a HTML page for which I want to extract the doctype. I tried the following: $doc = new DOMDocument(); $doc->loadHTML($html); $doctype = $doc->doctype->name; However, the DOMDocument class seems to be using a default doctype if no doctype is available in the loaded HTML. I have looked around and didn't find any other options in this class. Are there any better alternatives than having to write a regular expression? My regex skills are quite rusty, so I prefer an approach that does not rely on these. Or, if anyone can help me out with the regex, that would be fine too. Thanks in advance.
  3. Yes, that is the way I have always done it as well. I recently started going about it in a new way because the callback handlers you are using in your example (at least the success one) are deprecated as of jQuery 1.8 (scroll about half way down the page). Thanks again for the solution. I was going to mark the thread as solved, by the way, but I just wanted to give you another shot.
  4. Hello haku, Thank you very much for your answer. It turned out that I was lucky; your solution works! I do find it a bit strange, because the HTML I get back is perfectly valid HTML. I did a console.log, and it shows the markup in the beginning of my initial post (in the error message). Before I wrote here, I did try the $.html function, but that did not work either. The encoding of my document is also correct. I am quite confused as to why I got this error in the first place, so I will paste in some more code. If you can identify the problem please let me know. Otherwise thank you very much for your help! // Inside a click event $.ajax({ type: 'POST', url: URL_SEND_MESSAGE, data: ($(form).serialize() + '&include_markup=true'), dataType: 'json' }).done(function(data, textStatus, xhr) { // Created if (xhr.status == 201) { //$(data.markup).hide().appendTo('#messageContainer').fadeIn(500); // This doesn't work $("<div/>").html(data.markup).contents().hide().appendTo('#messageContainer').fadeIn(500); // This works } }).fail(function(xhr) { /* ... */ });
  5. Hey guys, I am sending an AJAX request with jQuery where I get JSON back. The JSON includes some HTML markup in UTF-8. For some reason, I get the following error when I try to create a DOM element with it (it used to work!): Uncaught Error: Syntax error, unrecognized expression: <div class="message self"> <strong>Andy123 wrote:</strong> <br /><br /> Profile link: /profile/45873/Andy123 <br /><br /> fsafawfwf222222222</div> Here is the code that triggers the error: $(data.markup).hide().appendTo('#messageContainer').fadeIn(500); If I put the same markup into a variable (or overwrite data.markup), without transferring over the network, it works as intended. Request headers: Accept: application/json, text/javascript, */*; q=0.01 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Response headers: Content-Type: application/json; charset=utf-8 I am not that good with charset and things, but to me that looks OK. Here is the JSON that is returned from the web server (PHP): {"markup":"\n\u003Cdiv class=\u0022message self\u0022\u003E\n \u003Cstrong\u003EAndy123 wrote:\u003C\/strong\u003E\n\n \u003Cbr \/\u003E\u003Cbr \/\u003E\n\n Profile link:\n\n \/profile\/45873\/Andy123\n \u003Cbr \/\u003E\u003Cbr \/\u003E\n\n fsafawfwf222222222\u003C\/div\u003E"} I suspect that it has something to do with encoding, hence why I pasted the above. Any idea what is wrong? Thanks!
  6. If you want to change the available options in select #2 when you select something in select #1, then what you are looking for is Javascript and not PHP. If you want to filter from the same options in select #2 for every option in select #1 (that is, the options to be displayed in select #2 are always a subset of all possible options in select #2), then pure Javascript would do. If you just have few different options in select #2, then you could hard code this in HTML/Javascript. If you need more options and flexibility, then you could bring PHP into the picture by firing AJAX requests to your web server when a user chooses an option in select #1. You could always cache this in Javascript if you think there is a chance that people will be making many changes (although this is overkill in most situations).
  7. Everything you need to know is in the manual - particularly in the "PDO" and "PDOStatement" sections. Otherwise, a quick Google search should give you what you need. I quickly found this one and it looks good. I didn't read it, though.
  8. ^ What he said, although I think he simply has 20 rows in his table but wants to display them all. If that is the case, simply remove the LIMIT clause.
  9. As you said, polling is not a good way to go if you start to get a bit of traffic. Web sockets would be your best bet I believe. It is true that there is a challenge with the browser support, but wouldn't it be acceptable to give the user a message that their browser is updated if it doesn't support it? There are surely other methods of doing this, some of which kicken described, but many of them are quite challenging to implement. Reading your post, I have the impression that you don't want to go for something highly complicated. I'd say that web sockets is the way to go. People with old browsers can simply choose to upgrade or to not use the chat. Supporting old browser versions is something that is going away very fast, so I would just forget about it but make sure that you present the users with a user friendly message (feature checking).
  10. What Christian F. said. I wrote some quick code below to get you started. Note that you will probably want to validate further as I am only checking to see if the submitted values are empty. But as I said, hopefully it will get you started and give you an idea on how to proceed. $Name = trim(stripslashes($_POST['Name'])); $Phone = trim(stripslashes($_POST['Phone'])); $Time = trim(stripslashes($_POST['Time'])); $errors = array(); if (empty($Name)) { $errors[] = 'You must enter a name'; } if (empty($Phone)) { $errors[] = 'You must enter a phone number'; } if (empty($Time)) { $errors[] = 'You must enter a time'; } // Done validating if (empty($errors)) { // No errors; proceed to send e-mail $success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>"); // redirect to success page if ($success){ print "<meta http-equiv=\"refresh\" content=\"0;URL=thank_you.html\">"; } else{ print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">"; } } else { // Errors occured; loop through them and output echo '<ul>'; foreach ($errors as $error) { echo '<li>' . $error . '</li>'; } echo '</ul>'; }
  11. If I had a penny for every time someone asked about this error on this forums, I would be rich. I don't mean to be rude. The error message is actually very precise and helpful. mysql_fetch_array() is being called with a boolean value where a resource is expected. If you look at the documentation for mysql_query(), you will see that it returns FALSE on failure, which is a boolean. This value is stored in $result, which is then passed to mysql_fetch_array(). So, an error occurs with your SQL query. Perhaps you made a spelling mistake or perhaps the word "insert" is not allowed; I am actually not sure. Anyways, you can check the error like this: $result = mysql_query("SELECT id, stations, title, detail from insert") or die(mysql_error()); Also, please consider using MySQLi or PDO instead as the mysql_* extension is deprecated. I am merely name dropping here, so please take the time to read about these.
  12. Hello again. Zend Framework 2.1.0 and 2.0.7 have just been released and with it came a tool! Below is a quote from the releaselog:
  13. Congratulations! I have noticed a lot of great posts from you, so it seems very well deserved.
  14. Thank you for the heads up. Actually, I made a silly mistake in my previous post. What I really did was to concatenate instead of add. So the line in my previous post should have been something like this instead: $user_code = (int) (rand(1,9) . ($primary_key + 164) . rand(0,9)); Sorry for the confusion.
  15. Thanks for the ideas, guys. I ended up with a quite alternative approach where I use my primary key (which is obviously unique) to generate my user code. I manipulate it a bit to obscure the pattern, such that my user codes are both unique, but also less predictable. I think what I did was this (done in a stored procedure): $user_code = (rand(1,9) + ($primary_key + 164) + rand(0,9)); It may seem silly, but it makes it hard to figure out a pattern if you are not aware of the implementation. Surely this is not random, but I guess that's okay after all. Since the primary key is sequential, the middle part of the addition will always be a unique number and thus, I will not have collisions. At least that's what I think; if someone disagrees, please let me know.
  16. It is true that I could create a loop, but I need to generate this identifier during user registration. This means that I would have to probe the database to see if each generated identifier is available. Sure I could do this from within a stored procedure to save some time, but I would still have to execute a query. But I guess as long as I do not check the generated codes sequentially, it would be a decent solution. If I were to check it sequentially, the day when the first N combinations are taken, then I'd be looping and probing N times pointlessly. Do you mean something like this? $identifier = ''; $i = 0; while ($i < 7) { $identifier .= rand(0, 9); $i++; } $identifier = (int) $identifier; // Check identifier availability and do the above again if it is not available Surely it is unlikely that this would result in collisions for quite a long time, given that there are 10^7 possible combinations (correct?). The reason why I want a short identifier is mostly cosmetic; 5972857 looks better in an URL than dsah3y39gyags2dsaf2. Also, 7 characters gives me plenty of possible combinations if I am not mistaken, provided that there is a way that I can make use of them without too much trouble (i.e. handling collissions). I could go with my approach, but I just wanted to know if there was a better way so I did not have to handle collisions myself.
  17. I would like to generate a unique user ID per user which should be an integer and with a length of 7. I do not want to use a hashing algorithm since collisions are possible. Since I will be putting these IDs in my URLs, it would be great if they could be pretty integers. They will be stored in a column with a unique index, so they must be unique. I do not want the IDs to be predictable or sequential. I looked into uniqid(), which looked pretty useful except that it does not return an integer. Simply using time() seems pretty safe too, but it is too long. Each user will obviously have a unique username, so perhaps that could be used in generating the ID - perhaps along with the microtime? It would be simple to use uniqid() with the username as a prefix, but that will not give me an integer. Any ideas on how I can do this? Is it even possible, or do I need to use sequential numbers? Thanks.
  18. It is true that InnoDB supports spacial types (I am indeed using 5.6). I have successfully created a table with a spacial column and inserted data into it. Unfortunately, it still does not support spatial indexes.
  19. Hey guys, I am looking into using MySQL's Spatial Extensions. However, I noticed that spatial indexes are not available for InnoDB tables which I am using to implement foreign key constraints. Instead, it is available on MyISAM tables, which do not support foreign keys. I have a table with user profiles and have a foreign key to a "city" table on which I would like to have a spatial index. To have this index, I need to use MyISAM, but then I have to throw my foreign key out the window. I can get the same performance if I add an index on the "foreign" key on the profile table; I can then simply join with the primary key of the "city" table just as before. The only difference is that I do not have a foreign key. This means that I lose the relationship constraint and managing the integrity of my key is then up to me. If I am not careful, I could add a wrong value which would not match anything in the "city" table and therefore a join cannot be done. Updating the "city" table will also be more complicated because then I have to update all rows in my referencing table myself. However, this is not a big concern. So, to sum up, to use the spatial index, I need to use MyISAM and lose my foreign key. Is the optimal solution to index my join columns properly and handle the correctness of my "foreign key" myself? Does anyone have any other ideas (or thumbs up to my approach)? Thanks.
  20. I was thinking of this, but the code that was posted in the initial post was quite far away from working code, which led me to believe that I was dealing with someone relatively new to PHP and/or programming. I figured that bringing design patterns, DAL, DAO, etc. into this would confuse more than it would do good, so I decided to keep things simple. But thanks for the heads up. Definitely. I left a comment in the code about this to encourage Idzik to look up either of those.
  21. To insert, you could do like this: Add a new function to your class which will insert data into the database Either pass data to this function with parameters or use class fields (variables) and access these from within the function Write insert code within the function To get the latest 10 entries, you could do like this: Add a new function to your class which will fetch X entries (X could be a parameter) Write the SQL query to fetch the latest X entries; for instance using ORDER BY and LIMIT Either create a wrapper class for an entry and return an array of objects or return an array of key-value pairs, such as 'entry_id' => 123 Call this function where you want to show the entries Loop through the returned array (perhaps with foreach) and generate the HTML markup to show them - e.g. in a table Here is a bit of code to get you started: class Account { protected $id; protected $name; protected $email; public function __construct($id, $name, $email) { $this->id = $id; $this->name = $name; $this->email = $email; } public static function getLatestEntries($number_to_fetch) { $number_to_fetch = (int) $number_to_fetch; // Ensure it's a number $query = "SELECT * FROM Account ORDER BY date DESC LIMIT 0, " . $number_to_fetch; $result = mysql_query($query); // You should really use mysqli or PDO here! The mysql extension is deprecated $entries = array(); // Fill rows into $entries here return $entries; } public function insert() { // Prevent against SQL injection $id = mysql_real_escape_string($this->id); $name = mysql_real_escape_string($this->name); $email = mysql_real_escape_string($this->email); $query = "INSERT INTO Account VALUES ($id, $name, $email)"; $result = mysql_query($query); return (mysql_affected_rows($result) > 0); // True if successful and false otherwise } public function getId() { return $this->id; } public function setId($id) { $this->id = $id; } public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } public function getEmail() { return $this->email; } public function setEmail($email) { $this->email = $email; } } ?> <p>This is your HTML markup</p> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $account = new Account(-1, $_POST['account_name'], $_POST['account_email']); $result = $account->insert(); if ($result === true) { // Show latest entries $entries = Account::getLatestEntries(10); foreach ($entries as $entry) { // Show entries here } } } ?>
  22. In a "real" application, one would of course use a database for this, but I understand that you want to move forward slowly and not learn everything at once. As Jessica said, you would almost always be using a database for storage, so learning how to do this by file probably won't help you out that much in the future anyways. Using a database also makes it easier to make relationships between data such as words. For instance, one could make relationships between words that indicate that they are synonyms instead of replicating the words in PHP (avoiding this would probably get more complicated than it really has to be). Either way, here is a quick example of how you could use arrays in PHP for this. Surely there are better ways (especially if you use a database), but perhaps it is enough to get you started. $words = array( 'beautiful' => array('handsome', 'pretty', 'lovely'), 'funny' => array('comical', 'amusing', 'humorous', 'laughable'), 'clever' => array('smart', 'intelligent', 'ingenious') ); To save it to a file, you can can serialize the array (Google should help you out here). Each word has an array of synonyms. Imagine that for each of those words, you would have an array of all of the other synonyms. For instance, an entry for the word "smart" would have an array of "clever", "intelligent", "ingenious", and so on. You can use references, but I think you will end up overcomplicating things - and worse yet, you will probably not be able to leverage so much from the experience since it is probably far away from what you will face when doing "real" applications. So my advice is to keep it as close to how you would do it if you were paid to do it for someone. Good luck!
  23. I just had an idea. Using signalling would make my stored procedures more complicated. I am using a Data Access Layer (DAL) for interacting with my database, so what I am thinking of doing is to have an abstract base class (which I have already) where error codes are mapped to keys that I can use in all of my DAOs/mappers. This would centralize the refactoring required if I were to change database vendor. Something like this: class AbstractDAO { protected $error_codes = array( 'duplicate_entry' => 1062, 'another_error' => 1234 ); // Other stuff } class UserDAO extends AbstractDAO { public function register(User $user) { try { // Call stored procedure } catch (Exception $e) { if ($e->getCode() == $this->error_codes['duplicate_entry']) { // Duplicate entry } } } } This would probably (?) save me from over complicating my stored procedures. If I change database vendor, I just have to update the error codes in one class. Better yet, the codes are defined within my data access layer. Any comments? Ideas? Suggestions? Recommendations? Thanks.
  24. I took a quick look at your site and it looks very nice! I didn't look for the "continuous YouTube playback", but that sounds quite impressive. I don't know what your goal is with your site, but if it is more than just a playground, then I would be a little concerned about how you are probing/polling your server in intervals on the "wall". I imagine that your server could quickly get busy with a decent amount of users. You may also want to reconsider the data that you are transferring within your JSON. It looks like you are sending along a list of friend IDs; having many friends whose IDs have to be transferred every 500ms (?) for several users could do bad. In the end, it probably doesn't matter (at least not for quite a while), but I just had to comment on it. Other than these details, I like what you have done!
  25. Hello guys, I am building an application where I am using a stored procedure in MySQL. In this stored procedure, some errors can occur, such as duplicate entry on a unique column. This would give an error with the code 1062. My question is if I should be checking on this code in my application like below or use signalling in the database (or something else). try { // Call stored procedure } catch (Exception $e) { if ($e->getCode() == 1062) { // Duplicate entry } } The above is convenient because it allows me to easily determine what went wrong so I can either log it or give the user a precise error message. My worry is that the error code (1062 in this example) is specific to MySQL, so if I were to change database vendor in the future, I would have to refactor my application (update error codes) and my stored procedures. It is unlikely that I will change vendor, but I like to build my application to support future changes. Alternatively, I believe that I could use signalling in my stored procedure. That is, if I detect an error 1062, I can signal an error with my own error code. This allows me to create error codes that are independent of my database vendor, such that if I were to change vendor, all I would have to do would be to change my stored procedure and thus leave my application intact (hopefully). The idea is that I could use error codes that are not already used by the various vendors. I have not checked which ranges are available yet. Perhaps there are other ways to go about it. I would love to hear your thoughts on this. Thanks, Andy
×
×
  • 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.