Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation since 12/05/2021 in all areas

  1. With a couple of db tables like this Table: user Table: role +---------+----------+--------+ +---------+---------------+-----------+------------+ | user_id | username | points | | role_id | role_name | point_min | points_max | +---------+----------+--------+ +---------+---------------+-----------+------------+ | 1 | John | 66 | | 5 | - | 0 | 100 | | 2 | Paul | 101 | | 6 | Contributor | 101 | 1000 | | 3 | George | 3000 | | 7 | Author | 1001 | 10000 | | 4 | Ringo | 200000 | | 8 | Editor | 10001 | 100000 | +---------+----------+--------+ | 9 | Administrator | 100001 | 999999999 | +---------+---------------+-----------+------------+ Then a simple query SELECT username , rolename FROM user u JOIN role r ON u.points BETWEEN r.points_min AND r.points_max; does the job for you +----------+---------------+ | username | rolename | +----------+---------------+ | John | - | | Paul | Contributor | | George | Author | | Ringo | Administrator | +----------+---------------+
    3 points
  2. Use DATE type columns for your dates, not varchar. Have your leaving dates either a valid date or NULL. SELECT eemp_id , fname , lname , AVG(timestampdiff(MONTH, joining_date, coalesce(leaving_date, curdate()))) as av_mths FROM employee_details ed JOIN employee e ON e.empid = ed.eemp_id GROUP BY eemp_id HAVING av_mths >= 36;
    3 points
  3. I think I might have guessed right regarding an access policy. How much "customization" does each resource need regarding its access? I would assume not much, and that they all typically pick from a small handful of possibilities. If so then you have access policies, a resource uses an access policy, every user has something to consume policies in a similar design, then you manage access through those secondary objects. user <-> permission policy <-> access policy <-> resource The principle here is that a resource does not try to decide how and where it can be used - it has a policy which manages that. And a user doesn't decide how and what it can use - it has permissions that decide. Consider a roller coaster ride. They'll have a sign saying "you must be this tall to ride" and a person who enforces that; the roller coaster is the resource and the sign is the access policy. When someone wants to ride, they present themselves; they are a user and their permissions are their physical appearance (ie. height). The person who enforces the height requirement would then be the code used to implement the system - someone who understands the access policy, the permissions, and how to evaluate the two together.
    2 points
  4. do not store any user information in cookies. anyone can set cookies to any value and can impersonate a user. to do what you are asking, generate a unique token, store the token in a cookie and store it in a row in a 'remember me' database table, along with the user's id and things like when the remember me was set and when you want it to expire if not regenerated. if you receive a cookie containing a token, query to get the user's id and the expire datetime to determine if the token is valid. if it is, set the normal session user_id variable to indicate who the logged in user is. you should only store the user id in a session variable, then query on each page request to get any other user information, such as the username, permissions,... this will insure that an change/edit in this user information will take effect on the very next page request.
    2 points
  5. OK - I've added the sort usort($test, fn($a, $b) => $b['itemCount']<=>$a['itemCount']); // sort descending itemCount $seen = []; foreach ($test as $k => &$rec) { $rec['rolanID'] = array_diff($rec['rolanID'], $seen); // find new ids if ($rec['rolanID']) { // if there are some new ones ... $rec['itemCount'] = count($rec['rolanID']); // count them $seen = array_merge($seen, $rec['rolanID']); // add the new ones to those already seen } else unset($test[$k]); // if no ids, remove the array item } and I now get this (no duplicate 123)... Array ( [0] => Array ( [supplier] => TEST2 DEPO [rolanID] => Array ( [0] => 456 [1] => 188 [2] => 200 [3] => 123 ) [itemCount] => 4 ) [1] => Array ( [supplier] => TEST DEPO [rolanID] => Array ( [1] => 234 ) [itemCount] => 1 ) [2] => Array ( [supplier] => DIFFERENT DEPO [rolanID] => Array ( [0] => 897 [1] => 487 [2] => 100 ) [itemCount] => 3 ) )
    2 points
  6. or... $res = $pdo->query("SELECT `option`, total FROM vote"); $data = $res->fetchAll(); $votes_cast = array_sum( array_column($data, 'total') ); foreach ($data as $r) { printf ("%s has %d votes (%0.1f %%)<br>", $r['option'], $r['total'], $r['total']*100/$votes_cast); }
    2 points
  7. Depending on what it is you're trying to do with the data, there are several ways to change a field. You can set up an accessor or mutator or use a query scope, for instance. Query scope sounds like what you're looking for, although should worse comes to worst you could just write a trait and use it on your model instances where needed.
    2 points
  8. For anyone following... I did a screen-share with the OP. The problem was missing files and files in the wrong place. I did a clean install of Laragon and installed (Not upgraded) Mysql 8. All is working.
    2 points
  9. The PHP DateTime::diff() method provides a very convenient way of getting the days, hours, minutes and seconds components of a time difference so this script uses an AJAX request on loading to get the time remaining. From then on, it calls a javascript function every second to reduce the time displayed by one second. This greatly reduces network traffic and gives a consistent update performance. Repeatedly using AJAX could sometimes result in delays preventing a regular countdown interval. <?php ################################################################################################################## # # # THIS SECTION HANDLES THE AJAX REQUEST AND EXITS TO SEND RESPONSE (Days,hrs, mins, secs remaining) # # # if (isset($_GET['ajax'])) { if ($_GET['ajax'] == 'countdown') { $remain = ['days' => 0, 'hrs' => 0, 'mins' => 0, 'secs' => 0]; $dt1 = new DateTime( $_GET['target'] ); $dt2 = new DateTime('now'); if ($dt1 > $dt2) { $diff = $dt1->diff($dt2); $remain['days'] = $diff->days; $remain['hrs'] = $diff->h; $remain['mins'] = $diff->i; $remain['secs'] = $diff->s; } exit(json_encode($remain)); } } # # ################################################################################################################### $target = '2022-04-30 23:59:59'; // SET OR GET TARGET TIME HERE $targ = new DateTime($target); $target_time = $targ->format('g:ia'); $target_date = $targ->format('F jS Y'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Countdown</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type='text/javascript'> var inter $().ready( function() { get_time_remaining() // call AJAX request to get remaining time inter = setInterval(countdown, 1000) // set timer to call "countdown()" function every second }) function countdown() { let s = parseInt($("#secs").html()) // get current time remaining let m = parseInt($("#mins").html()) let h = parseInt($("#hrs").html()) let d = parseInt($("#days").html()) if (d==0 && h==0 && m==0 && s==0) { // exit when target time is reached clearInterval(inter) $(".remain").css("background-color", "red") return } s--; // reduce display by 1 second if (s < 0) { s = 59; m-- } if (m < 0) { m = 59 h-- } if (h < 0) { h = 23 d-- } if (d < 0) { d = 0 } $("#days").html(d) // redisplay new values $("#hrs").html(h) $("#mins").html(m) $("#secs").html(s) } function get_time_remaining() { $.get( // make AJAX request "", {"ajax":"countdown", "target":$("#target").val()}, function(resp) { // put response values in display fields $("#days").html( resp.days ) $("#hrs").html( resp.hrs ) $("#mins").html( resp.mins ) $("#secs").html( resp.secs ) }, "JSON" ) } </script> <style type='text/css'> body { font-family: verdana, sans-serif; font-size: 11pt; } header { padding: 8px; text-align: center; width: 600px; margin: 20px auto; background-color: #F0F0F0; } .target { color: #006EFC; font-size: 16pt; } table { border-collapse: collapse; width: 400px; margin: 0 auto; } td, th { padding: 8px; text-align: center; width: 25%; } .remain { font-size: 24pt; color: white; background-color: black; border: 1px solid white; } </style> </head> <body> <header> <p>Countdown to</p> <p class='target'><?=$target_time?> on <?=$target_date?> </p> <!-- make target time available to javascript --> <input type='hidden' id='target' value='<?=$target?>' > <table border='0'> <tr><th>Days</th><th>Hours</th><th>Mins</th><th>Secs</th></tr> <tr> <td class='remain' id='days'>0</td> <td class='remain' id='hrs'>0</td> <td class='remain' id='mins'>0</td> <td class='remain' id='secs'>0</td> </tr> </table> </header> </body> </html>
    2 points
  10. Simple. Triple the page width and offset each label. require 'code128.php'; $data = ['item_name' => 'Fuel Vapour Hose' ,'code_purchase' => 'ABC-2342' ,'code_sale' => 'DFS-4312' ,'item_code' => '47900001' ]; class Barcode_Label extends PDF_Code128 { protected $data; //constructor public function __construct() { parent::__construct('L','mm',[190, 35]); } public function printLabel($data) { $this->setMargins(5,5,5); $this->SetAutoPageBreak(0); $this->AddPage(); $this->setFont('Times', 'B', 10); for ($lab=0; $lab<3; $lab++) { $offset = $lab * 65; $this->setXY($offset, 5); $this->Cell(50, 5, $data['item_name'], 0, 2, 'C'); $this->Cell(25, 5, $data['code_purchase'], 0, 0, 'C'); $this->Cell(25, 5, $data['code_sale'], 0, 2, 'C'); $barcode = $this->Code128($offset + 5,15,$data['item_code'],50,10); $this->setXY($offset, 25); $this->Cell(50, 5, $data['item_code'], 0, 1, 'C'); } } } #Barcode_Label $label= new Barcode_Label(); for ($i=0; $i<3; $i++) { $label->printLabel($data); } $label->Output(); [edit] PS I don't know your label dimensions so you may have to adjust offset, page size and margins
    2 points
  11. Here's one way class PriceCalculator { private $start; private $end; private $price = [ 0 => [ 98, 128], 1 => [ 88, 118], 2 => [ 88, 118], 3 => [ 88, 118], 4 => [ 88, 118], 5 => [ 88, 118], 6 => [ 98, 128] ]; public function __construct ($time1, $time2) { $this->start = new DateTime($time1); $this->end = new DateTime($time2); } public function calculate() { $total = 0; $dp = new DatePeriod($this->start, new DateInterval('PT1M'), $this->end ); foreach ($dp as $min) { $day = $min->format('w'); $peak = '02' <= $min->format('H') && $min->format('H') < '18' ? 0 : 1; $total += $this->price[$day][$peak]/60; } return number_format($total, 2); } } $time1 = "2022-03-12 16:12:00"; $time2 = "2022-03-12 18:31:00"; $instance = new PriceCalculator($time1, $time2); echo $instance->calculate(); // 242.53
    2 points
  12. First only returns a single item, so there's no point in putting it in a collection. The collection is for methods that might return several items.
    2 points
  13. I don't have any specific recollection of such a thing, but a lot of things have changed in the css world, most notably the standardization of flexbox and grid that make older techniques and tricks of css layout obsolete. You just don't need those things anymore when flexbox or grid can take care of your layout needs with simple, consistent and easy to understand syntax. There was a time when you needed to know the ins and outs of floats and clear fix, and other arcane tricks of css, but that's basically obsolete knowledge. People also use to use tables inside tables inside tables to get their "pixel perfect" layouts, but that also has given way to a focus on creating layouts that adapt from desktop to mobile. This guy (Kevin Powell) has become well known in the css/web design world, and he really knows his stuff. This video covers flexbox. If you work through the examples with him, you will learn what you need. He also has a corresponding Grid video. If you want something more interactive, lots of people love Scrimba, and in particular Per Borgen, who is one of the Scrimba founders. He happens to have a free scrimba course covering grid and flexbox, so that is another way you can learn flexbox, if you want something more interactive. The free Scrimba Grid/Flexbox course is here: https://scrimba.com/learn/cssgrid
    2 points
  14. PHPFreaks has been going through some ownership and hosting changes, and that has lead to some extended down time. The hosting for the site has been generously provided by a number of different people and organizations throughout the years, and without their patronage, phpfreaks would have shutdown many years ago. With that said, please understand that the volunteers who administer and moderate the site don't have control over the underlying infrastructure, other than what is provided to us. In this recent outage the new owner of the site, who supported it in the years following the sale of the original hosting company where phpfreaks was created, has provided us a lot of support and aid, and demonstrated a commitment to keep the site running for the foreseeable future. Unfortunately, with that said, there will probably be some additional outages in the near future as the server resources that run the site are being moved to a different co-location facility. Please bear with us through these difficulties, as we endeavor to keep the community alive and available for everyone who finds it useful. We will continue to keep doing the work to keep phpfreaks running, and we appreciate the many long time members who have made it their home.
    2 points
  15. Hello Marcus, So to be clear, what we are talking about is variable typing and type hints. Variable typing is only done within a class or trait. The dog class has examples of variable typing. I expanded the examples to make a point of what changed: <?php class Dog { private int $dog_weight = 0; private string $dog_breed = "no breed"; private string $dog_color = "no color"; private string $dog_name = "no name"; public function __construct($dog_weight, $dog_breed, $dog_color, $dog_name) { $this->dog_weight = $dog_weight; $this->dog_breed = $dog_breed; $this->dog_color = $dog_color; $this->dog_name = $dog_name; } public function get_properties() : string { return "$this->dog_weight, $this->dog_breed, $this->dog_color, $this->dog_name"; } } $fido = new Dog(42, 'Poodle', 'Brown', 'Fido'); echo $fido->get_properties() . PHP_EOL; $spike = new Dog('Heavy', 'Mutt', 'Orange', 'Spike'); // Generates Fatal error: Uncaught TypeError: Cannot assign string to property Dog::$dog_weight of type int echo $spike->get_properties() . PHP_EOL; The class variable definition lines like this one: "private int $dog_weight = 0" was first introduced in PHP 7.4. Prior to that you could not include the "int" to tell php you wanted $dog_weight to be a int. Furthermore, in my examples, if you try something like passing a string for the assignment, php will generate a runtime error now: "Fatal error: Uncaught TypeError: Cannot assign string to property Dog::$dog_weight of type int" Previously however, PHP did support type hinting for parameters that has a similar function. <?php class Dog { private $dog_weight = 0; private $dog_breed = "no breed"; private $dog_color = "no color"; private $dog_name = "no name"; public function __construct(int $dog_weight, string $dog_breed, string $dog_color, string $dog_name) { $this->dog_weight = $dog_weight; $this->dog_breed = $dog_breed; $this->dog_color = $dog_color; $this->dog_name = $dog_name; } public function get_properties() : string { return "$this->dog_weight, $this->dog_breed, $this->dog_color, $this->dog_name"; } } $fido = new Dog(42, 'Poodle', 'Brown', 'Fido'); echo $fido->get_properties() . PHP_EOL; $spike = new Dog('Heavy', 'Mutt', 'Orange', 'Spike'); // Generates a Fatal error: Uncaught TypeError: Dog::__construct(): Argument #1 ($dog_weight) must be of type int, string given echo $spike->get_properties() . PHP_EOL; This was available in PHP version 7.0. This parameter type hinting has been heavily used, especially when passing objects as parameters, since version 7.0. class Dog { private $dog_weight = 0; private $dog_breed = "no breed"; private $dog_color = "no color"; private $dog_name = "no name"; public function __construct(int $dog_weight, string $dog_breed, string $dog_color, string $dog_name) { $this->dog_weight = $dog_weight; $this->dog_breed = $dog_breed; $this->dog_color = $dog_color; $this->dog_name = $dog_name; } public function get_properties() : string { return "$this->dog_weight, $this->dog_breed, $this->dog_color, $this->dog_name"; } } class Cat { private $cat_breed = 'no breed'; private $cat_name = 'no name'; public function __construct(string $cat_breed, string $cat_name) { $this->cat_breed = $cat_breed; $this->cat_name= $cat_name; } public function get_properties() : string { return "$this->cat_breed, $this->cat_name"; } } class Kennel { private $borders = []; public function addDog(Dog $dog) : void { $this->borders[] = $dog; } public function getBorders() : string { $output = ''; foreach($this->borders as $pet) { $output .= $pet->get_properties() . PHP_EOL; } return $output; } } $kennel = new Kennel(); $fido = new Dog(42, 'Poodle', 'Brown', 'Fido'); $kennel->addDog($fido); $sparky = new Dog(22, 'Mutt', 'Tan', 'Sparky'); $kennel->addDog($sparky); $simba = new Cat('siamese', 'Simba'); echo $simba->get_properties() . PHP_EOL; echo $kennel->getBorders(); $kennel->addDog($simba); //Generates Fatal error: Uncaught TypeError: Kennel::addDog(): Argument #1 ($dog) must be of type Dog, Cat given What has never been possible is add a type to a variable declaration outside of a class definition (as you attempted to do): <?php int $errorCode = 7; //generates a Parse error: syntax error, unexpected '$errorCode' (T_VARIABLE) in 7. //generates Parse error: syntax error, unexpected variable "$errorCode" in 8. One other common type hint is to utilize an interface definition as a parameter type hint: <?php interface HasFeet { public function setFeet(int $number); public function getFeet() : int; } class Duck implements HasFeet { private $nbrFeet; public function setFeet(int $number) { $this->nbrFeet = $number; } public function getFeet() : int { return $this->nbrFeet; } } class Mouse implements HasFeet { private $legs; public function setFeet(int $number) { $this->legs = $number; } public function getFeet() : int { return $this->legs; } } class Fish { private $legs = 0; public function getFeet() : int { return $this->legs; } } class Catalog { private $animals = []; public function addAnimal(HasFeet $animal) { $this->animals[] = $animal; } public function getAnimalFeetCount() : string { $output = ''; foreach($this->animals as $animal) { $output .= 'A ' . get_class($animal) . " has {$animal->getFeet()} feet" . PHP_EOL; } return $output; } } $catalog = new Catalog(); $duck = new Duck(); $duck->setFeet(2); $mouse = new Mouse(); $mouse->setFeet(4); $catalog->addAnimal($duck); $catalog->addAnimal($mouse); echo $catalog->getAnimalFeetCount(); //Generates //A Duck has 2 feet //A Mouse has 4 feet // //Fatal error: Uncaught TypeError: Argument 1 passed to Catalog::addAnimal() must implement interface HasFeet, instance of Fish given PHP 8 has added constructor variable definition through parameter scope & typing: <?php // Prior to 8.0 - Standard class variable initialization class Bike { private $wheels = 0; public function __construct(int $wheels=2) { $this->wheels = $wheels; } public function getWheels() : int { return $this->wheels; } } // PHP 8.0 definition via parameter class Car { public function __construct(private int $wheels=4) { } public function getWheels() : int { return $this->wheels; } } $bike = new Bike(); echo $bike->getWheels() . PHP_EOL; $car = new Car(); echo $car->getWheels() . PHP_EOL; $truck = new Car(18); echo $truck->getWheels() . PHP_EOL; // In PHP 8.01+ // 2 // 4 // 18 So PHP 8 will relieve you of having to define attributes in the class definition, if you define them in the constructor. This works for class parameters as well!
    2 points
  16. Example $arr = [ [ 'A', 'Jan. 22, 22'], [ 'B', 'Dec. 25, 21'], [ 'C', 'Feb. 22, 22'], [ 'D', 'Jan. 2, 22'] ]; usort($arr, function($a, $b) { $da = DateTime::createFromFormat('M. j, y', $a[1]); $db = DateTime::createFromFormat('M. j, y', $b[1]); return $db <=> $da; }); echo '<pre>' . print_r($arr, 1) . '</pre>'; outputs Array ( [0] => Array ( [0] => C [1] => Feb. 22 22 ) [1] => Array ( [0] => A [1] => Jan. 22 22 ) [2] => Array ( [0] => D [1] => Jan. 2 22 ) [3] => Array ( [0] => B [1] => Dec. 25 21 ) )
    2 points
  17. COALESCE() comes in useful here SELECT ... FROM tablename WHERE COALESCE(colname, '') = '';
    2 points
  18. I use mostly PHP Debug and PHP Intelephense.
    2 points
  19. Create an array of those field names which are to be read only, for example $readonly = ['id', 'username', 'email']; then $ro = (in_array($key, $readonly)) ? 'readonly' : '';
    2 points
  20. 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 the post method form processing should - detect if a post method form was submitted keep all the input data in an array variable, then operate on elements in this array variable throughout the rest of the code trim all the inputs at once. after you do item #2 on this list, you can accomplish this with one line of code validate all the inputs, storing user/validation errors in an array using the field name as the array index after the end of all the validation logic, if the array holding the errors is empty, use the form data if an insert or update query can result in duplicate data, detect this in the error handling for the database query, and setup a message for the user telling them what was wrong with the data that they submitted after the end of the form processing logic, if there are no user/validation errors, perform a redirect to the exact same url of the current page to cause a get request for the page. to display a one-time success message, store it in a session variable, then test, display, and clear the session variable at the appropriate location in the html document. if there are errors at item #5 or #7 on this list, the code will continue on to display the html document, redisplay the form, where you should populate the form field values/selects/checkboxes with any existing values so that the user doesn't need to keep reentering/selecting/checking data over and over. you should get your code to fully work first with one form field, then one field of each type, before you worry about all the code needed for all the rest of the fields. you can use the following to display what post data is being submitted to your code - echo '<pre>'; print_r($_POST); echo '</pre>'; the posted code contains a php syntax error on line #13. to get php to display syntax errors, you must set php's error_reporting to E_ALL and display_errors to ON, in the php.ini on your development system (putting these settings into your code won't work for php syntax errors since your code never runs to change the settings.) stop and start your web server to get any changes made to the php.ini to take effect and confirm that the settings actually got changed by using a phpinfo() statement in a .php script file. you should also validate any resulting web page at validator.w3.org to help make sure the markup is valid and you should only write markup that is necessary.
    1 point
  21. The query you ran in PHPMyAdmin appears to be the only one above that has correct syntax.
    1 point
  22. Yea, I usually just do something like this: $storageDir = '/wherever/you/want'; do { $name = bin2hex(random_bytes(16)); } while (file_exists($storageDir.'/'.$name)); The loop probably isn't really necessary, the chance of a collision is statistically insignificant I think, but I throw it in anyway just in case. I'll usually create a few sub-directories as well rather than literally have everything in one directory. Take the first few characters of the name and make a sub-directory based on that. For example, if the result were c6c1ce8c2bcf000daea561cbcca4a671 then I'd end up saving the file to: /wherever/you/want/c6/c1/c6c1ce8c2bcf000daea561cbcca4a671. Keeps the directory sizes more manageable just in case you need to manually browse to some file.
    1 point
  23. PDO is more streamlined mysqli has result objects and statement objects depending on whether you used query() or prepare(). The methods for handling the results of these two objects are completely different. This mean two confusing sets of methods to learn. On the other hand, PDO produces objects with exactly the same methods to process the results of query() or prepare(), and usage of prepare() is itself much simpler. Some mysqli methods are only available depending on your implementation of MySql. PDO works with multiple varieties of DBMS (mysql, postgres etc). The SQL dialects may be different but your php code remains the same if you change. Having used the old mysql_* for years I originally changed to mysqli (how different could it be?) After a long while I decided I had to learn PDO in order to support others who were using it. I really wished I'd switched to it originally instead of mysqli.
    1 point
  24. i suspect you are asking this because your code and variables aren't behaving the way you expect? the reason most of your conditional tests are not working and variables are being changed, is because one = is an assignment operator and two == is a comparison operator. when you have a statement like - if($donationclash = false), this assigns false to the variable, then tests the result, which will be a false value. all these conditional tests against variables should use two ==. if($donationclash == false), this tests if the variable is equal to a false value and leaves the value in the variable as is. a comment about the use of the $donationclash variable throughout this code. since your program logic is halting execution if the $DONATIONCLASHTIME is false, there's no point in the $donationclash variable at all. all the rest of the code on the page after the $DONATIONCLASHTIME test and its message won't be executed. here's a list of issues with the current code - there are no helpful comments in the code describing what the goal of each section is. this makes it almost impossible for anyone to help with your code. switch to the much simpler and more consistent PDO database extension. it treats the result of a non-prepared and a prepared query identically. this alone will eliminate about half of the code dealing with database queries. don't copy variables to other variables for nothing. just use the original variables. this accounts for close to half of the existing lines of code. this is just a waste of typing and is making more work for you in keeping track of everything and makes it almost impossible for anyone to help. don't use multiple names for the same thing. this requires you to keep track of which name you are using and makes it next to impossible for someone to help. use under scores _ to separate the words making up names of things. make the database connection in an initialization section at the top of your code and don't repeatedly require (once) the connection file. only store the user's id in session variable, named user_id or similar, to indicate who the logged in user is. this will either be set or it won't. query on each page request to get any other user information, such as the username, permissions, ... you have mistakes in most of the if() comparisons. one = is an assignment operator. two == is a comparison operator. there are other logic mistakes with what the else and else if logic is doing, that would be easier to see if you consistently indent your code. use 'require' for things that your code must have for it to work. include/require are not functions. the () around the value does nothing but clutter up your code with unnecessary typing. be consistent. you are using include/require_once and echo/print at different points. don't use a loop to fetch data from a query that will match at most one row of data. just fetch the single row of data. why do you have an if() around the prepare() calls? you don't do anything if they fail and since the execute() calls can fail, why don't you have conditional tests for them too? instead of writing out conditional logic for each database statement that can fail, use exceptions for errors and in most cases simply let php catch and handle any database exception, simplifying the code. the only time your code should catch and handle a database statement error/exception is for user recoverable errors, such as when inserting/updating duplicate or out of range user submitted data. in all other cases, don't put any logic in your code and simply let php catch and handle the error/exception. build sql query statements in php variables. this will make testing easier and help to eliminate typo mistakes by separating the sql query syntax as much as possible from the php syntax. you should always fetch all the data that a query returns, which is why you went to the trouble of executing a query in the first place, so there should not be any case where you need to close a prepared query. don't store redundant data in multiple locations. you are storing the user's id in the donationclashdetails. that's all the user information you need. you can get any other user information via the user's id. any one conditional test can either be true or false. you don't need test for the false case after you have tested for the true case. if a test is not true, it must be false. the $stmt->store_result() and $stmt->bind_result() after the INSERT query don't belong there and may be producing errors. do you have php's error_reporting set to E_ALL and display_errors set to ON, preferably in the php.ini on your system, so that php will help you by reporting and displaying all the errors it detects? the SELECT ... FROM donationclashdetails WHERE participationid = ? query, right after the INSERT query, and the associated repetitive logic, is unnecessary. the php 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 post method form processing should - detect if a post method form was submitted, which you are doing. however, all the form processing code goes inside this conditional block of code. yours isn't. keep the form data as a set, in an array variable, then operate on elements in this array throughout the rest of the code trim all the inputs at once validate all inputs, storing validation errors in an array using the field name as the array index after the end of the validation logic, if there are no errors (the array holding the errors will be empty), use the submitted form data after the end of the form processing logic, if there are no errors, perform a redirect to the exact same url of the current page to cause a get request. this will prevent the browser from trying to resubmit the form data to display a one-time success message, store it in a session variable, then test, display, and clear the variable at the appropriate location in the html document. if there are errors at step #5, the code will continue on to (re)display the html document. you would test/display any errors and redisplay the form, populating the field value(s) with any existing data. apply htmlentities() to any dynamic value when you output it in a html context
    1 point
  25. PS If you really want to do it in PHP then you can apply the same method to an array $thresholds = array( '-' => [0, 100], 'contributor' => [101, 1000], 'author' => [1001, 10000], 'editor' => [10001, 100000], 'administrator' => [100001, 999999999] ); echo getUserRole(50000, $thresholds); //--> editor function getUserRole($current_balance, $thresholds) { foreach ( $thresholds as $role => $range ) { if ( $range[0] <= $current_balance && $current_balance <= $range[1] ) { return $role; } } return false; }
    1 point
  26. you would need to return $beneficiaries;, rather than to echo it, and then use the returned value in the calling code.
    1 point
  27. If you have problem getting your code to work then you should probably post that code. Because we'll be a lot more inclined to help if we can see what you have so far than if we had to try to do everything for you...
    1 point
  28. this is generally a symptom of something being output to the browser prior to the headers. if this is the case, there would be a php error at the headers stating where the output was started at. is php's error_reporting set to E_ALL and log_errors set to ON, preferably in the php.ini on your system, so that php would log all error? if so, check the web servers error log file. what code is there before the headers? could it be outputting anything to the browser, such as upon an unexpected received value? also, for the screenshot, for the file in question, if you open the original or a successfully downloaded copy of it, it in your programming editor, does it start with exactly the same characters as in the screenshot?
    1 point
  29. gmail has recently stopped accepting emails that are being sent by unknown, unauthenticated email clients/systems, such as a sending mail server at some random web hosting. you must generate an OAuth token and use it to authenticate when sending to gmail. see the following post and thread it is in - prior to this, you were required to use smtp authentication against your gmail mailbox, which the php mail() function does not support, so you need to use either the phpmailer or swiftmailer class in any case.
    1 point
  30. Oh dear. If you've got the money to buy Windows Server Datacenter then you've got the money to hire an IT person whose job it would be to deal with these matters.
    1 point
  31. Don't use a redirect. Half of the point of a 404 page is that it returns a 404, and using a redirect makes it do something different. Why not just change the 404.php to be this new page? Wouldn't that be easier?
    1 point
  32. Looking at the screenshot and your code, it seems like the following variable is the one you will use to determine which of the 3 images to display. $checkSqlRow["LEGIT"] Your screenshot suggests this variable will contain one of the following values: weet nie nee ja One option would be to test for those values in an if / elseif statements to determine which image to display. For example, if the green image is to be displayed for "ja" and red for "nee", you could do something like this: <?php $checkSqlRow["LEGIT"] = strtolower($checkSqlRow["LEGIT"]); //make sure the value is lower case before testing if($checkSqlRow["LEGIT"] == 'ja') { echo '<img src="green.gif">'; } elseif($checkSqlRow["LEGIT"] == 'nee') { echo '<img src="red.gif">'; } elseif($checkSqlRow["LEGIT"] == 'weet nie') { echo '<img src="yellow.gif">'; } ?> Note that the image names (and the path) will need to be adjusted to whatever you are using.
    1 point
  33. value="<?php while($item = $stmt->fetch()) { echo $item['agency_user']; } ?>" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ NO! NO! NO! You don't use a while loop when there is only a single row returned. The while loop fetches rows until there are none left, at which point item contains "false" (ie empty). You are using the prepared query incorrectly. The point of preparing queries is to avoid putting variables into the query. <?php if ($SERVER['REQUEST_METHOD'] == 'POST') { //database cn $db = new PDO("mysql:host=localhost;dbname=centrify","root",""); $stmt = $db->prepare("SELECT * FROM agencies_data WHERE agency_user = ? "); $stmt->execute([ $_POST['user'] ]); $item = $stmt->fetch(); if ($item) { ?> <input class="form-control" type="text" name="oid" value="<?= $item['agency_user']?>"> <php } } ?>
    1 point
  34. since you finally posted the code producing the unexpected output, this is because your html markup is broken. you are not surrounding the value = '...' attribute completely/correctly with single-quotes, so the first space character becomes a stop character. in the markup.
    1 point
  35. A good website to understand PDO that I found is this one -> https://phpdelusions.net/pdo and I suggest creating a PHP sandbox to play around with PDO. After reading this thread I think you're concentrating too much on the mysql and other databases (which PDO can handle) than PHP PDO? I have been using PDO for sometime now, but I don't think it's easier to learn than mysqli, though once learned it is more versatile.
    1 point
  36. 1. It clutters the session. If you have a lot pages storing their arbitrary data in there then you start to lose track of what values are in there and why. It's the same problem as with global variables. 2. Making sure the session is clean of old data can be hard. Consider if someone browses through the quiz and then stops partway: what happens to the data? It stays in there until something either overwrites it or removes it (like doing another quiz) so the longer a user is on the site and the more they don't conform to the expected behavior for a user, the more data piles up. 3. Upgrading users through data changes becomes a problem. If the quiz works one way for a long time and then it's changed to work differently (requiring the session data be stored differently) then you have to worry about users with long-lived sessions who have old data still in there. 4. It is actually slower to some degree. Every time you fire up the session, PHP has to deserialize the entire session from its cache, and if there are large chunks in there you don't care about then it is wasteful.
    1 point
  37. the error response you are getting has nothing directly to do with checkbox form data. you are getting an error with either the sql query statement or the execution of the sql query, but because the error handling does not display/log the raw error information, you don't have any idea why it is failing. you need to find what the problem is and correct it. just trying a bunch of different things results in a lot of wasted time, with no actual learning occurring. the current code is using the PDO extension, a prepared query with external, unknown, dynamic values, is supplying an array of the inputs to the execute() call, and is using exceptions for errors. this is the best choice for performing database operations and you should continue to use these practices. some changes for the current code - when you make the connection, set emulated prepared queries to false, i.e. you want to run real prepared queries. set the default fetch mode to assoc, so that you don't need to specify it in each fetch statement. i would also name the connection variable $pdo, so that anyone looking at the code can tell what database extension it is using. because you are using exceptions for errors, there's no point in having discrete conditional error handling logic in your code, because it will never get executed upon an error. so, simply remove the if($result)... logic. if duplicate data is not an application error for this insert (and also for an update) query, you would NOT have any exception try/catch code at all, and simply let php catch the exception, where php will use its error related setting to control what happens with the actual error information (database statement errors will 'automatically' get displayed/logged the same as php errors.) for what you are currently experimenting with, this is probably the case. if you remove the try/catch code you have now, and assuming that your php is configuration to report and display all php errors, you will now start seeing database statement errors too. if this insert (and also for an update) query could result in duplicate data values and this is an error for your application, you would catch the exception in your code, test if the error number is for a duplicate index error, and setup a message for the user telling them what was wrong with the data they submitted. if the error number is for anything else, re-throw the exception and let php handle it. note: $_POST is always set, even if it is empty, so the current logic testing if(isset($_POST)){ will always true. also, don't copy variables to other variables for nothing, this is just a waste of your time typing all of that. your post method form processing code and form code should - detect if a post method form was submitted. keep the form data as an array variable, then operate on elements in this array variable throughout the rest of the code. trim all the input data at once. by keeping the data in an array variable, you can do this with one single line of code. validate all the inputs, storing validation errors in an array, using the field name as the array index. after the end of all the validation code, if the array holding the errors is empty, use the submitted form data. after using the submitted form date (which could cause user/validation errors in itself), if there are no errors, execute a redirect to the exact same url of the current page to cause a get request for that page. if you want to display a one-time success message, store it in a session variable, then test, display, and clear that session variable at the appropriate location in the html document. to allow the user to go to a different page, provide navigation links. if there are errors at step #6, the code would continue on to display the html document, where you would test and display the contents of the array holding the errors, then display the form, populating the form field values with any existing data. apply htmlentities to any values you output on a web page to help prevent cross site scripting.
    1 point
  38. You'll find that serializing data it not used very much these days, largely abandoned in favour of JSON data $data = [ 'count' => 1, 'total' => 5, 'average' => 5 ]; echo "Serialized: " . serialize($data); echo "JSON: " . json_encode($data);; gives Serialized: a:3:{s:5:"count";i:1;s:5:"total";i:5;s:7:"average";i:5;} JSON: {"count":1,"total":5,"average":5}
    1 point
  39. You should find another tutorial: the code they've convinced you to use is... well, it's silly. It pointlessly uses encryption for something that doesn't need to use encryption. If you want a remember me cookie then all you need is to store a long random token in your database and associate it with the user - preferably in one-to-many form so the user can have multiple tokens for multiple devices. Store it in the browser with the Secure and HttpOnly flags. Then, every time the token is used to log someone in, you generate a new token and replace the old one.
    1 point
  40. Why build the json data manually??? $json_data = json_encode($result); AS for the rest of the code, without knowing your db structure and gantt api input requirements there is no way I can suggest a better route.
    1 point
  41. @gizmola - Got everything fixed - had to better define DocumentRoot path for both. I appreciate your continued support.
    1 point
  42. For completeness, my processing would be if ($_SERVER['REQUEST_METHOD']=='POST') { try { $db->beginTransaction(); $stmt1 = $db->prepare("DELETE FROM user_transport WHERE user_id = ? "); $stmt1->execute( [ $_POST['uid'] ] ); if (isset($_POST['trans'])) { $stmt2 = $db->prepare("INSERT INTO user_transport (user_id, trans_type) VALUES (?, ?) "); foreach ($_POST['trans'] as $tid) { $stmt2->execute( [ $_POST['uid'], $tid ] ); } } $db->commit(); } catch(PDOException $e) { $db->rollBack(); throw $e; } header("Refresh: 0"); exit; } $res = $db->query("SELECT u.user_id , u.fname , u.lname , tt.description , tt.trans_type , CASE WHEN ut.user_id IS NULL THEN 0 ELSE 1 END AS checked FROM user_demo u CROSS JOIN transport_type tt LEFT JOIN user_transport ut ON u.user_id = ut.user_id AND tt.trans_type = ut.trans_type ORDER BY lname, trans_type "); $data = []; // store results in a conveniently structured array foreach ($res as $r) { if (!isset($data[$r['user_id']])) { $data[$r['user_id']] = [ 'name' => "{$r['fname']} {$r['lname']}", 'trans' => [] ]; } $data[$r['user_id']]['trans'][$r['trans_type']] = ['desc' => $r['description'], 'check' => $r['checked']]; } // echo '<pre>' . print_r($data, 1) . '</pre>'; # view array structure ?> <!DOCTYPE html> <html lang='en'> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="generator" content="PhpED 19.5 (Build 19523, 64bit)"> <title>Example</title> <meta name="author" content="Barand"> <meta name="creation-date" content="04/09/2022"> <style type='text/css'> table { border-collapse: collapse; margin: 20px auto; width: 60%; } td, th { padding: 8px; } </style> </head> <body> <table border='1'> <tr> <th>Name</th> <th>Transport types</th> <th>&nbsp;</th> </tr> <?php // output the array foreach ($data as $uid => $udata) { echo "<tr> <form method='post'> <td>{$udata['name']}</td> <td>"; foreach ($udata['trans'] as $ttype => $tdata) { $chk = $tdata['check'] ? 'checked' : ''; echo "<label><input type='checkbox' name='trans[]' value='$ttype' $chk>{$tdata['desc']}</label><br>"; } echo "</td> <td> <input type='hidden' name='uid' value='$uid'> <input type='submit' value='Update'> </td> </form> </tr> "; } ?> </table> </body> </html> Results
    1 point
  43. So we have established that my suspicion was correct. You have a problem with a commercial product that we have no way of looking at. It does seem that this is related to an "attachment" processing addon, but I could also be wrong about that. Either way, without the actual source, or access to your server, there isn't some magical generic fix that is going to make things work. The stack dump you attached should be looked at in reverse. So the first item was the last method run. It was running the getEditorData() method in the Attachment class, and something the code is doing at around line 1752 triggered the exception. The message indicates that there is a "handler" architecture involved, and whatever is being read has the "post" content type, which is likely some internal classification of data inside the application/database. The code is expecting there to be a handler (ie. some code that will be able to figure out what to do next) and the forum software is not finding any handler that's been registered within the application to be able to process further, so it throws the exception and exits. This is why I suspect that the old forum might have been using some sort of plugin, and possibly your issue is that you don't have that plugin installed and configured with whatever Xenforo installation you have now. Also as I stated in my prior message, the forum version and PHP version you are running could very well be at the heart of the problem, as it's possible if you are running an older version of their forum software, that there are techniques and syntax that don't work anymore with a more current version of PHP, or as I surmised, there could also be a plugin missing. I don't think there's anything more I can suggest for you, other than to seek help on the xenforo and Xfrocks communities. I hope this helps you
    1 point
  44. Where's the part of your post where you describe the problem?
    1 point
  45. https://www.google.com/search?q=site%3Aforums.phpfreaks.com+css+wrapper+container+width+height ?
    1 point
  46. Then array_chunk won't be quite as helpful: it'll create 3 chunks of the same size and 1 of a remainder. I can't think of an easier way of doing this than creating your own chunks: <?php const COLUMNS = 4; $items = range(1, 98); $count = count($items); $base = floor($count / COLUMNS); // 24 $remainder = $count % COLUMNS; // 2 // so $base * COLUMNS + $remainder == $count $chunks = []; for ($start = 0; $start < $count; ) { // the base amount, plus one if there are any remainder to include $length = $base + ($remainder-- > 0 ? 1 : 0); $chunks[] = array_slice($items, $start, $length); $start += $length; } print_r($chunks); // [1-25, 26-50, 51-74, 75-98]
    1 point
  47. $data is an array with one element that is an array. That array has a lot of elements including the one you say you want. So try: <?php foreach ($data[0]['lastData'] as $key => $key_value) { echo "key: $key, value: $key_value <br>"; } Once you have figured out which keys you actually want, you should be able to access them more directly. So for example: echo "<p>Temperature (F): {$data[0]['lastData']['tempinf']}</p>"; echo "<p>Wind (mph): {$data[0]['lastData']['windspeedmph']}</p>"; I don't see a min/max temp value in the data you provided. Aside from 'lastData', there are several other keys and nested arrays in some cases. For figuring this out in the future, aside from var_dump, print_r is often a useful development/debugging function that can be used as an alternative.
    1 point
  48. I figured this out. The problem was not with the at command, the user www-data did not have permissions to create the directory. This is resolved.
    1 point
  49. First off, I understand what you are looking for, and it is in no way unusual to want to have instrumentation and information about what is happening. There are many products out there, first and foremost Google Analytics. There are also log "mining/reporting" systems available. Awstats is one of them, but it's pretty old and I haven't used it in a long time. I'm not sure how functional and up to date it is. Here's a partial Google list of "alternatives to Awstats": Dynatrace. LogicMonitor. New Relic One. Datadog. Sumo Logic. Graylog. LogDNA. Apache log4j. Of these I've used New Relic, and Sumo Logic in the recent past, so it just goes to show you the many commercial and non-commercial offerings in this space. One thing you sometimes need to do, to get the level of information you want, is to modify the web server log format, and sometimes to inject additional variables into the logs. Things like session id's and cookies can be added to the logs to help establish things that can't be surmised otherwise. The details of doing this are an aspect of system administration that depend on your specific webserver and hosting environment. One specific example, would be the IP address of the request. If your server has a load balancer in front of it, the IP address of all requests will be the load balancer, and not the actual client IP, so that is an example of where you need to customize the logs in order to see what is actually going on. There are many many products and companies out there that offer logging infrastructure. One I've used in the past, not just for webservers, but for analysis of an entire cluster is Splunk. With that said, Splunk is a pricey commercial option. One FOSS stack that has a lot of mindshare and users is the ELK Stack, which consists of a setup of Elastic Search, Logstash and Kibana. Each piece of that stack solves a particular part of the problem that companies with sometimes large and complicated infrastructures face in getting server side analytics. You can do some reading about it here: https://logz.io/learn/complete-guide-elk-stack/ This might be the type of server based analytics system you want, and is modern, scalable and far more functional than a simple log parser/web reports system like AWStats. Most companies use multiple different options, as each tends to have a strength and a weakness. Google Analytics has a lot of features, but of course, it depends on the client running its javascript, and thus isn't ever going to show you requests that were still processed but didn't load javascript. If there are errors or bugs in the javascript on the page, this might cause GA not to log correctly or at all. Still you want to configure and start using GA with your site, and you will find it already gives you a lot of the functionality you want, without you having to do anything within your infrastructure. In my experience companies often use a variety of different tools. Sometimes, just looking at web logs is not enough, or doesn't really help you understand something, and you need logs of multiple different services. You might need to look at graphs of webserver(s) and your database for example, to see that a problem your system was having was related to database load at a particular time, which was in turn related to some slow queries that were running tying up the database resources for a long period of time. Resources on the server itself, like available memory, amount of swap being used, and cpu load, might show you that your server is overloaded or low on disk space. There are different types of logging and monitoring you can setup, that can often provide valuable insights into issues you will never find just looking at web logs.
    1 point
This leaderboard is set to New York/GMT-05: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.