Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation since 04/19/2023 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. You've done the hard work already. Instead of calculating the product, store the selected array. <?php $primes = array(2, 3, 5, 7, 11, 13, 17, 19, 23); $combos = []; function getAllCombinations($arr, $n, &$combos, $selected = array(), $startIndex = 0) { if ($n == 0) { $combos[] = $selected; // $product = 1; // foreach ($selected as $prime) { // $pr[] = $prime; // $product *= $prime; // $pr[] = $prime; // } // echo "Product: $product\n"; return; } for ($i = $startIndex; $i < count($arr); $i++) { $selected[] = $arr[$i]; getAllCombinations($arr, $n - 1, $combos, $selected, $i + 1); array_pop($selected); // Backtrack and remove the element for next iteration } } getAllCombinations($primes, 4, $combos); echo '<pre>'; foreach ($combos as $com) { printf("%-35s = %5d<br>", join(' &times; ', $com), array_product($com)); // output numbers and product } ?> giving 2 × 3 × 5 × 7 = 210 2 × 3 × 5 × 11 = 330 2 × 3 × 5 × 13 = 390 2 × 3 × 5 × 17 = 510 2 × 3 × 5 × 19 = 570 2 × 3 × 5 × 23 = 690 2 × 3 × 7 × 11 = 462 2 × 3 × 7 × 13 = 546 2 × 3 × 7 × 17 = 714 2 × 3 × 7 × 19 = 798 2 × 3 × 7 × 23 = 966 2 × 3 × 11 × 13 = 858 2 × 3 × 11 × 17 = 1122 2 × 3 × 11 × 19 = 1254 2 × 3 × 11 × 23 = 1518 2 × 3 × 13 × 17 = 1326 2 × 3 × 13 × 19 = 1482 2 × 3 × 13 × 23 = 1794 2 × 3 × 17 × 19 = 1938 2 × 3 × 17 × 23 = 2346 2 × 3 × 19 × 23 = 2622 2 × 5 × 7 × 11 = 770 2 × 5 × 7 × 13 = 910 . . 5 × 17 × 19 × 23 = 37145 7 × 11 × 13 × 17 = 17017 7 × 11 × 13 × 19 = 19019 7 × 11 × 13 × 23 = 23023 7 × 11 × 17 × 19 = 24871 7 × 11 × 17 × 23 = 30107 7 × 11 × 19 × 23 = 33649 7 × 13 × 17 × 19 = 29393 7 × 13 × 17 × 23 = 35581 7 × 13 × 19 × 23 = 39767 7 × 17 × 19 × 23 = 52003 11 × 13 × 17 × 19 = 46189 11 × 13 × 17 × 23 = 55913 11 × 13 × 19 × 23 = 62491 11 × 17 × 19 × 23 = 81719 13 × 17 × 19 × 23 = 96577
    2 points
  5. Sorry to see your valuable time was wasted by Barand providing you free professional consulting, custom built code and hand holding. 😣
    2 points
  6. Once again we have no idea what the data you are processing looks like. Post the output from this code... echo '<pre>' . var_export($data, 1) . '</pre>';
    2 points
  7. the code is doing exactly what it was written to do, build a <tr><td>num</td></tr> for each number. if you want to produce a single <tr></tr>, you would need to add the opening <tr> before the start of the looping and add the closing </tr> after the end of the looping.
    2 points
  8. @gizmola With my model you would need to bring the ticket date into the equation SELECT s.id, s.row, s.seat_no FROM seat s LEFT JOIN booking b ON b.seat_id = s.id AND b.screening_id = 35 AND B.ticket_date = '2024-01-03' -- also required WHERE s.screen_id = 1 AND b.id IS NULL; As it is, a screening record states that the movie will be screened at time T each day between X and Y. On reflection, although requiring more rows, it would be better to have a screening record for every individual screening, giving... then your query would work as it is. Alternatively, to get vacant seats for a screening (and only requiring the screening id as input - if the screening id is known then the screen id is also known) you could SELECT s.id, s.row, s.seat_no FROM screening sg JOIN seat s ON sg.screen_id = s.screen_id LEFT JOIN booking b ON b.screening_id = sg.id AND b.seat_id = s.id WHERE sg.id = 35 AND b.id IS NULL
    2 points
  9. The main problem is that this $email_to = "email1@website.com", "email2@whatever.com"; isn't going to work. You can't just list multiple email address strings like that. But before that, the other problem is that you're manually trying to send emails. That's almost always bad: emails are hard, and doing it yourself is pretty much always going to go badly. Switch to a library like PHPMailer or SwiftMailer, which will not only be able to do emails properly but also make it easier to do things like add multiple recipients.
    2 points
  10. The only MyIsam-only functionality that I can think of is the ability to have a compound primary key EG PRIMARY KEY (year, number) where the 2nd part auto_increments within the first part, so if you have CREATE TABLE `test1` ( `year` int(11) NOT NULL, `number` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`year`,`number`) ) ENGINE=MyISAM ; mysql> select * from test1; +------+--------+ | year | number | +------+--------+ | 2022 | 1 | | 2022 | 2 | +------+--------+ mysql> insert into test1 (year) values (2022), (2022), (2023), (2023), (2024); mysql> select * from test1; +------+--------+ | year | number | +------+--------+ | 2022 | 1 | | 2022 | 2 | | 2022 | 3 | | 2022 | 4 | | 2023 | 1 | | 2023 | 2 | | 2024 | 1 | +------+--------+
    2 points
  11. I've never used it personally but I've heard good things about rector.
    2 points
  12. 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
  13. I agree with Gizmola^. Using a multidimensional array ... $probs = [ 'QB' => [ 'RB' => [ 1 => 11.22, 2 => 3.91, 3 => 0.15 ], 'TE' => [ 1 => 5.17, 2 => 0.80, 3 => 0.00 ], 'QB' => [ 1 => 9.44, 2 => 0.00, 3 => 0.00 ], 'WR' => [ 1 => 10.46, 2 => 8.67, 3 => 4.53 ], 'K' => [ 1 => 3.81, 2 => 0.19, 3 => 0.00 ], 'D' => [ 1 => 2.85, 2 => 0.07, 3 => 0.00 ] ] // rinse and repeat with the other MVPs and FLEXs ]; $lineup = 'QB, WR, WR, RB, K'; $arr = array_map('trim', explode(',', $lineup)); $mvp = array_shift($arr); $counts = array_count_values($arr); $probability = 0; foreach ($counts as $p => $n) { $probability += $probs[$mvp][$p][$n]; } echo '<br>'.$probability; // 23.7
    2 points
  14. Moving from PHP 5.4.45 to PHP 8 is a significant version upgrade, and it's good that you are considering updating your code accordingly. Here are some points to consider: 1. mysql_query(): The mysql_ functions, including mysql_query(), have been deprecated and removed in later PHP versions. You should replace them with MySQLi or PDO. 2. PDO: While you've updated your code to use PDO, keep in mind that PDO is a database access layer providing a uniform method of access to multiple databases, including MySQL. It should work fine with MySQL 5.7.4-43. It's important to note that updating to PHP 8 and MySQL 5.7 may introduce other compatibility issues or deprecated features in your code. It's recommended to thoroughly test your application in a development environment before making these changes on your live server.
    2 points
  15. 2 points
  16. password_hash() and password_verify()
    2 points
  17. 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
  18. 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
  19. 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
  20. don't bother with the mysqli extension. it is overly complicated, inconsistent, and in the case of procedural vs OOP statements, has different error responses for the same root problem. instead, use the much simpler, consistent, and more modern PDO extension. in php8+, both the mysqli and PDO extensions use exceptions for errors by default. the line of code that @Barand posted enables exceptions for errors for the msyqli extension. when you use exceptions for database statement errors, php will 'automatically' display or log the raw database errors, via an uncaught exception error. therefore, you can remove any existing error handling logic, since it won't ever get executed upon an error, simplifying the code. you should also name the connection variable as to the type of connection it contains, $mysqli/$pdo. this will let anyone looking at the code know what extension it is using, and also let you search for which code has been converted and which hasn't. you also need to use a prepared query when supplying external, unknown, dynamic values to a query when it gets executed, so that any sql special characters in a value cannot break the sql query syntax, which is how sql injection is accomplished. if you switch to the much simpler PDO extension, after you prepared the query, you can simply supply an array of the input values to the ->execute([...]) call.
    2 points
  21. try $res = $pdo->query("SELECT storeid , description FROM merge ORDER BY storeid "); foreach ($res as $r) { $data[$r['storeid']][] = $r['description']; } echo "<table>\n"; foreach ($data as $store =>$prods) { echo "<tr style='vertical-align: top;'><td>$store</td><td>" . join('<br>', $prods) . "</td></tr>\n"; } echo "</table>\n";
    2 points
  22. Does the uploads/ directory exist? And does it exist at (I think:) /paypal/uploads?
    2 points
  23. 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
  24. Easier with PDO $stmt = $pdo->prepare($sql); $stmt->execute($SearchValues);
    2 points
  25. lol. all the javascript posted for this problem is unnecessary. upon the DOM being loaded/rendered, it's getting data that's known at the time of the request for the map2.php page (the value being sent to getBookedSeats.php is coming from a js variable that's being set to a php value echoed on the page.) this is just a roundabout wall of code and data churn. here's a list of why this is not working - 1. you are making a POST request to getBookedSeats.php. the value won't be in any $_GET variable and adding an isset() won't make it work. all that did is hide the problem and caused the php code to be skipped over. 2. you are sending JSON encoded data to getBookedSeats.php. you would need to use the following to read and decode the data - $json = file_get_contents('php://input'); $data = json_decode($json,true); 3. the value will then be in $data['screeningId'], because that's the name of the javascript variable holding the value that you are sending in the ajax fetch request, which is a value that is coming from php in the first place.
    1 point
  26. This is almost always the wrong way to do things. You cannot guarantee that this update process will run every, single day. This is Technology - stuff happens. Updating every record is a lot of [unnecessary] work for your database to do and will, almost certainly, lock the entire table, causing other issues. Showing stuff to Users is not the database's job. You'll write an Application that the Users interact with and that will show them your "remaining time". I'm sorry, but why? Users these days want instant responses, not arbitrary and artificially-enforced delays. If you are interested in a particular date & time, then work out when that is and store that. You never need to change it, "in bulk" or at all, Your application can calculate how long it is until "Real Time" catches up with it and show that duration to the User, no matter what they do in the meantime (refreshing, logging off-and-on again, etc. ), and You can easily tell once you have reached it in a SQL query. Keep it Simple ... Regards, Phill W.
    1 point
  27. There is a popular library for enhancing the basic datetime api, called Carbon. One of the nice things that comes with it is "Human Diff". See the manual: https://carbon.nesbot.com/docs/#api-humandiff
    1 point
  28. I would add the following suggestion regarding this type of logic if ($row['fk_usertypes_id'] ==1) { echo "Hello 1"; } else { echo "Hello 2"; } Just because the value is not 1, you should not assume the value is 2 - even if those are the only expected values. I've seen multiple production issues where such logic was implemented and unexpected conditions caused impactful bugs. If you only expect the value to be 1 or 2, I would do the following. if ($row['fk_usertypes_id'] == 1) { echo "Hello 1"; } else if (($row['fk_usertypes_id'] == 2) { echo "Hello 2"; } else { //Throw error echo "Unhandled error"; } Although at this point a switch() statement might make more sense.
    1 point
  29. your login code should put the user's id (auto-increment primary index) into a uniquely named session variable, such as $_SESSION['user_id']. you would then test if that session variable is set on any page that requires a logged in user. you would query on each page request, using $_SESSION['user_id'], to get any other user data, such as the username, email, access type, ... don't do that. once you have the user's data, just test/use it on a single page to control what content gets displayed on the page and what action the user can perform on that page. since this query to get the access type will at most match one row of data, don't use a loop at all. just fetch/test the data. i reviewed your previous thread on this forum. you were using a single fetch() statement in it. what happended? this implies your db() function creates a new database connection every time it is called. don't do that. a database connection is one of the slowest operations you can perform on a page. your application should create one database connection, then use that single connection for every database operation on the page. don't do this. as of php8, the default setting for PDO error handling is to use exceptions for all the database statements that can fail - connection, query, exec, prepare, and execute. with exceptions, any discrete error check logic in your code won't ever get executed upon an error since execution transfers elsewhere. this is one of the great points of using exceptions. your main code will only 'see' error free execution. if execution continues past a statement that can fail, you know the statement was successful without needing conditional logic to test if it was or was not. this simplifies the code, allowing you to remove all the now unnecessary conditional logic. the only time you should catch and handle a database exception in your code is for recoverable user error, such as when inserting/updating duplicate or out of range user data. for all other error numbers and all other query types, just let php catch and handle any database exception. if you set the default fetch mode to assoc when you make the database connection, you don't need to specify it in each fetch statement, simplifying the code.
    1 point
  30. It is high time I tipped my cap to phpfreaks, small but mighty. Phpfreaks may be small in population, but the sense and knowledge derived from it are immeasurable. Here, you find gurus who are always ready to solve our problems. Since I joined this forum, I no longer bother flipping to any other place to get my problems solved because phpfreaks is competent. Please do not relent, and keep up the good work. Regards to you all.
    1 point
  31. The relevant link was in my reply... which linked to ... https://www.php.net/mysqli_query
    1 point
  32. you would not UPDATE amounts in a table to track this data, since that doesn't provide an accounting trail should a programming mistake, duplicate entry, or nafarious activity alter a value. these are derived amounts that you would calculate when needed. you would have an invoice_accounting (or similar named) table, that gets a row inserted for every amount that affects an invoice amount. you would query when needed (a UNION between the invoice(s) table and the invoice accounting table) to determine the current total +/-/0 for any invoice.
    1 point
  33. P.S. Your main problem is the spaghetti coding style you are using, continually moving in and out of php within the html. Try keeping them as separate as possible with php first then the html section. So something like... <?php function yearEntryOptions($current) { $CurrentMonth = date('n'); $opts = ''; for ($i = -1; $i <= 1; $i++) { $y = date('Y') + $i; $sel = $current == $y ? 'selected' : ''; $dis = ($CurrentMonth != 1 && $i == -1) || ($CurrentMonth <= 10 && $i == 1) ? 'disabled' : ''; $opts .= "<option $sel value='$y' $dis>$y</option>\n"; } return $opts; } ?> <html> <body> <select name="YYYY_Entry" style="width:60px"> <?= yearEntryOptions($SE_YYYY_Entry) ?> </select> </body> </html>
    1 point
  34. Hey there! I totally get what you mean. It seems like the posts you're seeing are from 2022, and the banner warning about responding to old posts might give the impression that the forum is inactive. However, it's worth noting that the activity on forums can vary across different categories. Some categories may indeed have older posts, while others might have more recent activity. For instance, in the PHP and MySQL categories, you might find more up-to-date discussions
    1 point
  35. Checkboxes are only submitted in form data when they are checked.
    1 point
  36. No, password_hash handles all the work for you. Including salting. Don't do anything extra.
    1 point
  37. What will your code do if there aren't any rows from the query? (I know the answer - I want you to read through it and think about what will happen)
    1 point
  38. Is that an assigned table design or are you able to make your own changes? I ask because it is need of some normalization... you have repeating data in the days column. you have dependent data (the dayplate is derived from the days). it would be better to store 2 time columns (start and end) instead of the timeplate to make it easier to determine, say, "show streets where there is a restriction at 8:30am." ie WHERE 08:30 BETWEEN start AND end
    1 point
  39. Here's one way $student_scores = [ [ 'name' => 'Student A', 'score' => 68, 'pos' => '' ], [ 'name' => 'Student B', 'score' => 52, 'pos' => '' ], [ 'name' => 'Student C', 'score' => 73, 'pos' => '' ], [ 'name' => 'Student D', 'score' => 80, 'pos' => '' ], [ 'name' => 'Student E', 'score' => 56, 'pos' => '' ], [ 'name' => 'Student F', 'score' => 77, 'pos' => '' ], [ 'name' => 'Student G', 'score' => 73, 'pos' => '' ], [ 'name' => 'Student H', 'score' => 49, 'pos' => '' ], [ 'name' => 'Student I', 'score' => 88, 'pos' => '' ], [ 'name' => 'Student J', 'score' => 90, 'pos' => '' ] ]; $scores = array_column($student_scores, 'score'); rsort($scores); foreach ($student_scores as &$s) { $s['pos'] = array_search($s['score'], $scores) + 1; } // sort scores by position uasort($student_scores, fn($a, $b) => $a['pos']<=> $b['pos']); // show results echo '<pre>' . print_r($student_scores, 1) . '</pre>'; giving Array ( [9] => Array ( [name] => Student J [score] => 90 [pos] => 1 ) [8] => Array ( [name] => Student I [score] => 88 [pos] => 2 ) [3] => Array ( [name] => Student D [score] => 80 [pos] => 3 ) [5] => Array ( [name] => Student F [score] => 77 [pos] => 4 ) [2] => Array ( [name] => Student C [score] => 73 [pos] => 5 ) [6] => Array ( [name] => Student G [score] => 73 [pos] => 5 ) [0] => Array ( [name] => Student A [score] => 68 [pos] => 7 ) [4] => Array ( [name] => Student E [score] => 56 [pos] => 8 ) [1] => Array ( [name] => Student B [score] => 52 [pos] => 9 ) [7] => Array ( [name] => Student H [score] => 49 [pos] => 10 ) )
    1 point
  40. Add some extra checks in to prevent the rendering of dates in the table if they are in the past. This should work: <section class="content" id="termin"> <?php $dt = new DateTime; $thisWeek = $dt->format('W'); $thisYear = $dt->format('o'); if (isset($_GET['year']) && $_GET['year'] >= $thisYear && isset($_GET['week']) && $_GET['week'] >= $thisWeek ) { $dt->setISODate($_GET['year'], $_GET['week']); } else { $dt->setISODate($dt->format('o'), $dt->format('W')); } $year = $dt->format('o'); $week = $dt->format('W'); ?>
    1 point
  41. What you downloaded is the source code of the software. You need to compile it to get an actual program you can use. You can do that relatively easily on Linux since that's the environment it was designed for. Whether it can be done and how difficult it would be to do on Windows is unknown. Something like MinGW might help. A .md file is just a text file. Any text editor will open and display it just fine. It might not open with a simple double-click as the .md extension probably is not registered, but you can always open the editor and use it's file->open command (or just rename the file to .txt and double-click).
    1 point
  42. You're going to need to setup some kind of security check - Here's a example function check_security($id) { // Example of PHP Connection $db = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password'); $sql = "SELECT security FROM user_table WHERE id=:id LIMIT 1"; $stmt = $db->prepare($sql); // Bind the named parameter :id to the value $id $stmt->bindParam(':id', $id, PDO::PARAM_INT); $stmt->execute(); // Fetch the result as an associative array $result = $stmt->fetch(PDO::FETCH_ASSOC); if ($result && $result['security'] === 'admin') { return true; } return false; } then simply // Check if the user has admin security by calling the check_security function if (check_security($id)) { // If the function returns true, echo out an HTML anchor tag that leads to delete-post.php // The id of the row to delete is passed in the query string of the URL // Inside the anchor tag is a button with the class btn3 and the text DELETE echo '<a href="delete-post.php?id='.$row['id'].'"><button class="btn3">DELETE</button></a>'; } You will still need to check the delete-post.php in order to stop some one from directly accessing that file. This is just a quick example and you can even do that for the original user - just check to see if the user's id for the post matches the original poster's id. Just setup an addition column like user_id in the database table that contains the posts (if you haven't already done so).
    1 point
  43. Example data TABLE: client TABLE: project +----+-----------+----------+ +----+---------------+-----------+------------+ | id | firstname | lastname | | id | project_name | client_id | start_date | +----+-----------+----------+ +----+---------------+-----------+------------+ | 1 | Scott | Chegg | | 1 | Project Alpha | 4 | 2022-12-01 | | 2 | Laura | Norder | | 2 | Proect Beta | 2 | 2023-01-15 | | 3 | Tom | DiCanari | | 3 | Project Gamma | 4 | 2023-03-01 | | 4 | S | Tonin | | 4 | Project Delta | 1 | 2023-03-20 | +----+-----------+----------+ +----+---------------+-----------+------------+ Query SELECT project_name , start_date , CONCAT(c.firstname, ' ', c.lastname) as client FROM project p JOIN client c ON p.client_id = c.id ORDER BY client, start_date; +---------------+------------+--------------+ | project_name | start_date | client | +---------------+------------+--------------+ | Proect Beta | 2023-01-15 | Laura Norder | | Project Alpha | 2022-12-01 | S Tonin | | Project Gamma | 2023-03-01 | S Tonin | | Project Delta | 2023-03-20 | Scott Chegg | +---------------+------------+--------------+ Now change the first name of client 4 and re-query UPDATE client SET firstname = 'Sarah' WHERE id = 4; SELECT project_name , start_date , CONCAT(c.firstname, ' ', c.lastname) as client FROM project p JOIN client c ON p.client_id = c.id ORDER BY client, start_date; +---------------+------------+--------------+ | project_name | start_date | client | +---------------+------------+--------------+ | Proect Beta | 2023-01-15 | Laura Norder | | Project Alpha | 2022-12-01 | Sarah Tonin | | Project Gamma | 2023-03-01 | Sarah Tonin | | Project Delta | 2023-03-20 | Scott Chegg | +---------------+------------+--------------+
    1 point
  44. I would use these table (or similar) TABLE: category TABLE: model TABLE: sale +----+------------+ +----+------------+-------------+ +----+------------+-------+--------+---------+ | id | cat_name | | id | model_name | category_id | | id | model_id | year | month | qty | +----+------------+ +----+------------+-------------+ +----+------------+-------+--------+---------+ | 1 | Category A | | 1 | Model 1 | 1 | CREATE TABLE `sale` ( | 2 | Category B | | 2 | Model 2 | 1 | `id` int(11) NOT NULL AUTO_INCREMENT, | 3 | Category C | | 3 | Model 3 | 1 | `model_id` int(11) DEFAULT NULL, +----+------------+ | 4 | Model 4 | 2 | `year` year(4) DEFAULT NULL, | 5 | Model 5 | 2 | `month` tinyint(4) DEFAULT NULL, | 6 | Model 6 | 2 | `qty` int(11) DEFAULT NULL, | 7 | Model 7 | 3 | PRIMARY KEY (`id`), | 8 | Model 8 | 3 | UNIQUE KEY `idx_model_yr_mth` (`model_id`,`year`,`month`) +----+------------+-------------+ ) For the javascript, I prefer to use a combination of class and data attriibutes for element grouping EG <?php require 'db_inc.php'; // USE YOUR OWN $pdo = pdoConnect('db2'); // CONNECTION CODE ################################################################################ # PROCESS POSTED DATA # ################################################################################ if ($_SERVER['REQUEST_METHOD']=='POST') { #echo '<pre>' . print_r($_POST, 1) . '</pre>'; $year = $_POST['year']; $pdata = []; foreach ($_POST['qty'] as $mod => $mdata) { foreach ($mdata as $mth => $qty) { if (intval($qty) && intval($mth) && intval($year) && intval($mod) ) { $pdata[] = sprintf("(%d, %d, %d, %d)", $mod, $year, $mth, $qty ); } } } $pdo->exec("INSERT INTO sale (model_id, year, month, qty) VALUES " . join(',', $pdata) . "ON DUPLICATE KEY UPDATE qty = VALUES(qty) "); header("Location: ?year=$year"); exit; } ################################################################################ # TABLE HEADINGS # ################################################################################ $year = $_GET['year'] ?? date('Y'); $dt1 = new DateTime("{$year}-01-01"); $dt2 = clone $dt1; $dt2->modify("+12 months"); $range = new DatePeriod($dt1, new DateInterval('P1M'), $dt2); $theadings = "<tr><th>S.No</th><th>Category</th><th>Model</th>"; foreach ($range as $d) { $theadings .= "<th>" . $d->format('My') . "</th>"; } $theadings .= "<th>Total</th><th>MS &nbsp;%</th></tr>\n"; ################################################################################ # CATEGORIES AND MODELS # ################################################################################ $res = $pdo->prepare("SELECT c.id as cid , cat_name , m.id as mid , model_name , month , qty FROM category c JOIN model m ON c.id = m.category_id LEFT JOIN sale s ON s.year = ? AND m.id = s.model_id ORDER BY cid, mid, month "); $res->execute([ $year ]); $empty = array_fill_keys(range(1,12), null); $data = []; ################################################################################ # PUT RESULTS INTO SUITABLY STRUCTURED ARRAY TO MATCH THE REQUIRED OUTPUT # ################################################################################ foreach ($res as $r) { if (!isset($data[$r['cid']])) { $data[$r['cid']] = ['cat' => $r['cat_name'], 'models' => [] ]; } if (!isset($data[$r['cid']]['models'][$r['mid']])) { $data[$r['cid']]['models'][$r['mid']] = [ 'mod' => $r['model_name'], 'vals' => $empty ]; } if ($r['qty']) { $data[$r['cid']]['models'][$r['mid']]['vals'][$r['month']] = $r['qty']; } } ################################################################################ # TAKE THE ARRAY DATA AND OUTPUT TO THE TABLE # ################################################################################ $tdata = ''; $n = 1; $prev = ''; foreach ($data as $catid => $cdata) { $catname = $cdata['cat']; $tdata .= "<tbody data-cat='$catid}'>\n"; foreach ($cdata['models'] as $modid => $mdata) { $modname = $mdata['mod']; $tdata .= "<tr class='qty-row' data-model='$modid'><td>$n</td><td>$catname</td><td>$modname</td>"; $catname = ''; foreach ($mdata['vals'] as $m => $qty) { $tdata .= "<td><input class='w3-input w3-border qty-mth' data-cat='$catid' data-model='$modid' data-mth='$m' name='qty[$modid][$m]' value='$qty'> </td>"; } $tdata .= "<td><input class='w3-input w3-border qty-yr' data-cat='$catid' data-model='$modid' ></td> <td><input class='w3-input w3-border ms-yr' data-cat='$catid' data-model='$modid' ></td> "; ++$n; } $tdata .= "</tbody>\n <tr class='total-row'><td colspan='3'>TOTAL</td>"; for ($m=1; $m<=12; $m++) { $tdata .= "<td><input class='w3-input w3-border tot-mth' data-cat='$catid' data-mth='$m' ></td>"; } $tdata .= "<td><input class='w3-input w3-border tot-yr' data-cat='$catid' ></td> <td>&nbsp;</td> "; } ################################################################################ # FUNCTIONS # ################################################################################ function yrOpts($current) { $yrs = range(date('Y'), date('Y')-4); $opts = "<option value=''>- select year -</option>\n"; foreach ($yrs as $y) { $sel = $current==$y ? 'selected':''; $opts .= "<option $sel>$y</option>\n"; } return $opts; } ?> <!DOCTYPE html> <html lang='en'> <head> <meta charset='utf-8'> <title>Example</title> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type='text/javascript'> $(function() { $("#year").change( function() { let yr = $(this).val() location.href = "?year="+yr }) $(".qty-mth").on('input', function() { calc_totals() }) calc_totals() }) function calc_totals() { $(".qty-yr").each(function(k,v) { let mod = $(v).data("model") let toty = 0 $(".tot-yr").val(0) $(".qty-mth[data-model="+mod+"]").each(function(k1,v1) { let q = parseInt($(v1).val()) toty += isNaN(q) ? 0 : q }) $(v).val(toty) }) $(".tot-yr").each(function(k,v) { let cat = $(v).data("cat") calc_cat_totals(cat) calc_percents(cat) }) } function calc_cat_totals(cat) { let ytot = 0 for (let m=1; m<=12; m++) { let mtot = 0 $(".qty-mth[data-cat="+cat+"][data-mth="+m+"]").each(function(k,v){ let q = parseInt($(v).val()) mtot += isNaN(q) ? 0 : q ytot += isNaN(q) ? 0 : q }) $(".tot-mth[data-cat="+cat+"][data-mth="+m+"]").val(mtot) } $(".tot-yr[data-cat="+cat+"]").val(ytot) } function calc_percents(cat) { let ytot = $(".tot-yr[data-cat="+cat+"]").val() if (ytot==0) return $(".qty-yr[data-cat="+cat+"]").each(function(k,v) { let mod = $(v).data("model") let q = $(v).val() * 100 / ytot q = q.toFixed(1) $(".ms-yr[data-model="+mod+"]").val(q) }) } </script> <style type='text/css'> table { width: 100%; border-collapse: collapse; margin: 20px 0; } th, td { padding: 2px 4px; font-size: 9pt; text-align: center; } th { background-color: black; color: white; } .qty-mth, .tot-mth, .qty-yr, .ms-yr, .tot-yr { width: 45px; margin: 0 auto; } .total-row { background-color: #D0D0D0; } .qty-row { background-color: #F8F8F8; } input { text-align: center; } </style> <script type='text/javascript'> </script> </head> <body> <div class='w3-container w3-padding'> <form id='form1' method='POST'> <div class='w3-bar'> <div class='w3-bar-item'>Year </div> <select id='year' name='year' class='w3-bar-item w3-border'> <?= yrOpts($year) ?> </select> </div> <table border='1' class="table" id="myTable2"> <thead> <?= $theadings ?> </thead> <?= $tdata ?> </table> <div class='w3-container w3-center'> <button class='w3-button w3-blue'>Save data</button> </div> </form> </div> </body> </html>
    1 point
  45. JQuery It makes life a lot easier when using javascript. <script type='text/javascript'> $(function() { $(".circ3").mouseover(function() { // handle mouseover event on elements with class "circ3" $(this).css("fill", "red") // $(this) is the target element - change its fill color $(this).css("fill-opacity", "1") // - change its opacity $("#grp1").removeClass('txt1').addClass('txt2') // change class of element with id = "grp1" }) $(".circ3").mouseout(function() { $(this).css("fill", "blue") $(this).css("fill-opacity", "0.3") $("#grp1").removeClass('txt2').addClass('txt1') }) }) </script>
    1 point
  46. "Tag" is still fine. It's not like that term has died off or anything. And it applies to all... well, to all tags... not just certain ones. "META tag", "HTML tag", "NAV tag", whatever. "Element" is the other one in common usage. Means the same thing. Probably a bit more proper. Maybe the word you're looking for is "semantic"? Because the idea of those new tags/elements is that they have a semantic meaning: while DIV is just whatever, HEADER is specifically for "a header", and NAV is specifically for navigation, and such. Makes it easier for automated processes (like search engines) to analyze a page.
    1 point
  47. Q1. yes, it needs a stored result to count the rows. Q2. yes, it clears the stored result from the internal buffer freeing memory. It's good practice to always clean up after yourself. Q3. either use mysqli_* or PDO, most people use PDO for its simple API. PDO has no pdo_* functions, only it's Object Oriented interface. Q4. bad, but not in the way of ugly or "newbie" but because it can be exploited by hackers; it will be hard to maintain (lots of duplicate code, weird indents, no separation between HTML and PHP, ..); using die() in a script is not good UX, the user can't get back to the homepage or try another search;
    1 point
  48. You avoid SQL injection when you use prepared statements assuming you write the full SQL and don't inject foreign SQL using variables. So while this is safe: mysqli_stmt_prepare($stmt, 'SELECT * FROM users WHERE username = ?'); This is not: mysqli_stmt_prepare($stmt, "SELECT * FROM $tbl WHERE $col_1 = ?"); Because now a hacker can control what the prepared statement is. So this could end up being: mysqli_stmt_prepare($stmt, "SELECT * FROM users; DELETE FROM users WHERE 1 = ?"); Which is not what you intended. -- I assume nobody told you, because I don't think anyone read over your code like I did. Walls of text do that to people. Which is why, as a programmer, we divide the program into little pieces like lego blocks. Building or re-using blocks to build a car or a house. We even have "rules" defining how small things should be: https://refactoring.guru/refactoring/smells/bloaters -- I assumed it was either a search engine or an SEO kinda tool. You might want to read up on cursor based pagination: https://medium.com/swlh/how-to-implement-cursor-pagination-like-a-pro-513140b65f32 as LIMIT OFFSET is not ideal for pagination (performance wise).
    1 point
  49. You're generally not going to find such specific examples in a manual. You need to use the documentation and examples given to learn the components so you can then put them together as needed to accomplish your task. Perhaps you should lookup what getAttribute does. You might also need to read up on how the DOM (the link talks JavaScript, but the interfaces work the same in any language) works in general if you want to continue using DOMDocument. Spend some time reading the documentation for DOMDocument and some about the DOM and you should be able to figure out where you went wrong in your above attempts.
    1 point
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.