Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation since 06/27/2015 in all areas

  1. Something like this? CODE <?php include 'db_inc.php'; // YOUR CONNECTION $pdo = pdoConnect('movies'); // CODE GOES HERE ################################################################################ ## PROCESS AJAX REQUESTS ################################################################################ if (isset($_GET['ajax'])) { $res = $pdo->prepare("SELECT m.id as movie_id , m.title , m.image , g.description as genre , CONCAT(m.running_time DIV 60, ' hrs ', m.running_time % 60, ' mins') as running_time , date_format(sg.screen_on, '%W, %D %b') as date , s.name as screen_num , TIME_FORMAT(sg.screen_at, '%H:%i') as start_time FROM screening sg JOIN screen s ON sg.screen_id = s.id JOIN movie m ON sg.movie_id = m.id JOIN genre g ON g.id = m.genre WHERE dayname(screen_on) = :day ORDER BY movie_id, screen_on, sg.screen_at "); $res->execute([ 'day' => $_GET['day'] ]); $data = []; # # Put data into an array with same structure a required output # - array of movies, each movie having arrays of screenings # foreach ($res as $r) { if (!isset($data[$r['movie_id']])) { $data[$r['movie_id']] = [ 'title' => $r['title'], 'image' => $r['image'], 'genre' => $r['genre'], 'runtime' => $r['running_time'], 'screenings' => [] ]; } $data[$r['movie_id']]['screenings'][$r['date']][] = ['start' => $r['start_time'], 'sno' => $r['screen_num'] ]; } exit(json_encode($data)); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta name="generator" content="PhpED 12.0 (Build 12010, 64bit)"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>olumide</title> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type='text/javascript'> function showScreenings(day) { $("#movie-listings").html("") $.get( "", {"ajax":1, "day":day}, function(resp) { $.each(resp, function(mid, mdata) { let title = `<h2>${mdata.title}</h2><h4 class='w3-text-gray'>${mdata.genre} (${mdata.runtime})</h4>` $("#movie-listings").append(title) $.each(mdata.screenings, function(dt, ddata) { let datesub = `<h3>${dt}</h3>` $("#movie-listings").append(datesub) $("#movie-listings").append("<div class='screenings'") $.each(ddata, function(k, sdata) { let scr = `<div class='screening'><b>${sdata.start}</b><br>${sdata.sno}</div>` $("#movie-listings").append(scr) }) $("#movie-listings").append("</div>") }) }) }, "JSON" ) } </script> <style type='text/css'> .days { padding: 16px; text-align: center; } .screening { width : 20%; display: inline-block; margin-right: 16px; margin-bottom: 8px; padding: 4px; border: 5px solid black; font-size: 9pt; } </style> </head> <body> <nav class="days"> <button onclick="showScreenings('Monday')">Monday</button> <button onclick="showScreenings('Tuesday')">Tuesday</button> <button onclick="showScreenings('Wednesday')">Wednesday</button> <button onclick="showScreenings('Thursday')">Thursday</button> <button onclick="showScreenings('Friday')">Friday</button> <button onclick="showScreenings('Saturday')">Saturday</button> <button onclick="showScreenings('Sunday')">Sunday</button> </nav> <div id='movie-listings'class='w3-content w3-padding w3-card-4'> <!-- LISTINGS GO HERE --> </div> </body> </html>
    3 points
  2. I guess you don't understand that phpfreaks is a free site, with expert help provided by volunteers. Given the fact that everyone is donating their time and expertise to try and help people like yourself, the argument that you host a free site with source code you got from somewhere else for free, means you shouldn't ever have to learn anything (which can be learned in a few hours) will not get you much sympathy here.
    3 points
  3. By far the best the best way is to fix whatever they are warning you about.
    3 points
  4. @HawkeNN I want to clarify some things for you. Most code that was written for PHP 7.x will still run fine under php 8. For the most part PHP 8 added new features. There are "Breaking Changes" that were made, listed here: https://www.php.net/manual/en/migration80.incompatible.php but it is unlikely that is the problem with your code from some of the errors I saw listed. For example, the "headers already sent" error is a common one and has been around since php 3 at least. It has to do with code that sends output to the browser (as in the case of a script that intermixes HTML and php) and then tries to set HTTP header values. At that point, the HTTP request has already been sent with whatever headers it had, and it's too late to add or modify them. PHP session use is one function that sets header values because it sets a cookie. Some of the advice that you got is related to common techniques for trying to solve the issue. Equally important is your hosting configuration for PHP. Changes to the configuration of PHP from a version upgrade, can turn on settings that might have been off previously, or warnings being emitted that weren't before. This can then trigger output which also causes the "headers already sent" message. I suspect that this is part of your problem here, and really requires some debugging of your hosting setup. This was already brought up to you, in that there will be a php.ini (and often other assorted xyz.ini files that are included by the main php.ini) where settings can be made or changed to re-configure php. In conclusion, this is a PHP developer forum. From looking at this thread, you aren't likely to have a good outcome here, because you aren't a php developer. My sincere advice is to just find yourself a developer (this forum is chock full of them) you can pay a fee to, in order to resolve your issues and get your site working again. We have established that the code is bad, and that there is likely a few different things going on that are somewhere between the configuration of your server to possible improvements to the code you have. In other words, this is a problem for an experienced developer that requires debugging. I probably shouldn't say this, but my knee jerk reaction is that getting your code to work is not that big of a job, but looking at a thread like this is frustrating to read, because in my experience it is not going anywhere. There isn't any long term value to it for our forum, and you are not going to become an active member of the forum, nor learn PHP development, so there is nothing in it for us, or the community at large.
    3 points
  5. 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
  6. 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
  7. If you are outputting an image from a DB blob field, then here's an example... // EMULATE DATA FROM THE DATABASE $type = 'image/png'; $comments = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.'; $image_data = file_get_contents('images/snowman.PNG'); // OUTPUT THE DATA echo "<div style='width:396;'> <img src='data:{$type};base64," . base64_encode( $image_data ) . "' width='394' height='393'> <p>$comments</p> "; RESULT
    3 points
  8. Don't use "SELECT * ". Specify the columns you want. This makes it easier for others, like me, to understand what is in the table and what the query is doing. Indent your code to show the nested structure of loops etc. If you had done those I might have given this problem more than a cursory glance. So you'll have to settle for a generic example of using a recursive function to give an indented list of parent/child elements. Also, Don't run queries inside loops. Use JOINs to get all the data in a single query THE DATA TABLE: category +----+---------+--------+ | id | name | parent | +----+---------+--------+ | 1 | happy | 0 | | 2 | comet | 0 | | 3 | grumpy | 0 | | 4 | prancer | 1 | | 5 | bashful | 1 | | 6 | dancer | 2 | | 7 | doc | 2 | | 8 | blitzen | 2 | | 9 | dasher | 3 | | 10 | donner | 1 | | 11 | vixen | 1 | | 12 | cupid | 8 | +----+---------+--------+ THE OUTPUT THE CODE <?php $sql = "SELECT id, name, parent FROM category"; $res = $db->query($sql); // // store arrays of items for each parent in an array // while (list($id, $name, $parent) = $res->fetch(PDO::FETCH_NUM)) { $data[$parent][] = array('id'=>$id, 'name'=>$name); } /** * recursive function to print a category then its child categories * * @param array $arr category data * @param int $parent parent category * @param int $level hierarchy level */ function displayHierarchy(&$arr, $parent, $level=0) { if (isset($arr[$parent])) { echo "<ul>\n"; foreach($arr[$parent] as $rec) { echo "<li class='li$level'>{$rec['name']}\n"; if (isset($arr[$rec['id']])) displayHierarchy($arr, $rec['id'], $level+1); echo "</li>\n"; } echo "</ul>\n"; } } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Example</title> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> </script> <style type="text/css"> body { font-family: verdana,sans-serif; font-size: 11pt; padding: 50px; } li { font-weight: 600;} .li0 { color: red; } .li1 { color: green; } .li2 { color: blue; } </style> </head> <body> <?php displayHierarchy($data, 0); ?> </body> </html>
    3 points
  9. Too many people are obsessed with "filtering" bad inputs. You don't have to "filter" anything. You don't have to remove HTML tags. You don't have to remove SQL keywords. You don't have to strip quotes or backslashes. All you have to do is make sure that whatever the user typed doesn't screw around with what you're trying to do. Want to put it into HTML? Make sure it doesn't screw around with your HTML. Want to put it into SQL? Make sure it doesn't screw around with your SQL. Want to send it in JSON? Make sure it doesn't screw around with your JSON. And every single one of those situations has a simple, single best-practice solution: HTML? Use htmlspecialchars with ENT_QUOTES* and the correct charset. SQL? Use prepared statements. JSON? Use json_encode. That's it. No filter_vars or filter_inputs, no strip_tags, no regular expressions, nothing stupid like that. User wants to look cool and type <script> tags into their forum post? Go ahead and let them, because it'll just show up as plain and simple text. Like it just did now. * Only actually required if you are putting the input into an single quote-delimited tag attribute. Using double quotes for your attributes? Not outputting into an HTML tag? Then you don't technically need ENT_QUOTES.
    3 points
  10. I enjoy the challenge when someone posts a problem I can get my teeth into.
    3 points
  11. People still use StackOverflow? That's only half a joke. Their community has always been toxic to newcomers and there's so much emphasis on correctness that anything less than perfect is unacceptable. And there's the hostility towards any form of discussion about what is right that I always mention when this subject comes up. SO is good when you're looking for a precise answer to a specific question, but it's terrible for actually asking the questions, or trying to weigh in as a new person with different answers. But I am glad they dethroned Expert Sex Change in search results. edit: If Your Common Sense/shrapnelcol came across this thread and decided they wanted to join our forum...
    3 points
  12. A few notes about text bounding boxes which, I hope, will help in precise placement of your text. Suppose I have the text string "The lazy fox" which I want to display using 150pt Vivaldi . My image is 4896 x 3672 and I want the text placed at the bottom right but 250 pixels from the edges of the image. $box = imagettfbbox(150,0,'c:/windows/fonts/vivaldii.ttf','The lazy fox'); gives this array of coordinates of the four corners $box = Array ( [0] => 23 [1] => 55 [2] => 871 [3] => 55 [4] => 871 [5] => -140 [6] => 23 [7] => -140 ) You may wonder why it can't just give a rectangle from (0,0) to (width, height) to make sizing simple, but there is extra information to be extracted from the array Text width = (871 - 23) = 848 Text height = 55 - (-140) = 195 The baseline will be 140px from the top The text is offset 23 px to the right. My text, therefore, will be in a rectangle 848 x 195 positioned 250 px from right and bottom edges. The top left x coord of the rectangle will be (4896 - 250 - 848) = 3798 and top left y coord will be (3672 - 250 - 195) = 3227. However, to land the text precisely into this area we position it on the baseline and at the required x offset, ie (3798 - 23 , 3227 + 140) = (3775, 3367). I use a simple custom function to assist with this process function metrics($font, $fsize, $str) { $box = imagettfbbox($fsize, 0, $font, $str); $ht = abs($box[5] - $box[1]); $wd = abs($box[4] - $box[0]); $base = -$box[5]; $tx = -$box[0]; return [ 'width' => $wd, 'height' => $ht, 'ascent' => $base, 'offsetx' => $tx ]; } $box = metrics ('c:/windows/fonts/vivaldii.ttf', 150, 'The lazy fox'); $box = Array ( [width] => 848 [height] => 195 [ascent] => 140 [offsetx] => -23 )
    3 points
  13. Don't use $GLOBALS. Forget it exists. There is never a good reason to use it. Pretend you never saw it.
    3 points
  14. +----------------+ +----------------+ | Make sure to |---+ +------->| (e.g. Courier) | +----------------+ | | +----------------+ | | | | +----------+ | | +->| use a |---+ | | +----------------+ +----------+ | | +------->| and use spaces | | | +----------------+ | +----------------+ | | +--->| monospace font |-----+ | +----------------+ | +----------+ | | not tabs |<----------+ +----------+ | +--------------------------------------------------------------------------+ | V +---------------+ | It also helps | +---------------+ | | | +-------------------+ +-------------------+ +------------------------>| if you sometimes |---------------------->| switch between | +-------------------+ +-------------------+ | | +-----------------+-----------------+ | | | | +-------------------+ +-------------------+ | overtype | | insert | +-------------------+ +-------------------+ | | | | | +----------+ | +----------=>| modes |<----------+ +----------+
    3 points
  15. The code in each switch is identical so all it achieves is to ensure the calculation uses only the defined list of diameter options. Just use an array of the valid values to verify the values. You can use the same array to generate the option list <?php $diam_vals = [2,3,4,6,8,10,12,14,16,18,20,22,24,26]; $results = ''; if ($_SERVER['REQUEST_METHOD']=='POST') { $x = $_POST['x'] ?? 0; $y = $_POST['y'] ?? 0; $diametre = $_POST['diametre'] ?? 0; if ($x > 0 && $y > 0 && in_array($diametre, $diam_vals)) { $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; $results .= "X = " . $x . "mm" . "<br/>"; $results .= "Y = " . $y . "mm" . "<br/>"; $results .= "Longueur = " . number_format($LongueurBayonette,1) . " mm" . "<br/>"; $results .= "&beta; = " . number_format($angle,1) . "°" . "<br/>"; $results .= "Rayon = " . $rayon . " mm" . "<br/>"; $results .= "&phi; = " . $diametre . '"' . "<br/>"; } else { $results = 'Inputs are not valid'; } } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Simplified Example</title> </head> <body> <form method="post" action=""> <fieldset> X: <input type="text" name="x" value="" /> <br/> Y: <input type="text" name="y" value="" /> <br/> Diametre: <select name="diametre"> <option value="0"> </option> <?php foreach ($diam_vals as $d) { echo "<option value='$d'>$d</option>\n" ; } ?> </select> <input type="submit" value = "Calculer" /> </fieldset> </form> <br> <?=$results?> Just curious - do you have a diagram of how those values relate to one another. It metions "rayon" and "bayonnette" so my guess is that it is some kind of laser rifle with attached bayonet (but I could be wrong) ?
    3 points
  16. Sorry to see your valuable time was wasted by Barand providing you free professional consulting, custom built code and hand holding. 😣
    2 points
  17. The only MyIsam-only functionality that I can think of is the ability to have a compound primary key EG PRIMARY KEY (year, number) where the 2nd part auto_increments within the first part, so if you have CREATE TABLE `test1` ( `year` int(11) NOT NULL, `number` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`year`,`number`) ) ENGINE=MyISAM ; mysql> select * from test1; +------+--------+ | year | number | +------+--------+ | 2022 | 1 | | 2022 | 2 | +------+--------+ mysql> insert into test1 (year) values (2022), (2022), (2023), (2023), (2024); mysql> select * from test1; +------+--------+ | year | number | +------+--------+ | 2022 | 1 | | 2022 | 2 | | 2022 | 3 | | 2022 | 4 | | 2023 | 1 | | 2023 | 2 | | 2024 | 1 | +------+--------+
    2 points
  18. I've never used it personally but I've heard good things about rector.
    2 points
  19. password_hash() and password_verify()
    2 points
  20. Alternatively, assuming they all have same rigid structure, ... $fp = file('weather.html', FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES); $data = []; foreach ($fp as $line) { switch (substr($line, 0, 4)) { case '<!--' : if ($line[4]!=' ') { $section = substr($line, 4, -8); } break; case '<td>' : list($name, $value) = getData($line); $data[$section][$name] = $value; break; default : continue 2; } } function getData($line) { $l = substr($line, 4, -5); return explode('</td><td>', $l); } // View the results echo '<pre>' . print_r($data, 1) . '</pre>'; giving ... $data = Array ( [MISCELLANEOUS] => Array ( [Name of Station] => AzureCove [City (from NOAA Setup)] => Garden City [State (from NOAA Setup)] => Utah [Elevation (from NOAA Setup)] => 5954 ft [Latitude (from NOAA Setup)] => 41° 56' 12" N [Longitude (from NOAA Setup)] => 111° 23' 20" W [Date on the PC] => 03/13/23 [Time on the PC] => 4:06a [UTC Time] => 10:06a [UTC Date] => 03/13/23 [Date on the Station] => 03/13/23 [Time on the Station] => 4:05a [Sunrise Time] => 7:41a [Sunset Time] => 7:30p [Current Weather Forecast *] => Partly cloudy with little temperature change. [Current Moon Phase] => Last Quarter [EMC] => --- [EMC Unit] => % [Air Density] => 0.0842 [Air Density Unit] => lb/cu.ft ) [INSIDE TEMPERATURE] => Array ( [Inside Temperature] => 42.5 [High Inside Temperature] => 43.6 [Time of High Inside Temperature] => 12:00a [Low Inside Temperature] => 42.5 [Time of Low Inside Temperature] => 3:41a [High Monthly Inside Temperature] => 45.4 [Low Monthly Inside Temperature] => 39.4 [High Yearly Inside Temperature] => 45.7 [Low Yearly Inside Temperature] => 39.4 ) [OUTSIDE TEMPERATURE] => Array ( [Outside Temperature] => 15.1 [High Outside Temperature] => 21.7 [Low Outside Temperature] => 15.1 [Time of High Outside Temperature] => 12:00a [Time of Low Outside Temperature] => 4:04a [High monthly Outside Temperature] => 46.1 [Low monthly Outside Temperature] => -11.3 [High yearly Outside Temperature] => 46.1 [Low yearly Outside Temperature] => -12.5 ) . . . )
    2 points
  21. Keep track of whether or not you've sent the count request, and only send it if you haven't. $('audio').on("play", function(){ let requestSent = false return function(){ if (requestSent){ return; } requestSent = true; let a_id = $(this).attr("id"); $.ajax({ url: "count-play.php?id=" + a_id , success: function(result){ $("."+ a_id + "count").html(result); } }); }; }()); The first time the event fires, requestSent will be false so the ajax call will run and record the play event and requestSent will be set to true. Later events will see that requestSent is true and immediately return thus doing nothing.
    2 points
  22. 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
  23. 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
  24. 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
  25. 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
  26. Apparently the DateInterval class supports milliseconds, but the default method does not support it as an input value. You need to instead use the createFromDateString class of that method // convert your date to DateTime object $date = '10:00:00.500000'; $dt = new DateTime($date); // convert your period to $interval = '00:25:10.300000'; //Extract time parts list($hours, $minutes, $totalSeconds) = explode(':', $interval); list($wholeSeconds, $milliSeconds) = explode('.', $totalSeconds); //Create interval with milliseconds $intervalString = "{$hours} hours + {$minutes} minutes + {$wholeSeconds} seconds + {$milliSeconds} microseconds"; $interval = DateInterval::createFromDateString($intervalString); // Add interval to date $dt->add($interval);// Format date as you needecho $dt->format('H:i:s'); echo $dt->format('Y-m-d\TH:i:s.u'); //Output: 2021-11-12T10:25:10.800000
    2 points
  27. Or avoid the concatenation which is usually the biggest source of error (and the query string needs an "=") echo "<a href='icerik.php?icerik={$goster['icerik_id']}'>{$goster['baslik']}</a>";
    2 points
  28. I was in my fifties when I first came across something called HTML. I knew Basic from from my days with a BBC home microcomputer so I started using Visual Basic to create web pages. Daily, I would log in to the Compuserve Bulletin Board using my dial-up modem to exchange ideas (much like now - plus ca change, plus ca meme). I started to write Java applets to enhance my pages but, no sooner had I started to become reasonably proficient, the world switched to Flash (which has since died a death). Disheartened, I let the Java lapse. One of the biggest mistakes I've made as today's phone apps are essentially Java applets. A year or so later I came across PHP and much prefered its Java/C type syntax to Basic. My preference was cemented when I discovered that rewriting my VB/ASP scripts in PHP gave me a 3x+ speed increase (in one case a 70x increase in performance as VB was crap at handling long string concatenations). Anyway, the moral is "You ain't too old".
    2 points
  29. This fails $j = "{'admin': 1, 'moderator': 1}" ; $a = json_decode($j, 1); echo '<pre> a ' . print_r($a, 1) . '</pre>'; This works $j = '{"admin": 1, "moderator": 1}' ; $b = json_decode($j, 1); echo '<pre> b ' . print_r($b, 1) . '</pre>'; Note the quotes in the JSON string.
    2 points
  30. Doesn't your console have a "preserve" option? Or, add "return false" to the end of your submitData() function to stop the page refreshing
    2 points
  31. In case anyone comes here and wants to know what the answer was, since that wasn't shared, Problem 1 - phpunit/phpunit[9.3.3, ..., 9.5.x-dev] require ext-dom * -> it is missing from your system. Install or enable PHP's dom extension. - Root composer.json requires phpunit/phpunit ^9.3.3 -> satisfiable by phpunit/phpunit[9.3.3, ..., 9.5.x-dev]. phpunit requires ext-dom (aka the DOM extension) but apparently it's missing. Install it.
    2 points
  32. less... $matched = array_intersect_key($all, array_flip($referred_by_Affiliate));
    2 points
  33. There is a very easy way to do this using a MySql myisam table. Store each vote in a table like this... CREATE TABLE `vote` ( `username` varchar(50) NOT NULL, `vote_year` year(4) NOT NULL, `week_num` tinyint(4) NOT NULL, `vote_count` int(11) NOT NULL AUTO_INCREMENT, `time_voted` datetime DEFAULT CURRENT_TIMESTAMP, `voted_for` int(11) DEFAULT NULL COMMENT 'Who/whatever was voted for', PRIMARY KEY (`username`,`vote_year`,`week_num`,`vote_count`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; Note the last column of the primary key is the auto-increment column "vote_count". This will make the vote count start again at 1 for each username each week whe you add votes. mysql> INSERT INTO vote (username, vote_year, week_num, voted_for) VALUES -> ('user1', year(curdate()), weekofyear(curdate()), 1), -> ('user1', year(curdate()), weekofyear(curdate()), 20), -> ('user1', year(curdate()), weekofyear(curdate()), 5), -> ('user2', year(curdate()), weekofyear(curdate()), 5), -> ('user2', year(curdate()), weekofyear(curdate()), 1), -> ('user2', year(curdate()), weekofyear(curdate()), 3); Query OK, 6 rows affected (0.00 sec) mysql> select * from vote; +----------+-----------+----------+------------+---------------------+-----------+ | username | vote_year | week_num | vote_count | time_voted | voted_for | +----------+-----------+----------+------------+---------------------+-----------+ | user1 | 2021 | 24 | 1 | 2021-06-16 17:37:56 | 1 | | user1 | 2021 | 24 | 2 | 2021-06-16 17:37:56 | 20 | | user1 | 2021 | 24 | 3 | 2021-06-16 17:37:56 | 5 | | user2 | 2021 | 24 | 1 | 2021-06-16 17:37:56 | 5 | | user2 | 2021 | 24 | 2 | 2021-06-16 17:37:56 | 1 | | user2 | 2021 | 24 | 3 | 2021-06-16 17:37:56 | 3 | +----------+-----------+----------+------------+---------------------+-----------+ 6 rows in set (0.00 sec) To do the insert in PHP $stmt = $pdo->prepare("INSERT INTO vote (username, vote_year, week_num, voted_for) VALUES ( ?, year(curdate()), weekofyear(curdate()), ? ) "); $stmt->execute( [ $username, $votedFor ] ); Now it doesn't matter how many times a user votes. When you come to counting the votes for each "voted_for" just ignore all records whose vote_count is > 10 SELECT voted_for , count(*) as votes FROM vote WHERE vote_count <= 10 GROUP BY voted_for ORDER BY votes DESC
    2 points
  34. I'll eat my words. I couldn't resist the challenge so, having slept on it, I wrote a an SQL function "isConsecutive(dates)" to find records where there are fewer than 10 dates and they are consecutive. TEST DATA and QUERY TABLE: ahtest +----+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | id | adates | +----+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | 1 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00 | | 2 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-08 12:00,2021-04-10 12:00,2021-04-11 12:00,2021-04-12 12:00,2021-04-13 12:00,2021-04-14 12:00 | | 3 | 2021-04-01 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00,2021-04-10 12:00,2021-04-11 12:00,2021-04-12 12:00 | | 4 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00,2021-04-10 12:00,2021-04-11 12:00 | | 5 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00,2021-04-09 12:00,2021-04-11 12:00,2021-04-12 12:00,2021-04-13 12:00 | | 6 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00,2021-04-09 12:00 | | 7 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-06 12:00,2021-04-08 12:00,2021-04-09 12:00,2021-04-11 12:00,2021-04-12 12:00,2021-04-13 12:00 | | 8 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00 | | 9 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00,2021-04-09 12:00,2021-04-11 12:00,2021-04-13 12:00,2021-04-15 12:00 | | 10 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-08 12:00,2021-04-09 12:00,2021-04-10 12:00,2021-04-11 12:00,2021-04-13 12:00,2021-04-14 12:00 | | 11 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-04 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00,2021-04-09 12:00,2021-04-10 12:00,2021-04-11 12:00,2021-04-12 12:00,2021-04-13 12:00,2021-04-14 12:00 | | 12 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-09 12:00,2021-04-10 12:00,2021-04-11 12:00,2021-04-12 12:00 | | 13 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00,2021-04-09 12:00,2021-04-10 12:00,2021-04-11 12:00,2021-04-13 12:00 | | 14 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00 | | 15 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00,2021-04-09 12:00,2021-04-10 12:00,2021-04-11 12:00 | | 16 | 2021-04-01 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00,2021-04-10 12:00,2021-04-11 12:00 | | 17 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00,2021-04-09 12:00,2021-04-10 12:00,2021-04-11 12:00 | | 18 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00 | | 19 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00,2021-04-10 12:00 | | 20 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-06 12:00,2021-04-08 12:00,2021-04-10 12:00,2021-04-11 12:00,2021-04-12 12:00,2021-04-13 12:00,2021-04-14 12:00,2021-04-15 12:00 | +----+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ mysql> SELECT id -> , adates -> FROM ahtest -> WHERE isConsecutive(adates); +----+-----------------------------------------------------------------------------------------------------------------------------------------+ | id | adates | +----+-----------------------------------------------------------------------------------------------------------------------------------------+ | 1 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00 | | 8 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00 | | 14 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00 | | 18 | 2021-04-01 12:00,2021-04-02 12:00,2021-04-03 12:00,2021-04-04 12:00,2021-04-05 12:00,2021-04-06 12:00,2021-04-07 12:00,2021-04-08 12:00 | +----+-----------------------------------------------------------------------------------------------------------------------------------------+ THE FUNCTION DELIMITER $$ CREATE FUNCTION `isConsecutive`(dates varchar(255)) RETURNS int(11) BEGIN DECLARE k INTEGER DEFAULT 1; DECLARE da DATE DEFAULT SUBSTRING_INDEX(dates, ',', 1); DECLARE db DATE ; DECLARE num INTEGER DEFAULT (LENGTH(dates)+1) DIV 17; DECLARE strx VARCHAR(255) DEFAULT SUBSTRING_INDEX(dates, ',', -(num-k)); DECLARE isconsec INTEGER DEFAULT 1; IF num >= 10 THEN RETURN 0; END IF; WHILE LENGTH(strx) > 0 DO SET db = SUBSTRING_INDEX(strx, ',', 1); if DATEDIFF(db, da) <> 1 THEN SET isconsec = 0; END IF; SET k = k + 1; SET da = SUBSTRING_INDEX(strx, ',', 1); SET strx = SUBSTRING_INDEX(strx, ',', -(num-k)); END WHILE; RETURN isconsec; END$$ DELIMITER ;
    2 points
  35. try foreach ($array as $k => $d) { if ($k > 0) { if (strtotime($d) > strtotime($array[$k-1])+6) { $new[] = "-------------------"; } } $new[] = $d; } $new = Array ( [0] => 2021-02-10 09:04:48 [1] => 2021-02-10 09:04:54 [2] => 2021-02-10 09:05:00 [3] => 2021-02-10 09:05:06 [4] => 2021-02-10 09:05:12 [5] => 2021-02-10 09:05:18 [6] => ------------------- [7] => 2021-02-10 09:06:18 [8] => 2021-02-10 09:06:24 ) [edit...] Alternative solution... $new = []; $newkey = 0; foreach ($array as $k => $d) { if ($k > 0) { if (strtotime($d) > strtotime($array[$k-1])+6) { $newkey++; } } $new[$newkey][] = $d; } gives $new = Array ( [0] => Array ( [0] => 2021-02-10 09:04:48 [1] => 2021-02-10 09:04:54 [2] => 2021-02-10 09:05:00 [3] => 2021-02-10 09:05:06 [4] => 2021-02-10 09:05:12 [5] => 2021-02-10 09:05:18 ) [1] => Array ( [0] => 2021-02-10 09:06:18 [1] => 2021-02-10 09:06:24 ) )
    2 points
  36. Sort the array first. Assuming you start with ... $options = [ [ 'type' => 'Visual disability', 'name' => 'Audio-described cut-scenes' ], [ 'type' => 'Visual disability', 'name' => 'Highlighted path to follow' ], [ 'type' => 'Physical disability', 'name' => 'Sensitivity settings for all the controls' ], [ 'type' => 'Visual disability', 'name' => 'Screen readers on menus' ], [ 'type' => 'Visual disability', 'name' => 'Slow down the game speed' ], ]; then ... # # Sort the array by type (descending) # usort($options, function($a, $b) { return $b['type'] <=> $a['type']; }); # # process the array # $prev_type = ''; // store previous type echo "<ul>\n"; foreach ($options as $opt) { if ($opt['type'] != $prev_type) { // is this a new type? if ($prev_type != '') { // was there a previous one? echo "</ul>\n</li>\n"; // if so, close it } echo "<li>{$opt['type']}\n<ul>\n"; $prev_type = $opt['type']; // store as previous value } echo "<li>{$opt['name']}</li>\n"; } // close last group echo "</ul>\n</li>\n"; // close whole list echo "</ul>\n"; giving ... <ul> <li>Visual disability <ul> <li>Audio-described cut-scenes</li> <li>Highlighted path to follow</li> <li>Screen readers on menus</li> <li>Slow down the game speed</li> </ul> </li> <li>Physical disability <ul> <li>Sensitivity settings for all the controls</li> </ul> </li> </ul> An alternative approach is to reorganise the array using subarrays for each type... $options = [ 'Visual disability' => [ 'Audio-described cut-scenes', 'Highlighted path to follow', 'Screen readers on menus', 'Slow down the game speed' ], 'Physical disability' => [ 'Sensitivity settings for all the controls' ] ]; then use two nested foreach() loops.
    2 points
  37. That's why I laid it out the way I did with the comments - so it would be easy for you get the separate feet/inches values if you still wanted to go that way. [edit] Look more closely at my code - you require two substring_index()s to extract the inches. The inner to get the string before the final " and the outer one to get the string after the ' SET feet = substring_index(@height, '\'', 1) * 12 , inches = substring_index(substring_index(@height, '"', 1), '\'', -1)
    2 points
  38. if ($success) { $_SESSION["userLoggedIn"] = $username; header("Location:index.php"); }else{ $error = $account->getError(Constants::$registerFailed); } It's a good practice to use an exit after the header ("Location ...
    2 points
  39. Short answer: it's safe. Longer answer: it's as safe as any other PHP file on your server. It's a common practice to put this script, or at least a script that defines variables/constants with database credentials, in a PHP file that is not located inside the web root (eg, outside of your public_html or www or whatever directory that your site is based in) because if it's not an actual page then it really shouldn't be in the root; this practice is easy to achieve when you get larger sites that have a single public_html/index.php that runs an "application" or some similar concept whose files are all outside the root.
    2 points
  40. I created an extra table to define which category the values were in mysql> select * from catval; +-----+------+ | val | cat | +-----+------+ | 1 | 4 | | 2 | 4 | | 3 | 4 | | 4 | 4 | | 5 | 3 | | 6 | 3 | | 7 | 2 | | 8 | 2 | | 9 | 1 | | 10 | 1 | +-----+------+ then $sql = "SELECT a.cat as cata , b.cat as catb FROM datatb d JOIN catval a ON d.grpa = a.val JOIN catval b ON d.grpb = b.val "; $result = $db->query($sql); //categories $cat = [ 4 => ['name'=>'1:4', 'recs'=>[]], 3 => ['name'=>'5:6', 'recs'=>[]], 2 => ['name'=>'7:8', 'recs'=>[]], 1 => ['name'=>'9:10','recs'=>[]] ]; $n = 0; while ($row = $result->fetch_assoc()) { $cat[$row['cata']]['recs'][$n][] = $row['cata']; $cat[$row['catb']]['recs'][$n][] = $row['catb']; $n++; } // the output echo "<table border='1' style='width:500px; border-collapse:collapse;'>"; foreach ($cat as $c) { echo "<tr><th>{$c['name']}</th>"; for ($i=0; $i<$n; $i++) { echo '<td style="text-align:center;">' . (isset($c['recs'][$i]) ? join(',', $c['recs'][$i]) : '&ndash;') . "</td>"; } echo "</tr>\n"; } echo "</table>\n";
    2 points
  41. $q = 'SELECT ID FROM table'; That is a SQL query. You have to run that query through your database, receive the results, and then look for each single matching image in the directory for every returned record. You can probably skip looking in the directory, though. It will only tell you if the file exists. So if you already know (or assume) the file exists then you don't need to bother looking.
    2 points
  42. Unlikely Quotes need removing... $query = "UPDATE `greencard` SET `comments`= '$comments', 'sent' = '$sent' WHERE `hospitalnumber`= '$hospitalnumber' and `PIN`= '$PIN'"; ^ ^ and it's easier just to use ... sent = NOW() WHERE ...
    2 points
  43. Why are you even attempting to store that duration. You can get it any time you need it with a query. Rule of DB design - don't store derived data. If you really insist on storing it, why do need two queries? UPDATE attendance_records SET duration = timediff(...) WHERE ... - a single update would do the job
    2 points
  44. Not sure I would call a registration and login system less complex than threads and posts, but I guess it depends... I suggest you take a look at MariaDB's knowledge base section on database theory.
    2 points
  45. Christmas has come early! <?php const IMGDIR = 'images/'; const THUMBDIR = 'thumbs/'; const THUMBSIZE = 150; // max thumbnail dimension const NUM = 100; // number of images to be processed on each run $images = glob(IMGDIR.'{*.png,*.jpg}', GLOB_BRACE); $thumbs = glob(THUMBDIR.'{*.png,*.jpg}', GLOB_BRACE); // reduce to basenames only $images = array_map('basename', $images); $thumbs = array_map('basename', $thumbs); // copy the next NUM images to $todo list where thumbnails do not yet exist $todo = array_slice(array_diff($images, $thumbs), 0, NUM); $output = ''; foreach ($todo as $fn) { $sz = getimagesize(IMGDIR.$fn); if ($sz[0] == 0) continue; // not an image $ok = 0; $out = null; switch ($sz['mime']) { // check the mime types case 'image/jpeg': $im = imagecreatefromjpeg(IMGDIR.$fn); $ok = $im; $out = 'imagejpeg'; break; case 'image/png': $im = imagecreatefrompng(IMGDIR.$fn); $ok = $im; $out = 'imagepng'; break; default: $ok = 0; } if (!$ok) continue; // not png or jpg // calculate thumbnail dimensions if ($sz[0] >= $sz[1]) { // landscape $w = THUMBSIZE; $h = THUMBSIZE * $sz[1]/$sz[0]; } else { // portrait $h = THUMBSIZE; $w = THUMBSIZE * $sz[0]/$sz[1]; } // copy and resize the image $tim = imagecreatetruecolor(THUMBSIZE, THUMBSIZE); $bg = imagecolorallocatealpha($tim,0xFF,0xFF,0xFF,127); imagefill($tim, 0, 0, $bg); imagecolortransparent($tim, $bg); // centre the image in the 150 pixel square $dx = (THUMBSIZE - $w) / 2; $dy = (THUMBSIZE - $h) / 2; imagecopyresized($tim, $im, $dx, $dy, 0, 0, $w, $h, $sz[0], $sz[1]); imagesavealpha($tim, true); $out($tim, THUMBDIR.$fn); imagedestroy($im); imagedestroy($tim); $output .= "<img src='".THUMBDIR."$fn' alt='$fn'>\n"; } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="content-language" content="en"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Create Thumbnails</title> <meta name="author" content="Barry Andrew"> <meta name="creation-date" content="10/09/2019"> <style type="text/css"> body { font-family: verdana, sans-serif; font-size: 11pt; } header { background-color: black; color: white; padding: 15px 10px;} img { margin: 5px; } </style> </head> <body> <header> <h1>New Thumbnail Images</h1> </header> <?=$output?> </body> </html>
    2 points
  46. $numbers = array(1,3,7,8,10,13); $max = max(array_filter($numbers, function($v) { return $v%2==0; })) ;
    2 points
  47. You need to specify your units for the margin values. 161px, not just 161.
    2 points
  48. Not as it is now - if you want to tell the user which is taken you'll have to update the query. Right now it just returns a count of records that match either the username or the email. You'll have to actually select both and then check in PHP which one matches, or rewrite the query to return the offending column. However, I'd recommend just letting people know that one of the two has been taken. That way you're not confirming to an outside party which of the two actually exists in the database - a hacker that knows for a fact a username exists has less work to do and can focus only on figuring out a correct password.
    2 points
  49. Just use var_dump if you just need to see what the array contains.
    2 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.