Jump to content


  • Content Count

  • Joined

  • Last visited

  • Days Won


Psycho last won the day on October 10 2018

Psycho had the most liked content!

Community Reputation

554 Excellent

About Psycho

  • Rank
    Move along, nothing to see here

Profile Information

  • Gender
    Not Telling
  • Location

Recent Profile Visitors

The recent visitors block is disabled and is not being shown to other users.

  1. array_rand only returns the key (or keys) of the randomly selected items. So, that line would only return a 0 or 1 - which is not helpful without the original array to get the value from. It makes more sense to create an array as a variable first, the use array rand to get the value like so: $values = ['orange', 'apple']; $randomValue = $values[array_rand($values)];
  2. Psycho

    Important "if" statement relying on mySQL

    However, I would strongly suggest putting the error condition first as Barand did in his examples. The reason is that it makes it easier to "see" the condition that creates the error. Plus, if your error condition does a redirect, you don't even need to enclose the main code in an else clause. This makes the code easier to read/maintain. if($foo == 'bar) { include('some_error_page.php'); exit; } //Continue with the main logic w/o else clause Also as Barand's stated, there is no reason to create a variable when you have a perfectly good condition. But, if you do need to create a flag based on a condition, do not do it this way if($numberoflabels > 4) { $too-many-labels = TRUE; } Instead do this: $too-many-labels = ($numberoflabels > 4);
  3. Psycho

    Problem with form output

    So, now you are going to post the REAL code? How nice of wasting people's time. You still haven't done what has been suggested multiple times - output your variables so you can SEE what they are. Instead of putting your query string directly in the prepare() statement, create it as a variable. Also, the full query that you are now showing us could be the problem. Even if there is matching data an error in the JOIN criteria could prevent any results. Replace this for the relevant section in your code and look at the results to see if the query and param values are what you think they are. // // FINDTOTAL RECORDS IN SEARCH RESULTS // $placeholderStr = join(",", $placeholders); $query = "SELECT COUNT(*) as tot FROM ( SELECT id FROM ( SELECT v.id , v.title , GROUP_CONCAT(tag SEPARATOR ' ') as alltags FROM product v JOIN product_tag t ON v.id = t.product_id GROUP BY v.id ) v JOIN product_tag t ON v.id = t.product_id WHERE tag IN ({$placeholderStr}) GROUP BY id HAVING COUNT(t.tag) = ? ) found;"; echo "<b>Query:</b><pre>{$query}</pre><br>\n"; echo "<b>Params:</b><pre>".print_r($params, true)."</pre><br>\n"; $res = $db->prepare($query); $res->execute($params);
  4. Psycho

    Problem with form output

    First, I would strongly suggest that you first use more appropriately named variables. Don't create a generic variable and then try and reuse it. What does "$params" represent? Parameters obviously, but parameters for "what"? In this case $params is an array that keeps getting additional values appended to it - and those values are logically different "types" of values. Also, a prepared query will expect an array with the same number of parameters as placeholder in the query. Second, output your variables to the page to "see" what they contain. $params does not contain what you think it does when you are using it.
  5. Psycho

    PHP Group Array Dealing With Duplicates

    In addition to ginerjm's excellent suggestion on building the array one time, the output code is also inefficient. This would do the same with much less code and in a more logical format. #output the data foreach ($product_table as $sku => $products) { echo "<tr>\n"; echo "<td>{$sku}</td>\n"; foreach ($products as $product) { echo "<td>{$row['Value']}</td>\n"; } echo "</tr>\n"; }
  6. Psycho

    save data from an array to database

    Something to consider, you can make the code much simpler if you can structure the input data in the same manner as you plan to use it. Instead of having fields called "name[]", "mode[]" and "sport[]" that are only associated by being in the same position - you can give them a more concrete structure that matches how you will use them for your query. The first input fields could be named: "student[0][name]", "student[0][mode]" and "student[0][sport]" The second input fields names: "student[1][name]", "student[1][mode]" and "student[1][sport]" etc. . . . This, of course, requires a little more logic in the process of 'cloning' rows to create the input fields. But, with this structure, your processing code would go something like this foreach($_POST['student'] as $studentRec) { $stmt->execute($studentRec); }
  7. Psycho

    Prevent direct File Access

    If there is a login system, then the orders should be associated with the user's account. If they log back in, you should have all the data you need in order to allow them to retrieve their shipping labels. If users can place orders without being logged in, then you you should provide an alternative method to "see" their order and retrieve a shipping label if needed. 1. You could provide a link in their order confirmation email that uses a unique GUID that is associated with the order 2. You can provide a page to "look up" an order. The user would need to provide their order number and one or more identifying pieces of information that were used when placing the order: email address, zip code, etc.
  8. Psycho

    Finding occurrence of values in a string.

    //I broke out the code into multiple lines for readability and maintainability function insertReferences($text) { $regEx = "#(\d{3})\.(\w)#is"; $format ='<span class="btn btn-link" data-target="section${1}" onclick="showPage('section${1}')" data-parent="#page">${1}.${2}</span>'; return preg_replace($regEx, $format, $text); }
  9. Psycho

    Finding occurrence of values in a string.

    I think the best solution is RegEx [specifically preg_replace() or preg_match()], but to provide a solution would require the "specs" for the article references. You gave one example where the reference was three digits + period + the letter 'f'. Do they always start with a series of digits? If so, what is the minimum/maximum number of digits? Are the digits always followed by a period? Is the period always followed by a letter? If so, what are the valid letters and are they always lower case? Also, how is that reference supposed to be modified to a URL? I.e. what would the URL look like for your example of '105.f'? Here is an example function insertReferences($text) { return preg_replace("#(\d{3})\.(\w)#is", '<a href="displayArticle.php?id=${1}&type=${2}">${1}.${2}</a>', $text); } //Text from DB $articleText = 'Beginning text and then a reference 105.f to another article'; //Modify text to include hyperlinks $outputText = insertReferences($articleText); //Output the result echo $outputText Output: Beginning text and then reference <a href="displayArticle.php?id=105&type=f">105.f</a> to another article
  10. Psycho

    Mysqli - Can You Not Do These Short-Cuts ?

    Mind blown! I never knew the ternary operator could be used like that. I typically use it for defining a variable from POST/GET data similar to that. However, I typically trim() the value within the true condition, so it may not be as useful as I would like, but still . . .
  11. 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 ] ); }
  12. 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()
  13. 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.
  14. 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.
  15. 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>'; }

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.