Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation since 04/23/2023 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. 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. It seems like you're trying to dynamically retrieve column names from the first loop and then use them to fetch corresponding data from the database in the second loop. However, you're facing issues with the data retrieval part. Let's correct the code: fputcsv($csvfile, $export_column_name_array, $delimiter); $stmt2 = $conn->prepare($sql_built_statement); //$stmt2->bind_param("ii", $company_id, $company_id); WILL ADD THIS LATER ONCE WORKING $stmt2->execute(); $result2 = $stmt2->get_result(); if($result2 != NULL){ // Retrieve data while($row2=$result2->fetch_assoc()){ // Initialize an empty data array for each row $data_array = array(); // Add data for each column foreach ($export_column_name_array as $value) { // Push data for each column into the data array $data_array[] = $row2[$value]; } // Write the data array to the CSV file fputcsv($csvfile, $data_array, $delimiter); } } fclose($csvfile); In this corrected code: We loop through each row of the fetched data and initialize an empty $data_array for each row. Within the row loop, we iterate through each column name from $export_column_name_array. For each column name, we fetch the corresponding data from the $row2 associative array and add it to the $data_array. After populating the $data_array with data for all columns, we write it to the CSV file using fputcsv(). The process repeats for each row fetched from the database until all rows have been processed. i hope This should correctly populate your CSV file with the data fetched from the database, using the dynamic column names obtained from $export_column_name_array. Best Regard Danish hafeez | QA Assistant ICTInnovations
    1 point
  26. 1. If you use /s for regex delimiters (at the beginning and end) then any /s you want inside the regex have to be escaped. Look at what your original had. 2. What's the rest of the code?
    1 point
  27. It's just an example of utilizing variable interpolation into a string. In general it is easier to read and maintain code that doesn't have a bunch of unnecessary string concatenation, when you can just use interpolation as Barand did.
    1 point
  28. don't unconditionally loop over $_POST data. hackers/bots can submit 100's or 1000's of fields (php had to add a setting to limit the number of fields), with their own field names (which will allow sql injection in the query), not yours. you should instead have an array the defines the expected fields, then use this definition to control what your code does. this is referred to as a data-driven design. see this example - // define the expected form fields $fields = ['easting', 'northing', 'purpose', 'country', 'admin1', 'admin2', 'admin3', 'settlement', 'orig_wellno', 'date_completed', 'coord_sys', 'elev', 'status']; $col = []; // array of columns $data = []; // array of prepared query input values // add the well no $col[] = '`well_no`'; $data[] = $_SESSION['well_no']; // use whatever the actual session variable is // loop over the defining array foreach($fields as $field) { // note: empty considers 0 or '0' to be an empty value. this will prohibit a numerical zero value being used. // you should instead test if the value is or is not an empty string. if($_POST[$field] !== '') { $col[] = "`$field`"; $data[] = $_POST[$field]; } } // build the sql query $sql = "INSERT INTO well_parent (".implode(',',$col).") VALUES (".implode(',',array_fill(0,count($col),'?')).")"; // examine the result echo $sql; echo '<pre>'; print_r($data); echo '</pre>';
    1 point
  29. Here is another way of writing this $User = current_user(); // I assume this 'current_user function is something you wrote $sql = 'SELECT fk_usertypes_id FROM users WHERE email=:User'; $statement = db()->prepare($sql); $parms = array('User'=>$User); if (!$statement->execute($parms)) { echo "Query did not run"; exit(); } // You probably don't need a loop here, but here you go while($row = $statement->fetch(PDO::FETCH_ASSOC)) { echo "UserType " . $row['fk_usertypes_id'] . '</br>'; } // this code makes no sense since you are not in the loop here. /* if ($bob == 1) echo "Hello 1"; else echo "Hello 2"; */ echo "<p><a href='index.php'>Home</a></p>"; view('footer'); // I HAVE NO IDEA WHAT "view" IS SUPPOSED TO DO FOR YOU Made some changes to your use of PDO and the way your query results are being processed. Of course, as already mentioned, you probably only have one results row since the email should be unique (perhaps). And I'm assuming that 'bob' is representing the sole result value, the usertype id, hence I left it out.
    1 point
  30. New member, looks to learn more about php and get help in areas 🙂 Thanks for having me
    1 point
  31. https://symfony.com/doc/current/doctrine.html "Symfony provides all the tools you need to use databases in your applications thanks to Doctrine, the best set of PHP libraries to work with databases. These tools support relational databases like MySQL and PostgreSQL and also NoSQL databases like MongoDB." I think it's just a case of learning and figuring it out.
    1 point
  32. this is because as of php8 the mysqli (and PDO) extension uses exceptions for all database statement errors, by default, and execution transferred to the nearest correct type of exception handling (try/catch logic) in your code or to php's exception handling if there is no correct type of exception handling in your code, and all your code after the point where an exception occurred is not executed. a great point of using exceptions is that your main/inline code only 'sees' error free execution. if execution continues past a statement that throws an exception, you know that there was no error, without needing logic in your code to test if there was or was not an error. this lets you eliminate all the existing conditional logic in your code testing for connection and query errors, since it won't ever get executed upon an error, simplifying the code. because you didn't get any error indication at all, that means that php's error related settings are not set up on your system so that php will help you by reporting and displaying all the errors it detects. php's error_reporting should always be set to E_ALL and when learning, developing, and debugging code/query(ies), display_errors should be set to ON. when running code on a live/public server, display_errors should be set to OFF and log_errors should be set to ON. these settings should be in the php.ini on your system so that they can be set or changed at a single point. stop and start your web server to get any changes to the php.ini to take effect and check using a phpinfo() statement in a .php script file that the settings actually go changed to the desired values. the only time you should catch and handle a database exception in your code is for user recoverable errors, such as when inserting/updating duplicate user submitted data, which is something you are/should be doing. at a minimum, the email database column should be defined as a unique index. you would then have exception try/catch logic in your code around at least the execute() statement, check in the catch block if the error number is for a duplicate index error, and setup a message for the user that the email is already in use. for all other error numbers, just re-throw the exception and let php handle it. and if that wasn't enough, here's a list of practices, most of which will simplify the code - the form and form processing code should be on the same page. the code for any page should be laid out in this general order - 1) initialization, 2) post method form processing, 3) get method business logic - get/produce data needed to display the page, 4) html document. the post method form processing code should only test if the request method == 'POST'. this is because there are cases where the submit button won't be set. you should keep the form data as a set, in a php array variable, then operate on elements in this array variable throughout the rest of the code, i.e. don't write out line after line of code that copies variables to other variables for nothing. you should trim all user entered data, mainly so that you can detect if it was all white-space characters, before validating it. after you do item #3 on this list, you can trim all the data using one single line of code. you should validate all input data, on the server, before using it, storing user/validation errors in an array using the field name as the main array index. except for unchecked checkbox/radio fields, all form fields will be set once the form has been submitted. there's no good reason to have isset() statements for always-set fields, and in fact doing so hides typo mistakes. as @Barand has already pointed out, you should be using a prepared query and switch to the much simpler and more modern PDO extension. after successfully processing the form data, you should execute a redirect to the exact same URL of the current page to cause a get request for that page. this will prevent the browser from trying to resubmit the form data should that page get reloaded or browsed away from and back to. if you want to display a one-time success message, store it in a session variable, then test, display, and clear that session variable at the appropriate location in the html document. to get a form to submit to the same page it is on, leave out the entire action attribute. if you put the closing </label> tag after the form field it corresponds to, you can leave out the for and matching id attributes, simplifying the code and eliminate a source of typos. in the name form field, your for attribute doesn't match the id attribute. the closing / in tags is no longer used. you need to validate the resulting web pages at validator.w3.org the form should be 'sticky' and repopulate the form fields with any existing values/choices so that the user doesn't need to keep reentering data over and over upon an error. any dynamic value you output in a html context should have htmlentities() applied to it to help prevent cross site scripting.
    1 point
  33. to convert old mysql_ based code, you need to 1) convert the database extension to a currently supported one, 2) provide protection against sql special characters in a value being able to break the sql query syntax, which is how sql injection is accomplished, and 3) handle database statement errors. for item #1, the PDO extension is much simpler and more modern then the mysqli extension. for item #2, the simplest way of doing this is to use prepared queries, which provides protection for all data types. converting any query to a prepared query is straightforward - remove the php variables (keep these for later) and any single-quotes, {}, and quotes/concatenation dots that were used to get the variables into the sql query statement. put a ? place-holder into the sql query statement for each variable you removed. prepare the query. supply an array of the variables to the ->execute([...]) call. note: any wild-card search characters, typically used with a LIKE comparison, are part of the value, not part of the sql query statement. for item #3, as of php8, both the mysqli and PDO extensions use exceptions by default for all the database statements that can fail - connection, query, exec, prepare, and execute. this simplifies your code, since you can remove any existing error handling logic. the only database exceptions you should catch and handle in your code are for user recoverable errors, such as when inserting/updating user submitted data (which you are not doing in this case.) in all other cases, simply let php catch and handle any database exceptions, where php will use its error related settings to control what happens with the actual error information (database statement errors will 'automatically' get displayed/logged the same as php errors.)
    1 point
  34. Object-oriented programming tends to be one of those things that doesn't really make sense until you find the right piece of information, or read something phrased in just the right way, or happen to be in the right frame of mind, at which point it all starts to click together. Which makes it hard to explain or teach. But basically, think of what you're doing - whatever it is - in terms of "Things" and the "Actions" those things can do. For now, forget programming and try applying it to real-world concepts. For example, I'm here sitting at my computer. The computer is a Thing. It has a power button, which also counts as its own Thing if you really want to go that deeply into it. If I perform the Action of "press the power button" on my computer, it'll either turn on (if it's off) or start shutting down nicely (if it's on). Or I can press the power button for a few seconds, in which case it'll either turn on or it will immediately turn off. And if I were to sketch that out in some pseudo-code, it might look like thing Computer { action PressThePowerButton(HowLong) { if PoweredOn { TurnOn // doesn't matter HowLong I pressed the button for... I think } else { if HowLong == Short { TurnOffGracefully } else { TurnOffImmediately } } } } For another example, I'm hungry because I haven't eaten today, so I'm going to go into the kitchen and cook something. I'll be using my stove Thing. It has four burner Things, each wired to one of four corresponding knob Things, and I can turn the knob right/left to turn on/off the associated burner. thing Stove { has Burner1 has Burner2 has Burner3 has Burner4 has Knob1 has Knob2 has Knob3 has Knob4 action Manufacture { Knob1 = create a new Knob connected to Burner1 Knob2 = create a new Knob connected to Burner2 Knob3 = create a new Knob connected to Burner3 Knob4 = create a new Knob connected to Burner4 } } thing Knob { knows about a Burner action TurnKnobRight() { set Burner on } action TurnKnobLeft() { set Burner off } } thing Burner { has Temperature action SetOn() { Temperature = High } action SetOff() { Temperature = Off } } Basically, 95% of OOP is thinking about Things and Actions, and by doing so you can take a complicated concept and reduce it into smaller pieces that are easier to manage. Like how I didn't try to "code" all the burner and knob stuff in one place: the knob knows how to do knob things, the burner knows how to do burner things, and they're hooked up to each other. But now I'm really hungry.
    1 point
  35. Thanks! I'll check those categories out! Thanks again for responding
    1 point
  36. Your first goal should be to reproduce the problem - because you can't know what to fix if you don't know what it is, and if you can't reproduce the problem then how will you know if your fix is working? 1. Gather more information. What SSL error? Surely there's some more specific information someone can give you? Like an actual error message, maybe? 2. Apply some logic. Which users are seeing this? What do they have in common? Do they have anything in common at all? Can the users successfully log in at another time? 3. Think about it from a technical standpoint. There are tons of possible SSL errors (see action item 1) but most of them boil down to the server not giving an appropriate cert. Do you have multiple servers? Is there a load balancer? Geographic CDNs? Are you sure they're all configured with identical information and up-to-date certificates? 4. Examine the details. "Certain static content not found" isn't any error message I've ever seen before - assuming it's a literal message. Where is it coming from? Under what conditions will it be emitted?
    1 point
  37. Some searching suggests the Twitch player has to do it itself, but in case that's not accurate, I would try using the FullScreen API triggered by when the screen orientation changes.
    1 point
  38. Personally, if I were writing a chess game I would use JavaScript and Canvas not PHP for the main coding part of the game.
    1 point
  39. Try this. You don't need date arithmetic for years. $start = 2020; $end = 2029; for ($y=$start; $y<=$end; $y++) { $session = sprintf('%d-%d', $y, $y+1); echo $session . '<br>'; } output 2020-2021 2021-2022 2022-2023 2023-2024 2024-2025 2025-2026 2026-2027 2027-2028 2028-2029 2029-2030
    1 point
  40. I don't know what gap you refer to but the line of code you posted needs changing to <?php echo '<pre>'; print_r($_POST, true); echo '</pre>'; ?> ^^^^ The "true" ( or you can use '1') prevents print_r() from returning a value after it has output the array. Ignore - as it was all on one line I assumed it was all one statement. But as print_r() is a debugging tool, why don't you just remove the line?
    1 point
  41. There are no internals of spl_autoload_register with regards to the locating and loading of a class. All the details of how that is done is up to the function you provide. All spl_autoload_register does is add your function to a list of functions that get called when an unknown class is referenced. Your function gets the fully qualified name of the class and has to use that to define that class, typically by converting the name to a file location and including that file. Your example essentially just uses the class name as-is as a file path and attempts to include that file. Since your class is defined as Hello then you get a filename of Hello.class.php with a capital H. Your actual filename however seems to be hello.class.php with a lower-case H. On a case-insensitive filesystem such as windows' ntfs, this would be fine and the file would be loaded. On a case-sensitive filesystem such as linux ext4, this is a problem and the file will fail to load. As mentioned, typically one would just use composer to handle class autoloading rather than defining your own function. Combine it with the PSR-4 standard (and ensure you get your case correct) and you mostly don't have to think about it at all.
    1 point
  42. 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
  43. Been a long time since I used a positioned popup window. Had to check the docs for the right options. You can center the popup on the screen by setting the top / left options. These control the top-left corner of the window, so to get it truly center you have to calculate the right offset. There's a standard formula for this. centerPoint = (sizeOfContainer - sizeOfThing) / 2 For this case, your sizeOfContainer is the screen width/height and the sizeOfThing are your popup window's width/height. Run that formula for each to get your top/left values and set them in the window options. const popupWidth = 400, popupHeight = 800; let top = (window.screen.height - popupHeight)/2; let left = (window.screen.width - popupWidth)/2; const win = window.open('', 'formpopup', 'width='+popupWidth+',height='+popupHeight+',resizable,scrollbars,top='+top+',left='+left); The final result may be slightly off (mostly in the height axis) due to the window UI elements since they are not part the calculation. The width/height you specify is for the content area of the window, the UI elements are added on top of that. If the slight offset bugs you, you can fix it after opening the window by re-calculating the offset using the window's outerWidth and outerHeight values for sizeOfThing, then using it's moveTo function to re-position it. top = (window.screen.height - win.outerHeight)/2; left = (window.screen.width - win.outerWidth)/2; win.moveTo(left, top); That may create a noticeable jump after the window opens though.
    1 point
  44. This is going to be a little more complicated with your date string, because you will need to turn the date string back into a valid javascript date, so that you set your form date element value. See if you can figure out how to do that. I'll give you a hint, on how to strip out the <br> tag from the date string, leaving you only with the text. function MyFunction(col, time) { const tbl = document.getElementById("myTable"); let dateValue = tbl.rows[0].cells[col].innerHTML; console.log('dateValue: ' + dateValue); dateValue = dateValue.replace('<br>', ' '); let dateEl = document.getElementsByName("tDatum"); let timeEl = document.getElementsByName("tVreme"); dateEl[0].value = dateValue; timeEl[0].value = time; } Another hint: google for javascript Date.parse()
    1 point
  45. The ORDER BY at the end of a set of UNIONs applies to the whole resultset. You may need a two-query approach (no data so untested) -- QUERY 1 CREATE TABLE copylinks SELECT * FROM `links` as l LEFT JOIN `accounts` as a ON a.id=l.author WHERE `l`.`live` = '1' ORDER BY `l`.`lastVisitDateTime` DESC LIMIT 10; -- QUERY 2 INSERT INTO copylinks SELECT * FROM `links` as l LEFT JOIN `accounts` as a ON a.id=l.author LEFT JOIN copylinks l2 ON l.id = l2.id WHERE `l`.`live` = '1' AND `l`.`linklocation` = 'main' AND l2.id IS NULL ORDER BY `l`.`timestamp` DESC; -- CHECK RESULT SELECT * FROM copylinks;
    1 point
  46. I'm confident that the less complicated one is the better solution. In terms of code, all you need is something that can tell what option the user selected, and something that can do what it needs to do to give the user the PDF they requested. Try writing the code yourself. If you have problems getting it to work then post what you have with a description of what you're trying to do and what problem(s) you're having with it.
    1 point
  47. Both of those use some third party API which you'd likely have to sign up for. Since I've never looked into either of them, I don't know how they operate and can't really judge the code. If your goal is to avoid third-parties and having to pay for access, then neither solution is great. AI isn't magic, if you don't really know what to ask for or ask for something too generic then you won't get good results. Knowing what to ask and how to ask for it means you need some working knowledge of the topic. Part of the issue with your prompts is that Bitcoin doesn't have some official gateway api, so you're getting solutions using third-party APIs. The way to interact with the bitcoin network yourself is by running a local node and using it's built-in RPC server. Once you know that, by studying how bitcoin works, you can develop a proper prompt that will get you some reasonable starting code. Prompt: Write a function in PHP that confirms a bitcoin transaction using a local node RPC server. /** * This function confirms a Bitcoin transaction using a local node RPC server. * * @param string $txid The transaction ID to confirm * @param string $rpc_user The RPC server username * @param string $rpc_password The RPC server password * @param string $rpc_host The RPC server host * @param int $rpc_port The RPC server port * * @return bool True if the transaction is confirmed, false otherwise */ function confirm_bitcoin_transaction($txid, $rpc_user, $rpc_password, $rpc_host, $rpc_port) { try { // Create a new RPC client instance $client = new \Nbobtc\Bitcoind\RpcClient($rpc_user, $rpc_password, $rpc_host, $rpc_port); // Get the transaction details $transaction = $client->getTransaction($txid); // Check if the transaction is confirmed if ($transaction['confirmations'] > 0) { return true; } else { return false; } } catch (\Exception $e) { // Log the error error_log("Error confirming Bitcoin transaction: " . $e->getMessage()); return false; } } This code is using some library to interface with the RPC server, you'll need to either find that library or write your own code to interact with the server. Yes, finding an AI forum (for ChatGPT or otherwise) would be ideal. I do not know of any. As far as crypto forums, the only one I know of is Bitcoin Talk. I'm sure your favorite search engine could help you find more for any subject.
    1 point
  48. There isn't a list of values for nodeName because the list would be infinitely long. The nodeName is the tag name in the source code. Since the code is interested in Sitemap files, and the root element of those files is either <sitemapindex> or <urlset> then you'll be looking for a nodeName of 'sitemapindex' or 'urlset'.
    1 point
  49. Search engines have changed a lot since 1998. They are about the change a lot again thanks to things like ChatGPT I suspect.
    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.