Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation since 09/05/2013 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. The radio buttons do not have to be visible, you can hide them and just have a label (which is your image) activate the associated radio. I put together an example. <input type="radio" name="color" value="black" id="black"> <label for="black"> <img src="black.png" alt="black"> </label> You can use CSS to display a border around whichever image is selected, and if you add a class to indication the current one, use a different border to indicate the current item. In my example above, the selected item has a white border, the current has a yellow border.
    2 points
  17. The redirections are part of the setup for running a command. > and < tie the STDOUT and STDIN streams to a file. This processing is handled by the shell, not the program being executed, so they are not considered part of the programs argument list. Since this is pre-execution setup work as well, the redirection happens before the program is executed, thus happen even if the program execution fails. So, given the command line: zcho It is cold today! > winter.txt The shell would Parse the line into it's components Argument list: ['zcho', 'It', 'is', 'cold', 'today!'] Redirections: STDOUT -> winter.txt Setup STDIN, STDOUT, and STDERR STDIN: tied to the shell's current STDIN stream STDOUT: tied to a new stream created by opening winter.txt for writing (with truncation) STDERR: tied to the shell's current STDERR stream. Extract the first argument and use it as the program/command name (zcho) Attempt to execute the program/command with the arguments given You can confirm the redirection happens first by running your invalid command with STDERR redirection: kicken@web1:~$ zcho It is cold today! 2> error.txt kicken@web1:~$ cat error.txt -bash: zcho: command not found The error message from the zcho command is redirected to the error.txt file rather than displayed in the terminal.
    2 points
  18. None. I played around with ChatGPT a bit when it first came out, to see what it was capable of and just have some fun. I was impressed by it's ability to understand things. I fed it a few functions I've written and asked it to explain what the functions did and write sample code using the functions and it was surprisingly accurate. I don't really see much use for it day-to-day though, so I haven't really used it in quite a while. It does get a lot closer to the "Ask a question, get an answer" goal of search engines, which is why I immediately knew people would be working on that and am not at all surprised to see it happening. Eventually as the models get better and more integrated into search, you'll be able to just type a plain-English (or whatever language) question into google and get an actually answer back instead of having to wade through a list of result pages. From the code side of things, the AI is good enough right now to answer simple syntax / logic errors. Take one of the questions posted here as an example. I told ChatGPT what the error was, what the code was, and to tell me why. It responded: I imagine eventually such a tool will be used to help teach new programmers by either providing better error detection in IDE's or having an virtual mentor they can ask questions and get immediate answers rather than having to either search the web or post on a forum and wait for a response. There are already AI coding assistants that might fulfill this task, I haven't tried any of them personally to know how useful they are.
    2 points
  19. So just to say it, the on event handler is accepting a callback function to run when there is a "play" event. A simpler solution would be to just have a function defined there, that the callback would run, or to define a function globally and pass the name of the function. However, @Kicken coded this function to return an anonymous function. It helps to focus in on return statements in code like this. If you notice the requestSent variable is declared outside the function declaration that does the work. This creates a "closure" (or takes advantage of javascript closure) depending on how you want to think about it. It makes the variable requestSent available to the inner function that is being returned, and this variable will continue to exist in the browser's memory associated with the window/page, until such a time as a new request is made that causes new html/javascript/css to be loaded. An alternative would be to declare requestSent globally and use that, but he gave you something more sophisticated -- a function that returns a function and takes advantage of a variable that is only visible to the anonymous function, and yet is available to the anonymous function across executions. Each time the callback is run, this could be either for the same song or a different song, so inside the function, there is a jQuery call to find the id of the button. let a_id = $(this).attr("id") It's good to think about why this is declared inside the function and how that works. Since this handler can be called for any song, the $(this) resolves in this situation as the song that is being played. Thus the a_id gets set each time there's a play event, and then gets the html id attribute. I added code to push the value onto the requestSent array, which again, since it's part of the closure for the anonymous function, survives across plays. I used Array.includes() to check if the song id already exists in requestSent. If not, I update requestSent with requestSent.push(a_id) and the ajax runs, passing a_id. The ajax is also being done using the jQuery library. The final question you should probably be asking is: if this is a function that returns a function, then how is it, that the callback, which requires a function to run, gets the actual function it needs. A function that returns a function is not a callback. The answer is that again Kicken used an IFFE here. What is actually being passed is a function that is immediately executed. You can see this because after the function definition function () { ... } It is immediately followed by the parens ie. () which causes javascript to execute the function. function () { ... }() So this code works because the function that returns a function, is run immediately, giving the callback parameter what it wants ... a function to run when a play event occurs. The function is anonymous and only bound to the event handler for play events, which also keeps global scope from being cluttered with a symbol table entry for a function that is only needed for the callback. The benefit of doing it this way is that he did not need to utilize a global variable, since closure takes care of this for you. This type of code is favored in many situations, since you don't have a slew of global variables floating around. Nothing outside the callback function can see or modify the requestSent array -- yet it is essentially a private environment that the callback uses. As I said previously -- advanced javascript stuff, that can be confusing if you are still learning javascript. Hope this helps -- using those terms (IFFE, javascript closure, js anonymous function, js callbacks, js this) will lead you to an enormous amount of additional material if you need to explore them further.
    2 points
  20. FYI - ROLLUP is certainly available in version 5.7 mysql> SELECT VERSION(); +------------+ | VERSION() | +------------+ | 5.7.36-log | +------------+ mysql> SELECT classid as class -> , COUNT(*) as students -> FROM student_class -> WHERE semesterid = 12 -> GROUP BY classid WITH ROLLUP; +-------+----------+ | class | students | +-------+----------+ | 1 | 17 | | 2 | 18 | | 3 | 20 | | 4 | 23 | | 5 | 22 | | 6 | 27 | | 7 | 24 | | 8 | 20 | | 9 | 21 | | 10 | 27 | | 11 | 25 | | 13 | 5 | | 14 | 5 | | 16 | 3 | | 17 | 5 | | 19 | 17 | | NULL | 279 | <--- ROLLUP total +-------+----------+
    2 points
  21. 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
  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. 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
  24. 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
  25. COALESCE() comes in useful here SELECT ... FROM tablename WHERE COALESCE(colname, '') = '';
    2 points
  26. 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
  27. @gizmola and I both gave you code that you have not implemented. You should spend some time going through this PDO tutorial. Making a PDO connection is one of the simplest things you would ever need to do. https://phpdelusions.net/pdo This is all that is required to make a PDO connection. Anything you do beyond this, you should know exactly WHY you are doing more. $con = new PDO("mysql:host=localhost;dbname=test", 'root', '');
    2 points
  28. Probably not what you really want, but it is what you asked for: $midPt = floor(strlen($content)/2); $file["content"] = substr($content, 0, $midPt) . $context['user']['id'] . substr($content, $midPt);
    2 points
  29. Using a DB, I'd do it this way (tables used are from my SQL tutorial). Select a house name and the pupils menu lists pupils from that house. <?php const HOST = 'localhost'; const USERNAME = '????'; const PASSWORD = '????'; const DATABASE = 'jointute'; // default db $db = pdoConnect(); //============================================================================== // HANDLE AJAX CALLS // if (isset($_GET['ajax'])) { if ($_GET['ajax']=='pupilopts') { exit( json_encode(pupilOptions($db, $_GET['hid']))); } exit('INVALID REQUEST'); } //============================================================================== function houseOptions($db) { $opts = "<option value=''>- select house -</option>\n"; $res = $db->query("SELECT houseID , house_name FROM house ORDER BY house_name "); foreach ($res as $r) { $opts .= "<option value='{$r['houseID']}'>{$r['house_name']}</option>\n"; } return $opts; } function pupilOptions($db, $hid) { $opts = []; $res = $db->prepare("SELECT pupilID , CONCAT(lname, ', ', fname) as name FROM pupil WHERE houseID = ? ORDER BY lname, fname "); $res->execute([$hid]); $pups = $res->fetchAll(); $opts = array_column($pups, 'name', 'pupilID'); sort($opts); return $opts; } function pdoConnect($dbname=DATABASE) { $db = new PDO("mysql:host=".HOST.";dbname=$dbname;charset=utf8",USERNAME,PASSWORD); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); return $db; } ?> <!DOCTYPE html> <html lang='en'> <head> <title>Example</title> <meta charset='utf-8'> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type='text/javascript'> $().ready( function() { $("#houses").change( function() { var hid = $(this).val() $.get( "", // specify processing file on server (in this case it's same file) {"ajax":"pupilopts", "hid":hid}, // data to send in request function(resp) { // handle the response $("#pupils").html("<option value=''> - select pupil -</option"); $.each(resp, function(k, v) { $("#pupils").append($("<option>", {"val":k, "text":v})) }) }, "JSON" // response type ) }) }) </script> <style type='text/css'> body { font-family: calibri, sans-serif; font-size: 12pt; } div { margin: 16px; padding: 8px; border: 1px solid gray; } label { display: inline-block; background-color: black; color: white; width: 120px; padding: 8px; margin: 1px 8px; } </style> </head> <body> <div> <label>House</label> <select id="houses" > <?= houseOptions($db) ?> </select> </div> <div> <label>Pupil</label> <select id="pupils" > <!-- pupil options --> </select> </div> </body> </html>
    2 points
  30. 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
  31. While PHPStorm is subscription based, it's pretty good in my opinion and for an IDE it has helped my PHP skills a lot. It makes suggestions on how to write the code in a better way that I would never have thought of and makes syntax errors easy to resolve. I am not affiliated with JetBrains as I just like using their developer tools as it simplifies my coding a lot.
    2 points
  32. If you want to use silly names like that with the "." at the end then you need the column name inside backticks. SELECT `KNr.` FROM .... From MySQL manual
    2 points
  33. A more efficient way is to only select the 8 rows you're looking for instead of selecting the entire table.
    2 points
  34. Hello everyone, I'm very new to this site. I'm here to learn how to code in PHP as I once did. I'm very raw at tho, and I'm looking to start back up in it again. So again, hello everyone and remember I'm new. So any dummy questions I made ask, please bear with me. I would like to start my own web site for my own purpose. Something very small and for my needs. And to top it all off, I'm going to run it on a Raspberry Pi from my home. This is should be a fun trip. Thanks Sincerely Dan
    2 points
  35. 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
  36. If you want it in a single query, initialize the variables in a joined subquery SELECT , (@csumA := @csumA + A) as cumulative_A , (@csumM := @csumM + M) as cumulative_M , (@csumE := @csumE + E) as cumulative_E , (@csumW := @csumW + W) as cumulative_W FROM ( SELECT WEEK(s.date) week, SUM(CASE WHEN s.user_id = 50 THEN s.points ELSE 0 END) AS A, SUM(CASE WHEN s.user_id = 51 THEN s.points ELSE 0 END) AS M, SUM(CASE WHEN s.user_id = 52 THEN s.points ELSE 0 END) AS E, SUM(CASE WHEN s.user_id = 53 THEN s.points ELSE 0 END) AS W FROM users u JOIN scores s ON u.user_id = s.user_id JOIN league l ON l.league_id = s.league_id AND and l.league_name = 'Sunday League' WHERE year(s.date) = YEAR(sysdate()) GROUP BY s.date ORDER BY s.date ASC ) PTS JOIN ( SELECT @csumA:=0, @csumM:=0, @csumE := 0, @csumW:=0 ) INIT;
    2 points
  37. 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
  38. 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
  39. If it helps, note that that a <button> element can have a value attribute independent of its label <?php $option = $_GET['option'] ?? ''; if ($option) echo "You chose $option<hr>"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Sample</title> </head> <body> <form> Select an option <button name="option" value="1">Choose me</button> <button name="option" value="2">Choose me</button> <button name="option" value="3">No, Choose me</button> <button name="option" value="4">No, Choose me</button> <button name="option" value="5">No, Choose me</button> </form> </body> </html>
    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. An alternative to the 2-table option is to treat costs as transactions, just like payments (cost amounts +ve, payment amounts -ve in this example)... DATA TABLE: payment +------+------+------------+--------------+---------+ | uid | name | trans_date | payment_type | payment | +------+------+------------+--------------+---------+ | 1 | kim | 2020-03-01 | cost | 100 | | 1 | kim | 2020-03-02 | card | -100 | | 2 | lee | 2020-03-01 | cost | 95 | | 2 | lee | 2020-03-02 | cash | -95 | | 3 | kent | 2020-03-01 | cost | 100 | | 3 | kent | 2020-03-03 | cash | -50 | | 3 | kent | 2020-03-04 | card | -50 | | 4 | iya | 2020-03-01 | cost | 80 | | 4 | iya | 2020-03-05 | cash | -40 | | 4 | iya | 2020-03-06 | card | -20 | +------+------+------------+--------------+---------+ then SELECT uid , name , date , cost , cash , card , total as balance FROM ( SELECT name , DATE_FORMAT(trans_date, '%b %D') as date , CASE payment_type WHEN 'cash' THEN -payment ELSE '-' END as cash , CASE payment_type WHEN 'card' THEN -payment ELSE '-' END as card , CASE payment_type WHEN 'cost' THEN payment ELSE '-' END as cost , @tot := CASE @previd WHEN uid THEN @tot+payment ELSE payment END as total , @previd := uid as uid FROM ( SELECT * FROM payment ORDER BY uid, trans_date ) sorted JOIN (SELECT @previd:=0, @tot:=0) initialize ) recs; +------+------+---------+------+------+------+---------+ | uid | name | date | cost | cash | card | balance | +------+------+---------+------+------+------+---------+ | 1 | kim | Mar 1st | 100 | - | - | 100 | | 1 | kim | Mar 2nd | - | - | 100 | 0 | | 2 | lee | Mar 1st | 95 | - | - | 95 | | 2 | lee | Mar 2nd | - | 95 | - | 0 | | 3 | kent | Mar 1st | 100 | - | - | 100 | | 3 | kent | Mar 3rd | - | 50 | - | 50 | | 3 | kent | Mar 4th | - | - | 50 | 0 | | 4 | iya | Mar 1st | 80 | - | - | 80 | | 4 | iya | Mar 5th | - | 40 | - | 40 | | 4 | iya | Mar 6th | - | - | 20 | 20 | +------+------+---------+------+------+------+---------+
    2 points
  43. the convention around here is "New question, new thread". That allows for short, direct answer to short, direct questions instead of long, rambling threads where all the "Goodness" gets lost. Some comments on the above: the use of "global" breaks encapsulation, requiring the environment "outside" the function to provide the variable. It is better to pass the data as an argument to the function. What value does admin['gender'] have? Any value passed that resolves to true will cause the ternary operator to return "Mr" and everything else will return "Mrs". The code makes no attempt to ensure that the array indexes used actually exist; this may or may not be an issue. What if the individual is female and not married? They might object to being called "Mrs". What if the individual is not gender-identifying? They would object most strongly to be referred to by either of the terms used here. Marital status and/or gender are both Personal Data and should be stored in the User's "record" (whatever form that takes) so that it can be managed by/on behalf of the User and changed over time. Regards, Phill W.
    2 points
  44. For example, https://www.php.net/manual/en/datetime.createfromformat.php https://www.php.net/manual/en/datetime.format.php
    2 points
  45. Yes but you don't want to run both at the same time. If you really wanted to, you would need to change the Apache port on one of them as they both use port 80
    2 points
  46. the path being used in the opendir() statement either has a hard-coded '/home/sites/' in it or is using a variable that has that incorrect value in it. based on the path where the code is actually at, that part of the path should be - /home/customer/www/
    2 points
  47. $numbers = array(1,3,7,8,10,13); $max = max(array_filter($numbers, function($v) { return $v%2==0; })) ;
    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. Simplest thing to do is install VirtualBox and load Linux in a Virtual Machine
    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.