Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation since 09/23/2012 in Posts

  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. Try $expected = array( '1111', '2222', '2222', '3333' ); $received = array( '1111', '2222', '3333', '3333' ); $cExp = array_count_values($expected); $cRec = array_count_values($received); foreach (array_keys($cExp+$cRec) as $prod) { $e = $cExp[$prod] ?? 0; $r = $cRec[$prod] ?? 0; switch ($e <=>$r) { case -1: $check = 'Over'; break; case 0: $check = 'OK'; break; case 1: $check = 'Under'; break; } echo $prod . " Ordered: $e Received: $r - $check <br>"; } giving 1111 Ordered: 1 Received: 1 - OK 2222 Ordered: 2 Received: 1 - Under 3333 Ordered: 1 Received: 2 - Over
    2 points
  18. password_hash() and password_verify()
    2 points
  19. Query your existing bookings and create an array... function getBookedSlots($pdo, $wkcomm) { $res = $pdo->prepare("SELECT datum , vreme FROM tehnicki WHERE datum BETWEEN ? AND ? + INTERVAL 6 DAY "); $res->execute([ $wkcomm, $wkcomm ]); $data = []; foreach ($res as $r) { $data[$r['datum']][$r['vreme']] = 1; } return $data; } $bookings [ '2023-07-05'][ '10:00' ] = 1; $bookings [ '2023-07-06'][ '11:30' ] = 1 then if ($d > $today && !isset($bookings[$dt][$ts])) { // clickable if not booked Incorporating into my previous code... <?php $duration = 45; $cleanup = 0; $start = "10:00"; $end = "15:15"; ################################################################################ # Default week commence date # ################################################################################ $d1 = new DateTime(); if ($d1->format('w') <> 1) { $d1->modify('last monday'); } $wkcomm = $_GET['week'] ?? $d1->format('Y-m-d'); $d1 = new DateTime($wkcomm); $week1 = $d1->sub(new DateInterval('P7D'))->format('Y-m-d'); $week2 = $d1->add(new DateInterval('P14D'))->format('Y-m-d'); function getBookedSlots($pdo, $wkcomm) { $res = $pdo->prepare("SELECT datum , vreme FROM tehnicki WHERE datum BETWEEN ? AND ? + INTERVAL 6 DAY "); $res->execute([ $wkcomm, $wkcomm ]); $data = []; foreach ($res as $r) { $data[$r['datum']][$r['vreme']] = 1; } return $data; } function timeslots($duration, $cleanup, $start, $end) { $start = new DateTime($start); $end = new DateTime($end); $duration += $cleanup; $interval = new DateInterval("PT".$duration."M"); return new DatePeriod($start, $interval, $end); } function daysOfWeek($comm) { $d1 = new DateTime($comm); return new DatePeriod($d1, new DateInterval('P1D'), 6); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <title>Tehnički pregled</title> <script type='text/javascript'> $(function() { // when page has loaded $(".tslot").click(function() { // define click event listener $("#tVreme").val( $(this).data("timeslot") ) $(".tslot").css('background-color', '#fff') $(this).css('background-color', '#ccc') }) }) </script> <style type='text/css'> td, th { padding: 4px; text-align: center; } th { background-color: black; color: white; } td { color: #999; } </style> </head> <body> <section class="header"> <div class="navbar"> <div class="logo"> <img src="images/logo.png"> <span>Tehnički pregled</span> </div> <div class="nav-links" id="navLinks"> <ul> <li><a aria-current="page" href="index.php">Naslovna</a></li> <li><a href="galerija.php">Galerija</a></li> </ul> </div> </div> <div class="headline"> <h1>Tehnički pregled</h1> <p>Odaberite termin i zakažite tehnički pregled svog vozila brzo i jednostavno na našem sajtu.</p> <a href="#termin" class="btn">Zakažite termin</a> </div> </section> <div id="myModal" class="modal"> <div class="login-box"> <p>Zakazivanje termina</p> <form method="POST"> <div class="user-box"> <input name="tIme" type="text" required="Please"> <label>Ime</label> </div> <div class="user-box"> <input name="tPrezime" type="text" required> <label>Prezime</label> </div> <div class="user-box"> <input name="tTelefon" type="text" required> <label>Broj telefona</label> </div> <div class="user-box"> <input name="tVreme" id="tVreme" type="text" required readonly> <label>Datum i vrijeme</label> </div> <br> <input type='submit' value='POŠALJI'> </form> </div> </div> <section class="content" id="termin"> <br><br> <a href='?week=<?=$week1?>'>Previous Week</a> &emsp; <a href='?week=<?=$week2?>'>Next Week</a> <br><br> <table> <?php #################################################################### # BUILD THE TABLE OF TIMESLOTS # #################################################################### $days = daysOfWeek($wkcomm); $times = timeslots($duration, $cleanup, $start, $end); $bookings = getBookedSlots($pdo, $wkcomm); // get current bookings $today = new DateTime(); // table headings echo "<tr>"; foreach ($days as $d) { echo '<th>' . $d->format('l<\b\r>d M Y') . '</th>'; } echo "</tr>\n"; // times foreach ($times as $t) { $ts = $t->format('H:i'); echo "<tr>"; foreach ($days as $d) { $dt = $d->format('Y-m-d'); if ($d > $today && !isset($bookings[$dt][$ts])) { // clickable if not booked $dt = $dt . ' ' . $ts; echo "<td><a href='#' class='tslot' data-timeslot='$dt' >$ts h</a><?td>"; } else { echo "<td>$ts</td>"; } } echo "</tr>\n"; } ?> </table> <span>Odaberite željeno vreme.</span> </section> <section class="footer"> <div class="social"> <ul> <li><a href="#"><img src="images/facebook.png" alt=""></a></li> <li><a href="#"><img src="images/twitter.png" alt=""></a></li> <li><a href="#"><img src="images/gmail.png" alt=""></a></li> </ul> </div> <span>Designed by Filip Glišović &copy2023. - All rights reserved.</span> </section> </body> </html>
    2 points
  20. PHPFreaks has been going through some ownership and hosting changes, and that has lead to some extended down time. The hosting for the site has been generously provided by a number of different people and organizations throughout the years, and without their patronage, phpfreaks would have shutdown many years ago. With that said, please understand that the volunteers who administer and moderate the site don't have control over the underlying infrastructure, other than what is provided to us. In this recent outage the new owner of the site, who supported it in the years following the sale of the original hosting company where phpfreaks was created, has provided us a lot of support and aid, and demonstrated a commitment to keep the site running for the foreseeable future. Unfortunately, with that said, there will probably be some additional outages in the near future as the server resources that run the site are being moved to a different co-location facility. Please bear with us through these difficulties, as we endeavor to keep the community alive and available for everyone who finds it useful. We will continue to keep doing the work to keep phpfreaks running, and we appreciate the many long time members who have made it their home.
    2 points
  21. Does the uploads/ directory exist? And does it exist at (I think:) /paypal/uploads?
    2 points
  22. You won't learn anything useful about SQL pursuing this design because the design is fundamentally flawed and directly opposed what SQL is designed to do. My answer is that you don't. I'm sure there is a way for it to be done, but doing so would teach you nothing useful. The correct solution to your problem is to re-design your table structure, then use SQL as it's intended to be used rather than fight against it trying to make a poor design work. This shows yet another potential reason why your design is flawed. Why do you have multiple rows for the same link? If the answer is "To have more than 4 key words" then that's wrong. The multi-table solution gives you the ability to have an unlimited number of keywords per link.
    2 points
  23. first of all you should use an unique index for email and I don't understand the also having for username (though that too). Though I now can see both...tired. Second take a look at this $sql = "SELECT * FROM register WHERE username:username AND email:email"; See anything missing? I give you a hint it's between username :username and also email :email. Here's a good link https://phpdelusions.net/pdo and I even still use it from time to time.
    2 points
  24. do not store any user information in cookies. anyone can set cookies to any value and can impersonate a user. to do what you are asking, generate a unique token, store the token in a cookie and store it in a row in a 'remember me' database table, along with the user's id and things like when the remember me was set and when you want it to expire if not regenerated. if you receive a cookie containing a token, query to get the user's id and the expire datetime to determine if the token is valid. if it is, set the normal session user_id variable to indicate who the logged in user is. you should only store the user id in a session variable, then query on each page request to get any other user information, such as the username, permissions,... this will insure that an change/edit in this user information will take effect on the very next page request.
    2 points
  25. 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
  26. 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
  27. 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
  28. 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
  29. Just before closing the book on this one, please ask yourself this: In [another] four months time, are you going to look at this code and ask yourself "What the H*** does this do?" You will spend far more time reading code than writing it (accepted industry stats estimate 80% reading, 20% writing). Always favour Clarity and Correctness over Conciseness or Cleverness. Regards, Phill W.
    2 points
  30. It's the antithesis of progress and learning. We can only tell him stuff that he already knows, which is pointless. If he doesn't know it he won't use it. Therefore, whatever we tell him is a waste of time.
    2 points
  31. 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
  32. 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
  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. Rinse and repeat - exchanging u1 and u2 $new = []; foreach ($array as $a) { if (!isset($new[$a['u1']])) { $new[$a['u1']] = []; } $new[$a['u1']][] = $a['u2']; //repeat exchanging u1 and u2 if (!isset($new[$a['u2']])) { $new[$a['u2']] = []; } $new[$a['u2']][] = $a['u1']; } // // Output $new array // echo '<pre>'; foreach ($new as $u1 => $u2s) { printf('<br><b>%4d</b> | ', $u1); foreach ($u2s as $u) { printf('%4d &vellip;', $u); } }
    2 points
  35. Here's my attempt DATA mysql> select * from ajoo -> order by user, recno; +-------+----------+---------+---------+ | recno | user | v_score | rollavg | +-------+----------+---------+---------+ | 6 | mina1111 | 4 | 3.2500 | | 7 | mina1111 | 3 | 3.2000 | | 8 | mina1111 | 2 | 3.2000 | | 9 | mina1111 | 4 | 3.4000 | | 10 | mina1111 | 5 | 3.6000 | | 11 | mina1111 | 0 | 2.8000 | | 12 | mina1111 | 1 | 2.5000 | | 13 | mina1111 | 1 | 1.7500 | | 14 | mina1111 | 1 | 0.7500 | | 1 | nina1234 | 3 | NULL | | 4 | nina1234 | 3 | 2.5000 | | 5 | nina1234 | 4 | 3.0000 | | 15 | nina1234 | 5 | NULL | | 17 | nina1234 | 2 | 2.0000 | | 22 | nina1234 | 2 | NULL | +-------+----------+---------+---------+ QUERIES -- -- create temp table a -- CREATE TEMPORARY TABLE temp_a SELECT a.recno , a.v_score , @count := CASE WHEN user = @prevu THEN @count+1 ELSE 1 END AS reccount , @prevu := user AS user FROM ajoo a JOIN (SELECT @count:=0, @prevu:=NULL) AS init ORDER BY user, recno ; -- -- create temp table b -- (copy of temp_a) -- CREATE TEMPORARY TABLE temp_b SELECT * FROM temp_a ; -- -- get results -- SELECT av.user , avg5 , tot3 FROM ( SELECT user , AVG(v_score) as avg5 FROM ( SELECT a.user , v_score FROM temp_a a JOIN ( SELECT user , COUNT(*) AS maxrec FROM ajoo GROUP BY user ) max ON a.user = max.user AND a.reccount > max.maxrec - 5 ) tots GROUP BY user ) av JOIN ( SELECT user , SUM(v_score) as tot3 FROM ( SELECT b.user , v_score FROM temp_b b JOIN ( SELECT user , COUNT(*) AS maxrec FROM ajoo GROUP BY user ) max ON b.user = max.user AND b.reccount > max.maxrec - 3 ) tots GROUP BY user ) tot USING (user) ; RESULTS +----------+--------+------+ | user | avg5 | tot3 | +----------+--------+------+ | mina1111 | 1.6000 | 3 | | nina1234 | 3.2000 | 9 | +----------+--------+------+
    2 points
  36. $this (programming pun intended) is the correct syntax, but produced a different error than the one you posted about the undefined variable. what was the error message in $this case? i'm going to guess that the database connection probably failed and there's no useful error handling in the code. while not the cause of the most immediate problem, your main code should be responsible for creating the database connection, then use dependency injection to supply that to any class that needs it. by making each class responsible for getting a specific database connection, your code is not general purpose. if the data source changes, to use an additional/different database type or using a remote api, you would need to go through and edit all the current code.
    2 points
  37. OK, I loaded your data into a test table INSERT INTO ajoo_login (datein, dateout) VALUES ('2019-03-30 17:05:24', '2019-03-30 17:09:47'), ('2019-04-01 15:13:32', '2019-04-01 15:19:46'), ('2019-04-04 23:37:21', '2019-04-04 23:50:51'), ('2019-04-18 15:28:35', '2019-04-18 15:33:10'), ('2019-04-23 16:35:20', '2019-04-23 16:42:35'), ('2019-04-24 12:03:07', '2019-04-24 12:10:28'), ('2019-05-01 08:05:48', '2019-05-01 08:20:28'), ('2019-05-08 18:04:04', '2019-05-08 18:14:57'), ('2019-05-09 08:18:15', '2019-05-09 08:29:38'), ('2019-06-18 12:49:01', '2019-06-18 13:10:15'), ('2019-09-05 17:17:33', '2019-09-13 15:24:28'), ('2019-09-28 07:05:03', '2019-09-28 08:12:26'), ('2019-09-28 12:55:56', '2019-09-28 13:21:15'), ('2019-09-28 16:47:52', '2019-10-01 16:28:18'), ('2019-10-03 13:11:44', '2019-12-10 17:56:25'), ('2020-05-22 12:08:32', '2020-08-27 17:21:02'); Running the query gives SELECT SUM(diff) AS tot_absent FROM ( SELECT CASE WHEN DATE(datein) > DATE(@prevout) THEN DATEDIFF(datein, @prevout) - 1 ELSE 0 END AS diff , datein , @prevout := dateout AS dateout -- store dateout in @prevout FROM ajoo_login JOIN (SELECT @prevout := NULL) init -- initialize @prevout ) logins; +------------+ | tot_absent | +------------+ | 327 | +------------+ Running just the subquery portion gives mysql> SELECT -> CASE WHEN DATE(datein) > DATE(@prevout) -> THEN DATEDIFF(datein, @prevout) - 1 -> ELSE 0 -> END AS diff -> , datein -> , @prevout := dateout AS dateout -> FROM ajoo_login -> JOIN (SELECT @prevout := NULL) init; +------+---------------------+---------------------+ | diff | datein | dateout | +------+---------------------+---------------------+ | 0 | 2019-03-30 17:05:24 | 2019-03-30 17:09:47 | | 1 | 2019-04-01 15:13:32 | 2019-04-01 15:19:46 | | 2 | 2019-04-04 23:37:21 | 2019-04-04 23:50:51 | | 13 | 2019-04-18 15:28:35 | 2019-04-18 15:33:10 | | 4 | 2019-04-23 16:35:20 | 2019-04-23 16:42:35 | | 0 | 2019-04-24 12:03:07 | 2019-04-24 12:10:28 | | 6 | 2019-05-01 08:05:48 | 2019-05-01 08:20:28 | | 6 | 2019-05-08 18:04:04 | 2019-05-08 18:14:57 | | 0 | 2019-05-09 08:18:15 | 2019-05-09 08:29:38 | | 39 | 2019-06-18 12:49:01 | 2019-06-18 13:10:15 | | 78 | 2019-09-05 17:17:33 | 2019-09-13 15:24:28 | | 14 | 2019-09-28 07:05:03 | 2019-09-28 08:12:26 | | 0 | 2019-09-28 12:55:56 | 2019-09-28 13:21:15 | | 0 | 2019-09-28 16:47:52 | 2019-10-01 16:28:18 | | 1 | 2019-10-03 13:11:44 | 2019-12-10 17:56:25 | | 163 | 2020-05-22 12:08:32 | 2020-08-27 17:21:02 | +------+---------------------+---------------------+
    2 points
  38. However, using the string just as far as the the first entity $valrD = json_decode(valrGet, true); echo '<pre>$valrD = ', print_r($valrD, 1), '</pre>'; gives therefore $target = 'BTC/ZAR'; foreach ($valrD['response']['entities'] as $k => $ents) { if ($ents['pair_name'] == $target) { echo "$target asking price : {$ents['ask']['price']}<br>"; break; } } outputs "BTC/ZAR asking price : 179382.54"
    2 points
  39. 1 and 2 would presumably be input from the web page. The rest would be something like: for ($m=1; $m<=$M; $m++) { for ($l=1; $l<=$L; $l++) { for ($j=1; $j<=$N; $j++) { #do calculation here storing it in a 2D array } # select minimum here (perhaps min() function) } } # use array sort # use PHP vector class # compute distance from vectors # echo results in desired format
    2 points
  40. try $temp = []; foreach ($cars as $car) { $qty = intval($car); $key = trim(strstr($car, ','), ','); if (!isset($temp[$key])) $temp[$key] = 0; $temp[$key] += $qty; } foreach ($temp as $k => $t) { $newcars[] = "$t,$k"; }
    2 points
  41. foreach ($global_array as $k => $v) { foreach ($global_array as $k1 => $v1) { if ($k==$k1) continue; if (array_values(array_intersect($v, $v1)) == array_values($v1)) { unset($global_array[$k1]); } } }
    2 points
  42. Your randomNr array contains 10 elements so foreach($randomNr as $number) will give 10 columns. You need to pick a random 6 numbers out of the 10. Separate the php code from the html. Use CSS for styling the output. Example <?php $randomNr = range(0,9); $bingokaart = display($randomNr); function display ($arr) { $result = ""; for ($row = 1; $row < 7; ++$row) { $rand6 = array_rand($arr, 6); $result .= '<tr>'; foreach ($rand6 as $n) { $result .= "<td>$row$arr[$n]</td>"; } $result .= "</tr>\n"; } return $result; } ?> <!DOCTYPE html> <html> <head> <title>Sample</title> <style type="text/css"> table { border-collapse: collapse; } td { padding: 2px; } </style> </head> <body> <table border='1'> <?= $bingokaart ?> </table> </body> </html>
    2 points
  43. 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
  44. Alternative model which allows multiple siblings jdev_nroll; jdev_sibling; +----+--------+---------+-------+-----------+------------+ +------------+----------+ | id | sname | ctclass | shift | ctstudent | dob | | sibling_id | elder_id | +----+--------+---------+-------+-----------+------------+ +------------+----------+ | 1 | Curly | 1 | 0 | N | 2007-01-20 | | 2 | 1 | | 2 | Larry | 1 | 0 | Y | 2010-12-21 | | 3 | 1 | | 3 | Mo | 1 | 0 | Y | 2011-02-22 | | 3 | 2 | | 4 | Peter | 1 | 0 | N | 2009-01-03 | | 4 | 5 | | 5 | Paul | 1 | 0 | N | 2006-12-21 | | 9 | 8 | | 6 | Mary | 1 | 0 | Y | 2010-09-20 | | 9 | 10 | | 7 | Jane | 1 | 0 | N | 2008-03-08 | | 10 | 8 | | 8 | John | 1 | 0 | N | 2006-10-04 | +------------+----------+ | 9 | George | 1 | 0 | Y | 2010-10-26 | | 10 | Ringo | 1 | 0 | Y | 2009-11-15 | +----+--------+---------+-------+-----------+------------+ SELECT a.id as sibling_id , a.sname as sibling_name , TIMESTAMPDIFF(YEAR,a.dob,curdate()) as sibling_age , a.ctclass as class , b.id as elder_id , b.sname as elder_name , TIMESTAMPDIFF(YEAR,b.dob,curdate()) as elder_age , b.ctstudent as elder_ctstudent FROM jdev_nroll a JOIN jdev_sibling s ON a.id = s.sibling_id JOIN jdev_nroll b ON s.elder_id = b.id WHERE a.ctstudent = 'Y' ORDER BY a.id +------------+--------------+-------------+-------+----------+------------+-----------+-----------------+ | sibling_id | sibling_name | sibling_age | class | elder_id | elder_name | elder_age | elder_ctstudent | +------------+--------------+-------------+-------+----------+------------+-----------+-----------------+ | 2 | Larry | 9 | 1 | 1 | Curly | 13 | N | | 3 | Mo | 8 | 1 | 1 | Curly | 13 | N | | 3 | Mo | 8 | 1 | 2 | Larry | 9 | Y | | 9 | George | 9 | 1 | 8 | John | 13 | N | | 9 | George | 9 | 1 | 10 | Ringo | 10 | Y | | 10 | Ringo | 10 | 1 | 8 | John | 13 | N | +------------+--------------+-------------+-------+----------+------------+-----------+-----------------+
    2 points
  45. For example, https://www.php.net/manual/en/datetime.createfromformat.php https://www.php.net/manual/en/datetime.format.php
    2 points
  46. 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
  47. Protecting a form field from what? htmlspecialchars() is for use when outputting user-supplied data data to a web page. mysql_real_escape string() is was used to protect input values to queries from SQL injection. This is now obsolete, replaced by mysqli_real_escape_string() or (better still) the use of prepared statements to completely separate the query code from the user-supplied data.
    2 points
  48. $numbers = array(1,3,7,8,10,13); $max = max(array_filter($numbers, function($v) { return $v%2==0; })) ;
    2 points
  49. You need to specify your units for the margin values. 161px, not just 161.
    2 points
  50. 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
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.