Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
Your question is so vague that it needs to be answered with a correspondingly vague response. Yes you can use a method as a condition. How you would use it would be based entirely on the possible return values of the method and what your needs are. If you are having some trouble with some code, post the relevant code and what your problem is.
-
Dropdown select submit and placing variables also syntax help
Psycho replied to Bill Withers's topic in PHP Coding Help
That first line would not generate an error regarding an undefined index. There's a reason the PHP errors provide all the information that they do - they are useful in finding the actual error. By trying to parse the error down to what you think is relevant only hinders our ability to help. I only provided "sample code". I do my best to ensure it is working code, but I don't take the time to create databases and sample data just to test code I am providing to people here. Generally, the code I provide is more of a general guideline on how to solve a problem. My expectation is that the recipient will do the debugging and fixing of any typos. After reviewing the code I do see some errors: 1. The options being created were overwriting the variable $optionsHTML instead of appending to it 2. The while loop was using the the wrong variable -it should be the one passed to the function Try the following. If it doesn't work try to fix the errors. If you can't fix the errors provide the entire error messages received <?php $dataResult="op1"; mysql_connect ("localhost", "root", "xxx") or die( "Unable to connect to database"); @mysql_select_db($dataResult) or die( "Unable to select database"); //Function to create the options list. //The $dataResult is expected to be a DB //Result set with fields named 'id' and 'name' function createOptions($dataResult) { if(!$dataResult || mysql_num_rows($dataResult)) { //No records included for option list return "<option value=''>EMPTY</option>\n"; } $optionsIDs = array(); $optionsHTML = ''; //Process result set into HTML options while($row = mysql_fetch_assoc($dataResult)) { $optionsHTML .= "<option value='{$row['id']}'>{$row['name']}</option>\n"; $optionsIDs[] = $row['id']; } //Get a random ID from the records $randomID = $optionsIDs[array_rand($optionsIDs)]; $optionsHTML = "<option value='{$randomID}'>Random</option>\n" . $optionsHTML; return $optionsHTML; } $query = "SELECT id, name FROM places"; $result = mysql_query($query); $placesOptions = createOptions($result); $query = "SELECT id, name FROM color"; $result = mysql_query($query); $colorOptions = createOptions($result); ?> Places: <select name="places"> <?php echo $placesOptions; ?> </select> Colors: <select name="color"> <?php echo $colorOptions; ?> </select> -
As Pikachu stated that could be written more logically and it actually has a flaw. If the user entered the number '0' the validation would fail because the function empty() would return false. But, let's step back a second because that is really overkill. If you must have a check to ensure there is at least 1 number in the value there is no need to do the strlen() or empty() checks at all! Also, I normally do an isset() check on form field values. It could be considered overkill, but I incorporate it with a process to also trim the values which you should be doing anyway. So, here's my take: $address = isset($_POST['address']) ? trim($_POST['address']) : ''; if(!preg_match("/[0-9]/", $address )) { //Invalid echo "The value '$address' is invalid"; //Add this for debugging }
-
And that was good advice in my opinion. There is a reason that even the largest IT companies rely upon hashing methods available in the industry. they have been developed by people that have a very deep knowledge and years of experience in the field. We're talking about people with PhD's in mathematics and advanced sciences. For example, SHA-1 was Sorry to be blunt, but I highly doubt you were able to come up with a better method. My organization works with companies that require the highest measures of security because of the data we store. We would fail any security audit by those companies if we were using a hashing method that has not been proven in the industry. If you want verification that your method is acceptable then you should provide the hashing method along with some sample data. If you are confident in what you built.
-
Your immaturity in both temperament and experience is apparent. Do you realize that many (if not all) the algorithms for the hashing methods used within the industry are publicly available? A secure hashing method is not one that relies upon obfuscation of the process. It's the exact opposite. By having the algorithms publicly available it allows experts and novices alike to verify the quality of the process, find flaws, and improve upon that method. A good hashing method would not be any less secure by the process being hidden because it should be impossible to reverse engineer the process to the the unhashed value. I have very little confidence that you or your associates were able to build a more secure hashing method than are already available. A more intelligent approach would have been to use an existing hash method with string lengthening and a salt. Further, your so called challenge is a joke. As stated above a hash - if done correctly - cannot be "unhashed" into it's original value. All the sites that can presumably tell you the password for an MD5 hash are nothing more than rainbow tables which could be created for any hashing method. I could easily create some trivial hashing method in 2 seconds that would create a hash which you would never be able to decipher. Here's a hash: 1 That is a hash of my social security number, date of birth and my mothers maiden name. I added up all the ASCII values of the characters and performed a modulus on the number 2. Granted, that is a gross simplification, but it illustrates the triviality of creating a value that cannot be reversed into the original value. But, as stated above, that is not what hashes are for. Lastly, you have violated numerous forum rules No one here attacked you. Some criticism was made, but you should take that and use it rather than getting defensive. I had also looked at your website earlier and had also considered writing a response regarding the poor spelling and grammar which stood out to me like an electronic billboard. But, I decided I didn't care enough to do so.
-
Well "best" is subjective. I prefer PHPEdit by WaterProof: http://www.phpedit.com/en There are way too many features to list. But, my favorite is that, in addition to auto-complete for functions, once the function name is complete and you are inside the parameter list of a function - there is a hover block that shows you the function name, a description of what it does, as well as a list of the parameters. There are inconsistencies in how some functions expect their arguments and I hate having to look up the argument list. Case in point: array_map() and array_walk(). These perform similar processes. But, the first two arguments are switched. maybe there is some logic to that, but I can never remember it. So, I really appreciate that feature in PHPEdit.
-
Look closer. The error state, the problem is with the "bind_param()" method/function - not "Bind". Here is where you use bind_param() $return = self::$Stmt->bind_param(implode(', ', $arg)); You have a single parameter as an argument (the result of the implode). Per the manual there are two required arguments (or three if you are using procedural style): Also, I am sure your error message gave you a line number. Did you not use that to verify where the error occurred?
-
It's a mystery, isn't it? // Query member data from the database and ready it for display $sql = mysql_query("SELECT * FROM car_data WHERE id='$id' LIMIT 1");
-
Having an issue with UPDATING SQL Database via PHP Table
Psycho replied to mbb87's topic in PHP Coding Help
I made some minor errors in the code I provided (I didn't test it), but the logic is sound. Some of the replies since are getting this conversation on the wrong track, so let me elaborate: David was 100% correct here - I meant to use 'intval'. Using that will force all the values to be integers to prevent SQL Injection. [ As one other contributor noted the table name should be in backticks (or none at all). However, the query is fine. The query I provided doesn't need a WHERE clause and using one would actually make it fail to produce the correct results. I actually tested this logic on a table so I know it works. Let me explain how it works because it is not completely obvious how it works but is actually pretty ingenious in my humble opinion. Here is the query UPDATE `players` SET `block` = `players`.`pl_id` IN (1, 5, 9, 10, 11, 12) The list of IDs will be dynamic based upon those that are checked on the form page. So the query is going to attempt to update all records and set the value of 'block' to `players`.`pl_id` IN (1, 5, 9, 10, 11, 12) What is happening there is that for each record a condition is done to see if that records id is in the list of supplied ids. The result will be true or false. In MySQL a true/false response is a 1 or 0. So, the result is that the block value is set to '1' for all records in the supplied list and '0' for the rest. I originally supplied two queries to do the 0 and 1 separately and then thought of the above approach. After I tested it I modified my post where I provided that code. So, you should only need to make the changes to the array_map() function to use 'intval' and then use backticks around the table name: //Verify the values are valid integers and put in comma separated string $checked_players_list = implode(', ', array_map('intval', $_POST['pl_id'])); //Run update to set blocked status based on whether the player ID was in the submitted list $query = "UPDATE `players` SET `block` = `players`.`pl_id` IN ({$checked_players_list})"; $result = mysql_query($query); echo "Debugging info:<br>\n"; echo "POST Data:<pre>" . print_r($_POST, 1) . "</pre>\n"; echo "Checked Players list: {$checked_players_list}<br>\n"; echo "Update Query: {$query}<br>\n"; if($result) { echo "Query executed with " . mysql_affected_rows($result) . " affected rows"; } else { echo "Query Failed. Error " . mysql_error(); } -
Having an issue with UPDATING SQL Database via PHP Table
Psycho replied to mbb87's topic in PHP Coding Help
Put some error/debugging handling into your code to see where the problem is. Change the processing code to this: //Verify the values are valid integers and put in comma separated string $checked_players_list = implode(', ', array_map('int', $_POST['pl_id'])); //Run update to set blocked status based on whether the player ID was in the submitted list $query = "UPDATE 'players' SET `block` = `players`.`pl_id` IN ({$checked_players_list})"; $result = mysql_query($query); echo "Debugging info:<br>\n"; echo "POST Data:<pre>" . print_r($_POST, 1) . "</pre>\n"; echo "Checked Players list: {$checked_players_list}<br>\n"; echo "Update Query: {$query}<br>\n"; if($result) { echo "Query executed with " . mysql_affected_rows($result) . " affected rows"; } else { echo "Query Failed. Error " . mysql_error(); } What is output to the page? -
Having an issue with UPDATING SQL Database via PHP Table
Psycho replied to mbb87's topic in PHP Coding Help
-- DELETED -- -
Having an issue with UPDATING SQL Database via PHP Table
Psycho replied to mbb87's topic in PHP Coding Help
OK, I just realized that you were using a hidden field for the ID. That's completely unnecessary and would not work with the code I provided. You only need to use the checkbox field in your form. The hidden fields are not needed. Use this for your form along with the processing logic I provided above. echo "<table border='1'>"; echo "<tr><th>NAME</th><th>POS</th><th>BLOCK</th></tr>"; while($row = mysql_fetch_array( $result )) { $checked = ($row['block'] == '1') ? ' checked="checked"' : ''; echo "<tr>\n"; echo " <td>{$row['f_name']} {$row['l_name']}</td>\n"; echo " <td>{$row['pos']}</td>\n"; echo " <td><input type='checkbox' name='pl_id[{$row['pl_id']}]' value='{$row['pl_id']}'{$checked}></td>\n"; echo "</tr>"; } echo "</table>"; -
Having an issue with UPDATING SQL Database via PHP Table
Psycho replied to mbb87's topic in PHP Coding Help
NEVER EVER run queries in loops. They are a huge resource hog and will kill your server. There is ALWAYS a better solution. In this case you need to run only two queries: one to update the record that are unchecked and one to update those that are checked. First off, I would change the form code by removing the $counter and just using the ID of the record as the field index in the input field name. You aren't using the index of the field name for anything anyway. Or you could just remove the named index entirely. echo "<table border='1'>"; echo "<tr><th>NAME</th><th>POS</th><th>BLOCK</th></tr>"; while($row = mysql_fetch_array( $result )) { $checked = ($row['block'] == '1') ? ' checked="checked"' : ''; echo "<tr>\n"; echo " <td>{$row['f_name']} {$row['l_name']}</td>\n"; echo " <td><input name='pl_id[$row['pl_id']]' type='hidden' value='{$row['pl_id']}'>{$row['pos']}</td>\n"; echo " <td>\n"; echo " <input name='pos[$counter]' type='hidden' value='{$row['pos']}'>"; echo " <input type='checkbox' name='block[$counter]' size='1' value='1'{$checked}>\n"; echo " </td>\n"; echo "</tr>"; } echo "</table>"; Then on your processing page you just need to do ONE query like this //Verify the values are valid integers and put in comma separated string $checked_players_list = implode(', ', array_map('int', $_POST['pl_id'])); //Run update to set blocked status based on whether the player ID was in the submitted list $query = "UPDATE 'players' SET `block` = `players`.`pl_id` IN ({$checked_players_list})"; $result = mysql_query($query); EDIT: Corrected one mistake in code above (imploded IDs) and revised to only need ONE query to update all the records! -
First off, don't just try something and provide a reply along the lines of "it doesn't work". Provide some details of what you tried, what were the expected results, and what were the actual results. But, yes, you are correct. It doesn't work of nested and non-nested quotes together. In fact, I've never been able to build such a query that handles both. If you change to the non-greedy format you had previously for the content inside the quote tags it will work for that output. However, if there are any opening or closing quote tags that don't have a partner you will get some odd results. Use this $regEx = '#\[quote\ ([^;]*);([^\]]*)\](.*?)\[\/quote\]#ims';
-
Dropdown select submit and placing variables also syntax help
Psycho replied to Bill Withers's topic in PHP Coding Help
Here's some sample code using two tables for illustrative purposes. This is not tested, but should give you an idea of where to start. The key to this approach is that you will simply use the ID passed from the form. The code below will automatically create the select lists for you along with a "Random" option that will have the value of a random ID from that list. <?php //Function to create the options list. //The $dataResult is expected to be a DB //Result set with fields named 'id' and 'name' function createOptions($dataResult) { $optionsIDs = array(); $optionsHTML = ''; //Process result set into options while($row = mysql_fetch_assoc($result)) { $optionsIDs[] = $row['id']; $optionsHTML .= "<option value='{$row['id']}'>{$row['name']}</option>\n"; } //Get a random ID from the records $randomID = $optionsIDs[array_rand($optionsIDs)]; $optionsHTML = "<option value='{$randomID}'>Random</option>\n" . $optionsHTML; return $optionsHTML; } $query = "SELECT id, name FROM Places"; $result = mysql_query($query); $placesOptions = createOptions($result); $query = "SELECT id, name FROM color"; $result = mysql_query($query); $colorOptions = createOptions($result); ?> Places: <select name="places"> <?php echo $placesOptions; ?> </select> Colors: <select name="color"> <?php echo $colorOptions; ?> </select> -
Dropdown select submit and placing variables also syntax help
Psycho replied to Bill Withers's topic in PHP Coding Help
There's a much simpler way. Create a function to create the select lists. So, you just need to run the query with the IDs and the names and pass the result into the function to create the options. Further, build the function to first create all the non-random choices putting the IDs into an array. Once all the options have been created choose a random ID from the list and create the Random option using that ID and prepend that option to the beginning. Then when the user chooses random, just use the selected ID that was used for the Random optino rather than having to run another DB query. -
Hmm, you can set any values YOU wish. You can have the user submit a form and then completely overwrite any data they may or may not have entered with hard coded data. I'm not really sure what you are asking. $favoriteSnack = $_POST['user_submitted_favorite_snack']; if($favoriteSnack != 'Ding Dongs') { //Ding dongs rule all bitches ! ! ! $favoriteSnack = 'Ding Dongs'; } $query = "UPDATE USERS SET favorite_snack = '$favoriteSnack' WHERE user_id = $user_id";
-
OK, I tested out his regex some more and my interpretation was correct. It is getting the correct results - but it is working by accident. If this was the content to be parsed The first iteration would produce this: The regex I provided will handle each block as a whole
-
Yeah, I found that his regex did work for nested quotes, but I've reviewed the regex a few times and don't see how it is working correctly. The way I read that is that the part in bold would do a lazy match of all characters up till the first closing quote tag is found. So, the first opening quote tag would match content up till the first closing quote encountered - which would be from the last quote block. I guess I'm missing something. BUt, using those lazy quantifiers is kind of inefficient. Here is my rewrite that fixes the line breaks and removes the lazy quantifiers function formatQuotes($input) { $output = nl2br($input); $regEx = '#\[quote\ ([^;]*);([^\]]*)\](.*)\[\/quote\]#ims'; $format = '<blockquote>Posted by: \1 at \2.<br/>\3</blockquote>'; do { $output = preg_replace($regEx, $format, $output, -1, $replaceCount); } while($replaceCount != 0); return $output; }
-
It looks like he is using the loop to handle nested quotes. But I don't think it will work with the regex being used because of the lazy matches. The regex could use some work.
-
How to insert data into a div using a foreach statement.
Psycho replied to shyam13's topic in PHP Coding Help
Did you even look at the code we provided? What we both provided was very, very simple logic. -
How to insert data into a div using a foreach statement.
Psycho replied to shyam13's topic in PHP Coding Help
while($row = mysql_fetch_assoc($result)) { echo "<div>\n"; echo "{$row['field_name1']}<br>\n"; echo "{$row['field_name2']}<br>\n"; echo "{$row['field_name3']}<br>\n"; echo "</div>\n"; } -
A couple things: You don't have to "echo" the content as you are processing it. You can store the content in a variable(s) as you are getting the count and then echo the output. I'm curious why you are grouping by events and area. Why would you have multiple events in the events table? I would also assume that each event is only associated with one area. It's really difficult to provide the proper solution as I do not understand your database schema. If what I think is true about your database, then I would think that GROUP BY clause is not serving a purpose. Another thing is that your query has a specific area ID specified in the WHERE clause. If you are only pulling records for one area then just use mysql_num_rows() on the result to get the number of venues for that area. But, assuming you are pulling records for multiple areas, I would modify the processing logic to get the count of venues by area THEN create the output for that area. Sample code (NOTE: I would change the query to also return the area ID and use that in the logic to determine changes in area. Using a name value is not good practice. function displayEventsByArea($areaArr) { $areaCount = count($areaArr); echo "<div class='areaheader'>"; echo "<h2 class='gridarea'>{}</h2>{$areaArr['area_name']} ({$areaCount})"; echo "</div>"; foreach($areaArr) { echo "Event: {$areaArr['event_title']}"; echo "<img src='{$areaArr['img_filename']}'><br>\n"; } } $currentArea = false; while($row = mysql_fetch_assoc($result)) { if($currentArea !== $row['area_name']) { if($currentArea !== false) { //Output the previous set of events for the area displayEventsByArea($areaArray); } //Set the current area $currentArea = $row['area_name']; //Set (or reset) array of event data $areaData = array(); } //Populate current record into $areaData array $areaData[] = $row; } //Output the LAST set of events for the LAST area displayEventsByArea($areaArray);
-
Really?! There are two problems with that statement. 1) You could EASILY put the values into a single dimensional array when processing the DB results. 2) If you need to know the count of unique names - then just do that using your DB query! Something such as: SELECT name, COUNT(name) as count FROM table GROUP BY name I actually have a very simple solution for getting the result you asked for using the multi-dimensional array, but that is not the solution that you should be using.
-
array_count_values() will get you started. How is the original array created? There might be a way to get it in a more useful format to start with.