Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation since 02/24/2025 in all areas

  1. Hi No offense taken at all ; I was just annoyed at myself with the fact that I spent most of last night debugging something, that seemingly fixed itself next morning (as is often sadly the case) Thats propably why my reply seemed angry. I apologize. As for the actual problem I have no idea what caused the initial behaviour. Now I get perfectly reasonable results regardless of whether i use cURL or file_get_contents; I therefore thought it was fitting to mark your reply as the solution, since: was exactly what was needed. Best, David
    1 point
  2. Hi CBG, Logical switches do not work like spoken words and it is easy to misunderstand them. What you really want to check is that if any one of d,c,o is yes, then error. But PHP is obeying your instructions by stopping when anyone of them is No. You need to switch the OR to an AND and it will catch the one Yes that is not allowed: <?php $p = "Yes"; //yes is different than Yes $d = "No"; $c = "No"; $o = "No"; if ($p === "Yes" && $d !== "Yes" && $c !== "Yes" && $o !== "Yes") { echo "error"; exit; } echo 'no errors'; ?> which will display an error if all three (d,c,o) are No. Otherwise, the code will display no errors. but what are you doing when a lowercase y is used? yes instead of Yes. maybe you should also use lowercase and compare with strtolower().
    1 point
  3. the 'successful' case is: $d == "Yes" || $c == "Yes" || $o == "Yes" because you are using negative logic to produce an error, the complement of this is: $d != "Yes" && $c != "Yes" && $o != "Yes" // what i think you want if ($p == "Yes" && $d != "Yes" && $c != "Yes" && $o != "Yes") { echo "error"; }
    1 point
  4. your written statement is ambiguous. please post some examples showing what result you want for different input combinations. specifically, what is the 'successful' case, which can then be complemented to produce the error case? what do you want when $p is not Yes? is that an error or does it mean that you don't care about the other three values?
    1 point
  5. You can't concatenate an if() statement like that. Try $message = 'Message goes here' . "\r\n" . 'Name: ' . $name . "\r\n"; if ($doesthishavedata != '') { $message .= 'Does this have data: ' . $doesthishavedata . "\r\n"; } $message .= 'something else: ' . $hasdata . "\r\n" .
    1 point
  6. An "if() construct" often comes in useful at times like this.
    1 point
  7. mac_gyver is 100% correct with those suggestions. I will add that using '?' placeholders can get confusing if you've got several to many variables in your query - in this case i recommend named placeholders. So, to update mac_gyver's perfectly good code as an example, $sql = "Select * FROM weekends WHERE Weekend_Number = :weekendNumber AND Men_Women = :menWomen"; $stmt = $pdo->prepare($sql); $stmt->execute([ 'weekendNumber' => $_SESSION['Weekend_Number'], 'menWomen' => $_SESSION['Men_Women'] ]); Note that another benefit of using PDO over mysqli is that you don't have to bind the parameters separately. It's been a while since I used mysqli, but i think i remember having to bind the result values as well? If I'm remembering correctly, this is another thing you don't have to do with PDO.
    1 point
  8. you should use var_dump() on the values for debugging, since it indicates the length of the value. unfortunately, you didn't show us what you saw when you echoed the variables and if you made a change to the sql query statement and it didn't work, showing us what you changed would help someone solve the problem. converting a query that has variables being put directly into it into a prepared query is straight forward - remove, and keep for later, any php variables that are inside the sql query statement. note: any wild-card characters in a LIKE comparison are supplied as part of the data value not as part of the sql query statement. remove any quotes or {} that were around the php variable and any concatenation dots/extra quotes that were used to get the php variable into the sql query statement. put a simple ? prepared query place-holder into the sql query statement for each value. call the PDO prepare() method for the sql query statement. this returns a PDOStatement object. call the PDOStatement execute([...]) method with an array of the variables you removed in step #1. for a query that returns a result set, fetch the data from the query. see the PDOStatement fetch() method when fetching a single row of data. the PDOStatement fetchAll() method when fetching all the rows of data at once. and occasionally the PDOStatement fetchColum() method when fetching a single column from a single row of data. forget about any num rows function/method/property. just fetch then test if/how many rows of data there are. for a query that doesn't return a result set, you can use the PDO lastInsertId() method and the PDOStatement rowCount() method to get the last insert id and the number of affected rows. for the query in this thread, this would look like - // i recommend that you build the sql query statement in a php variable. this makes debugging easier since you can echo the sql $sql = "Select * FROM weekends WHERE Weekend_Number = ? AND Men_Women = ?"; $stmt = $pdo->prepare($sql); $stmt->execute([ $_SESSION['Weekend_Number'], $_SESSION['Men_Women'] ]); // if this query can match a set of data $result = $stmt->fetchAll(); // if this query can match at most one row of data $result = $stmt->fetch(); typical PDO connection code - $DB_HOST = ''; // database host name or ip address $DB_USER = ''; // database username $DB_PASS = ''; // database password $DB_NAME = ''; // database name $DB_ENCODING = 'utf8mb4'; // db character encoding. set to match your database table's character set. note: utf8 is an alias of utf8mb3/utf8mb4 $options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // set the error mode to exceptions - this is the default setting now in php8+ PDO::ATTR_EMULATE_PREPARES => false, // run real prepared queries PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC // set default fetch mode to assoc ]; $pdo = new pdo("mysql:host=$DB_HOST;dbname=$DB_NAME;charset=$DB_ENCODING",$DB_USER,$DB_PASS,$options);
    1 point
  9. i second the use of prepared statements. you MUST protect against sql special characters in a value being able to break the sql query syntax, which is how sql injection is accomplished. a prepared query is the simplest (provided you use the much simpler and better designed PDO extension), fool proof way of accomplishing this for all data types. also, if the 'th' (ordinal indicator) is actually part of the value, it should not be. this is a human convention and should only be displayed, not actually submitted or stored. you should only submit or store the integer value. the code copying session variables to other variables is both unnecessary (just use the original variable that data is in) and indicates that your form and form processing code is on different pages. by separating these, you are nearly doubling the amount of code and since it takes more code to accomplish a task, you are likely leaving out things that provide security or a good User eXperience (UX.) the code for any page should be laid out in this general order - initialization post method form processing get method business logic - get/produce data needed to display the page html document
    1 point
  10. There are issues here beyond the error you're seeing. First and foremost, drop mysqli_* and use PDO - it's easier to use and can handle several different SQL dialects. Secondly, never put raw user data into a query (session data can be modified by the user). Use prepared statements in order to not lose or expose your data. As to the actual issue you're seeing, print out the value of $Number and $MW before you run the query to make sure they contain what you think they contain. If the value is actually '55th' you need quotes around the value - another bonus of using prepared statements (preparing the statement will take care of that for you).
    1 point
  11. You INSERT new records. You UPDATE existing records. When you do this, you replace the values that were in that record before you updated it. There is no way around this - it's just how databases work. What you're attempting to do is an UPDATE: UPDATE `table` SET field5 = 'value1' WHERE field1 = 'value2' AND field2 = 'value3' Regards, Phill W.
    1 point
  12. if this is the only session variable you are getting an error for (i didn't get an error for this variable, but did for some other ones when i ran your code), here are some possibilities - your actual code has some non-printing characters in or smart/curly-quotes around the index name (that posting code on this forum filtered out). i would delete and retype the entire index name, including the initial and final double-quotes, in each reference to this array index name. is any of the other code that gets executed in the functions being called, referencing or setting that variable and could be unsetting it? are you sure that the latest code got saved/uploaded so that you are actually initializing that variable? most of these session variables exist solely to pass data from the form processing code back to the form. you should instead put the form processing code and the form on the same page. this will greatly simplify all the code. the code for any page should be laid out in this general order - initialization post method form processing get method business logic - get/produce data needed to display the page html document at the completion of the post method form processing code, you should preform a redirect to the exact same URL of the current page to cause a get request for that page. this will prevent the browser from trying to resubmit the form data should that page get browsed back to or reloaded. you should not copy variables to other variables for nothing. just use the original variables that data is in. in the current code, a significant number of lines are there only to copy variables back and forth, yet you have instances of using the original variable that data is in. you should apply htmlentities() to any dynamic value being output in a html context, right before/as it is being output, to prevent any html entity in value from breaking the html syntax.
    1 point
  13. In any code that I work with that doesn't use a templating engine I try to label my conditionals, like so: <div class="slew-of-form-elements"> <?php if($myVar === true): ?> <input type="text" name="field_1"> <select name="field_2"> <option value="-1">Select an option</option> <?php foreach($options as $key=>$value): ?> <option value="<?= $key; ?>"><?= $value; ?></option> <?php endforeach; // $options as $option ?> </select> <?php endif; // $myVar === true ?> </div> Obviously this is a contrived example and is missing things like output sanitization and the many, many, many form elements some of the code deals with but hopefully the point comes across.
    1 point
  14. what this would look like using the method i posted above - <input type="text" maxlength="32" size="42" name= "<?=$Comment_Name?>" value="<?=$_SESSION["DE_Retain"] == 1 ? $_SESSION["DE_Comment"] : ''?>">&nbsp;&nbsp;Max 32 Characters<br><br> likewise for the checkbox logic - Retain comment:&nbsp;<input type="checkbox" maxlength="1" size="1" name="Retain" <?=$_SESSION["DE_Retain"] == 1 ? 'checked' : ''?>> i'm pretty sure that checkboxes don't have maxlength or size attributes. if any of these variable may not exist, to prevent php errors, you need to use the null coalescing operator ?? to set default values. if you want to clear all the session data, you can use session_destroy();. if you only want to clear this 'form' data you are passing around, while keeping the current user logged in, you should store this data in a session array variable, such as $_SESSION['post']. you can then clear this data by just unsetting it - unset($_SESSION['post']);
    1 point
  15. The lack of indentation makes it entirely unclear what the control flow of your script has, since indentation is missing and it's hard to understand by looking at it, what runs or doesn't. This is generally considered to be spaghetti. The best practice for intermingling HTML and PHP is to utilize the PHP alternative syntax tags, which allow your code to integrate more cleanly with your html. You are already using the "<?= ?>" shorthand syntax for individual values, which is good. Extend that to also using the control tag structure, and add indentation. Make sure that your editor is configured to use spaces for tabs! Once you have done that, it's possible in most editors to go back and replace all your tab characters with your standard tab size. Typically people choose either 2 or 4 spaces per tab. If you adhere to https://www.php-fig.org/psr/psr-12/ then it should be 4 spaces of indentation (a tab should create 4 spaces). As this is a snippet from a larger script, we are obviously missing the context of the rest of the code, but I re-wrote your snippet using the alternative syntax for comparison. <?php if ($_SESSION["DE_Retain"] == 1): ?> <input type="text" maxlength="32" size="42" name= "<?= $Comment_Name ?>" value="Des">&nbsp;&nbsp;Max 32 Characters<br><br> <?php else: ?> <input type="text" maxlength="32" size="42" name= "<?= $Comment_Name ?>" value="Dave">&nbsp;&nbsp;Max 32 Characters<br><br> <?php endif; ?>
    1 point
  16. You don't need the braces so long as there are only single statements to be executed but only if they are in the same <?php .. ?> block of code. EG this works... <?php if (date('d')==24) echo 'today'; else echo 'Not today'; ?>
    1 point
  17. the php error you are getting is a follow-on error, because the query is failing, but there is no error handling for the query. the easiest way of adding error handling for all the mysqli statements that can fail - connection, query, exec, prepare, and execute, is to use exceptions for errors (this is the default setting now in php8+). to enabled exceptions for the mysqli extension, add the following line of code before the point where you make the database connection (or upgrade to php8) - mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); you should then be getting an uncaught exception error with the raw database error information in it about a non-groupby/non-aggerate column being referenced. the correct way of fixing this is to a) only select the columns you are using, and b) every column you are selecting needs to be either in the GROUP BY term or used in an aggerate function. there is a database server mode setting that control if this condition produces a query error (the current setting) or if it is just a warning. you may or may not have access to this database mode setting.
    1 point
  18. You only need one query. For example TABLE : product +----+-------------+--------------+--------+ | id | productName | category | status | +----+-------------+--------------+--------+ | 1 | Room 1 | Guestroom | Active | | 2 | Room 2 | Guestroom | Active | | 3 | Room 3 | Guestroom | Active | | 4 | Room 4 | Guestroom | Active | | 5 | Function 1 | Functionroom | NULL | +----+-------------+--------------+--------+ code $sql = "SELECT SUM(status='Pending')as pending , SUM(status='Active') as active FROM product"; $result = mysqli_query($con, $sql); $row = mysqli_fetch_assoc($result); echo "Pending : <input type=\"button\" class=\"button\" value=\"{$row['pending']}\"> Active : <input type=\"button\" class=\"button\" value=\"{$row['active']}\"> "; output
    1 point
  19. I'd ask exactly how confident you are that the strings are definitely going to look the way you think. If you're 100% sure they will definitely be "[Stuff] Text (Page 123)" then great, but if not then...
    1 point
  20. One way is to find the positions of the "]" and and the "(" and grab the text between those points. $qa = [ "[Question - Geography Chapter2] How would you describe humans' relationship with the physical environment? (Page 42)", "[Question - Geography Chapter4] What is a natural resource? (Page 67)", "[Question - Geography Chapter3] What are two or three resources which you cannot do without? What are the reasons for your choices? (Page 52)" ]; foreach ($qa as $k => &$q) { $p1 = strpos($q, ']'); $p2 = strpos($q, '('); $q = trim(substr($q, $p1+1, $p2-$p1-1)); }
    1 point
  21. The point of programming help forums is for you to post your code and the error or symptom you are getting and someone with the ability (and often without) will attempt to help you with the problem.
    0 points
This leaderboard is set to New York/GMT-04:00
×
×
  • 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.