Jump to content

Psycho

Moderators
  • Content count

    11,936
  • Joined

  • Last visited

  • Days Won

    113

Psycho last won the day on October 10

Psycho had the most liked content!

Community Reputation

553 Excellent

About Psycho

  • Rank
    Move along, nothing to see here

Profile Information

  • Gender
    Not Telling
  • Location
    Canada
  1. Psycho

    Refactoring this code...

    Instead of one long procedural body of code, create functions or classes for certain operations - especially if you need to do the same thing anywhere else in your application. That way you can create intuitive calls within your code that makes it much easier to read/manage. For example, you could create a function called usernameExists($uname) that returns a TRUE?FALSE based on whether the passed username already exists or not. Then also create a function to create a new user. Try to avoid "SELECT *" in your queries. Only select the fields you need. Otherwise, you can create conditions that leak data. In this case you are just checking if the record exists, so select the username or some other innocuous field. Alternatively, you could do a COUNT(*) query. Your process to see if a record exists with one query before running another query to create a record is problematic. It is possible for a "race condition" to occur which would allow a duplicate to be created. You should instead create the DB table to ensure that field is unique. Then just try to perform the insert. If it fails, check the error to see if it was due to a duplicate. Lastly, use comments! It may seem obvious when you are writing code what is happening, but when you have to come back later or if someone else has to work on the code it is invaluable. Here's a slight update to the code Barand posted with some modifications. //Function to see if a username exists function usernameExists($uname) { $username_query = $conn->prepare("SELECT username from profiles001 WHERE username=?"); $username_query->execute( [ $_POST['username'] ] ); return ($username_query->fetch() != false); } //Function to create a new user function createUser($userDataAry) { $sqlInsert = $conn->prepare("INSERT INTO profiles001  (username, password, email, c_status, doc, avatar, bio) VALUES (?, ?, ?, ?, NOW() , ? , ? )"); $sqlInsert->execute( $userDataAry ); } if ($_SERVER['REQUEST_METHOD'] == 'POST') { //Check if username already eists if (usernameExists($uname)) { header('Location: /soapbox/signup.php'); exit; } //Get data from the $_FILES array $file = $_FILES['file']; # other code here # if (empty($fileDestination)) $fileDestination = "assets/soap.jpg"; //Create the user $hashed_password = password_hash($_POST['password'], PASSWORD_DEFAULT); createUser( [ $username, $hashed_password, $email, $confirmation_status, $fileDestination, $bio ] ); }
  2. Psycho

    Ajax call without reloading ?

    To be clear, Requinix is being sarcastic. It is absolutely possible, you just aren't understanding what he was stating in the first response. Here is an analogy that might help. Think of a web page like a "printout" from a printer. So, let's say you create a document on your computer and print it out - then you change some content in the file on your computer. Would you expect the content on the already printed page to change? Of course not! Now, imagine that JavaScript can modify the computer document AND/OR modify the printed page like an eraser and pen. So, in your currently code your JavaScript is only changing the value of $_SESSION["so"] in the electronic document. You would need to refresh the page (i.e. create a new printout) OR modify the code to change the content in the existing output. Requinix already provided an example of how to do that, but let me explain in simple terms. 1) When creating the output for the page create an element on the page that can be referenced in the JavaScript <span id="value"><?php echo $_SESSION["so"]; ?></span> 2) Run your javascript to update the value to be changed on the page. In this case, you would have the JS use an AJAX call to a page that updates the session value and returns that value to the calling AJAX script in the original page. 3) The AJAX script then takes that return value and modifies the element created in step 1. In fact, the JQuery framework has a simple method for doing this without needing to use the full AJAX method. .load()
  3. Psycho

    rearrange dates in a DB table

    I'm not sure what the OP is really wanting here as the "requirements" are very confusing. Right now, the DB contains a timestamp for a login and a timestamp for a logout. If the intent is to replace those values with a human readable period of time (i.e. 5 hours, 23 minutes) then no changes to the DB should be made. That type of logic should be made in the output process. There are plenty of resources that will take two timestamps and produce a period of time output.
  4. Wait. What is/are the error(s)? No way to tell if any function will or will not work to solve an error without knowing the specific error and what code is causing it.
  5. Psycho

    Use of conditions (Switch/IF)

    //Get the count of true conditions $conditionCount = 0; $conditionCount += (info_cond1()) ? 1 : 0; $conditionCount += (info_cond2()) ? 1 : 0; $conditionCount += (info_cond3()) ? 1 : 0; //If only one condition, set correct div if($conditionCount==1) { //Only one condition is true if(info_cond1()) { echo '<div>DIV A</div>'; } if(info_cond2()) { echo '<div>DIV B</div>'; } if(info_cond3()) { echo '<div>DIV C</div>'; } } elseif($conditionCount>1) { //Multiple conditions are true echo '<div>DIV D</div>'; } else { //No conditions are true echo '<div>DIV E</div>'; }
  6. Psycho

    timer not updating in database reliably

    A lot of "generalized" info and not enough specifics. 1. What type of field is time_achieved right now?I am guessing it is a "time" field type. My guess is that the value that is getting passed to update that field is not properly formatted for that field type - therefore it defaults to 00:00:00. But, I also see you have some javascript to reset the value of a field to 00:00:00 - perhaps there is something calling that function onsubmit of the form. 2. You ask about how to do a countdown. Storing a time value will not work for that. Instead you should be storing a timestamp of when the countdown should end. Then you can calculate how much time is left. If a user submits 00:20:00 (for a 20 minute timer), then your logic should set a timestamp 20 minutes in the future.
  7. Psycho

    Displaying null for unwanted data

    I'm not following. You first state that you are using a regular expression to remove all but numbers from the values. Then you state that you want a value such as "Tnex>=40" to return Null or empty (as opposed to "40"). So, I'm not sure what you really want returned. Then you state that when you try to add the logic to your query you are not getting the rows that don't match the criteria. But, the query you provided doesn't have any where clause. If you had, I might have a better understanding of what you are really wanting from above. Lastly, the most important question is WHY are you doing this? If that data is not valid, then you should fix the data instead of creating complex process to handle the bad data on the output. I would update all the values in the database to just the number (or empty if you prefer) and implement logic when saving new values to ensure only valid data is entered. Although I would NOT advise the approach you are wanting, one of these will do what I think you are wanting Return the value if it is only a number - else return an empty string SELECT Date, Tnex, Mode, IF(Snex*1 = 0, "", Snex) as Snex FROM datatb Return the value with all non-numeric characters removed SELECT Date, Tnex, Mode, REGEXP_REPLACE(Snex, '[^0-9]+', '') as Snex FROM datatb
  8. Psycho

    how to reset a counter in a for loop

    You need to use CODE tags - not QUOTE tags. E.g. [ CODE ] $foo = 'bar'; [ /CODE ] (or use the <> button in the editor) will be presented like this $foo = 'bar'; As to the issue with $resultCheck. That variable is defined once at the top of the script - it never changes. So the condition if ($resultCheck == $increment) { would only pass if the number of initial results is exactly the same as the $increment value. I have a suspicion that you think the value of $resultCheck will dynamically change in the loop as records are consumed. As Barand has stated, this code has a lot of flaws. Before writing any code, I suggest getting a piece of paper and create a rough outline of the logic flow instead of trying to determine the logic as you write the code. As you start writing out the code you might find flaws in the originally planned logic and that's OK. but, by having a rough plan before you start you will be better able to make changes as you go instead of coding yourself into a corner.
  9. Psycho

    Do you see my coding error?

    Where is $first_name defined? Do the two records being returned happen to have no first name? If so, it all makes sense to me.
  10. Psycho

    forms forms forms... Please help

    Barand gave a lot of good advice and there is a lot more that can/should be done. However, a forum post is not the right medium to give a tutorial on all the aspects in creating a good form. But, I will elaborate on one thing Barand stated: Right now, three is no "processing logic", there is just a single statement to INSERT the data into the DB. As Barand stated you need to be using "prepared statements" (here's a good tutorial). But, you need to validate the user input before you even attempt to INSERT the data, otherwise simple input mistakes will lead to corrupt data. For example, you need to check that required fields have an input and for any fields that do have an input you need to ensure it is a proper value for that field. Number fields should be numbers, dates should be dates, etc. Also, if a field has a properly formatted value, it may still not be valid. You wouldn't want to accept a date if the user accidentally entered a year of 2118, right? One way to help users enter data (especially when format is important, i.e. date) is to use the placeholder parameter for input fields. It puts an "example" value as a guid into the field until the user puts focus on the field <input type="text" name="date" placeholder="MM-DD-YYYY"> Also, using javascript plugins for things like date inputs is also a good idea. But, don't rely upon them for ensuring user input is correct. Get the firm working first with just HTML - then add any JavaScript to enhance the user experience. Here is a quick and dirty example of a form and how I tend to approach them. <?php //Variable to hold form error description $errorDsc = ""; //Get the form values (if posted) $name = isset($_POST['name']) ? trim($_POST['name']) : ''; //Trim strings $dab = isset($_POST['dab']) ? trim($_POST['dab']) : ''; //Trim strings $pounds = isset($_POST['pounds']) ? intval($_POST['pounds']) : ''; //Convert to number //Check if form was posted if($_SERVER['REQUEST_METHOD']=="POST") { //Create an array to hold errors $errors = array(); //Check name if($name=="") { $errors[] = "Name is required"; } //Check DOB if($dab=="") { $errors[] = "Date of birth is required"; } else { //Create a timestamp of DOB $dabTS = strtotime($dab); //Check if DOB was invalid or in the future if(!$dabTS or $dabTS>time()) { $errors[] = "Date of birth must be validly formatted (mm-dd-yyyy) and not in the future."; } } //Check weight - 0 will be value if no input provided because of intval() above if($pounds<0) { $errors[] = "Weight cannot be negative."; } //Check if there were errors if(!count($errors)) { //Prepare the error description $errorDsc = "Please correct the following errors:<br><ul>\n"; foreach($errors as $err) { $errorDsc .= "<li>{$err}</li>\n"; } $errorDsc .= "</ul>\n"; } else { //Form was posted and all input is valid // //Create and run prepared statement to insert data into DB //Then perform a header redirect to a confirmation page //The redirect will prevent a duplicate submission if the // user was to click the refresh button } } ?> <html> <head></head> <body> <?php //Show the error description //Will be empty if form was not posted echo $errorDsc; //Note, if there were errors, the entered values will be repopulated in //input fields below. select/radio/etc type fields would need a different process ?> <form method="post" action=""> Name: <input type="text" name="name" placeholder="" required value="<?php echo htmlentities($name); ?>"> <br> Date of Birth: <input type="text" name="dob" placeholder="mm-dd-yyyy" required value="<?php echo htmlentities($dob); ?>"> <br> Weight in pounds: <input type="text" name="pounds" placeholder="No. of pounds" value="<?php echo htmlentities($pounds); ?>"> </form> </body> </html>
  11. Psycho

    PHP Multidimensional Arrays

    And who said you wanted it on all of them? He was saying that when you build the array you should make the determination as to which elements to make active. Also, your statements are confusing. In the first post you state you want to search for an element by a string value, but in your last post you state you know the Article_ID. So, why would you be searching for a text value if you know the Article_ID?
  12. Try this <?php //Read file into variable $file = "Sample.txt"; $text = file_get_contents($file); //Create array to hold results $results = array(); //Split the content based on *NEXT* $questions = preg_split("#\*NEXT\*[^\n]*#is", $text); //Process each question section foreach($questions as $question) { //Find the question text if(preg_match("#}(.*)#", $question, $question_match)) { //Exctract the question text $question_text = trim($question_match[1]); //Find the answers preg_match_all("#([ABCD]\)) ([^\n]*)#i", $question, $answers_match, PREG_PATTERN_ORDER); $answers = array_combine ( ['A','B','C','D'], array_map('trim', $answers_match[2])); //Find the correct ansewer preg_match("#Answer\: ([ABCD])#", $question, $correct_match); $correct = $correct_match[1]; //Put question parts into results $results[] = array( 'question' => $question_text, 'answers' => $answers, 'correct' => $correct ); } } //See results echo "<pre>" . print_r($results, true) . "</pre>";
  13. Psycho

    JavaScript not working in IE11

    To my knowledge, <output> tags do not have a "value" attribute. In your form there are fields like this: <output class="loan-amount" name="principal" id="principal" onChange="calculate();"></output> Then, in the calculate function there is logic like this: var principal = document.getElementById("principal").value; Typically I see IE making 'assumptions' in how it interprets code, but this seems to be one instance where IE is doing the right thing and not assuming the field has a property which it does not. I would write all of that much differently, but to make it work correctly move the name/id parameters from the <output> tags to the corresponding <input> tags. That way the code is referencing the value of the input fields.
  14. Another reason is that the data should be "agnostic" to how it is being used. When working in PHP, and many languages, you can reference the data via the column names. However, what if there was a need to reference the data via numerical index (there's a reason why there are explicit options to only retrieve data via numerical indexes). You might be passing the results to another process that can't use the column names and will simply reference the data by the order it is presented. In that case, if "SELECT *" is used and field order is changed or fields are added, the functionality could break. By selecting just the fields that are needed in the order that they are needed, the functionality will not break (unless someone was to remove a field).
  15. Psycho

    truncate text

    Please read requinix's earlier response. If you are still getting the full output with your code above, that is because the function wpjm_the_job_description() is outputting the content to the page and not returning it. E.g. wpjm_the_job_description() { $value = "Get some text from some process or source to be displayed"; echo $value; //The function is directly outputting text to the page return; //Nothing is returned from the function for you to modify it } You will either need to see if there is a function to get the string rather than outputting it or you can try modifying that function directly.
×

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.