Jump to content

Strider64

Members
  • Posts

    482
  • Joined

  • Last visited

  • Days Won

    13

Everything posted by Strider64

  1. "await" is great if you need have all the data before you moving on especially good when developing a game. // Fetch the First ID const fetchFirstId = async () => { try { // fetch the data from the server const response = await fetch('get-first-id.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({resetScore: false}) }); // parse the response as JSON const data = await response.json(); id = data.first_id; // Grab the First ID the DB Table //console.log(id); await changeImageSource(data.image); await fetchQuestion(); await fetchWord(); // fetch the answers //await fetchImage(); } catch (error) { console.error(error); } };
  2. You can do a full text content search on a `content` field, but the main thing is you have to search a column in order to find what you are looking for. This is done in PDO, but gives an example on what I'm trying to say - // Extract the search term and heading from the request, if they exist. $searchTerm = isset($request['searchTerm']) ? $request['searchTerm'] : null; $heading = isset($request['heading']) ? $request['heading'] : null; // If a search term was provided, use a full-text search on the 'content' field. // Before this can work, you'll need to make sure your content column is indexed for full-text searching. // You can do this with the following SQL command: // Example: // ALTER TABLE gallery ADD FULLTEXT(content); if($searchTerm !== null) { $sql = "SELECT * FROM gallery WHERE MATCH(content) AGAINST(:searchTerm IN NATURAL LANGUAGE MODE) LIMIT 1"; $stmt = $pdo->prepare($sql); $stmt->bindValue(':searchTerm', $searchTerm); // If a heading was provided, search for exact matches on the 'heading' field. } else if($heading !== null) { $sql = "SELECT * FROM gallery WHERE heading = :heading LIMIT 1"; $stmt = $pdo->prepare($sql); $stmt->bindValue(':heading', $heading); // If neither a search term nor a heading was provided, throw an exception. } else { throw new Exception("No valid search term or heading provided"); } // Execute the prepared statement. $stmt->execute(); // Fetch the results and handle them as needed. $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
  3. Game designers/developers do that all the time with a countdown timer - example -> https://www.phototechguru.com/trivia.php. though the server side would be a little tricky if it is automated. Like someone stated websockets might be worth looking into if that is the case?
  4. This is how I do my page layouts - I start off with grids /* Approximately the size of a 1248px large display monitor */ @supports (grid-area: auto) { @media screen and (min-width: 78em) { .name-website { display: block; } .site { display: grid; grid-template-columns: 78em; grid-template-areas: "nav" "main" "sidebar" "footer"; column-gap: 1.250em; justify-content: center; } // More CSS then I use flex for individual sections or elements #file_grid_area { grid-area: file_grid_area; display: flex; box-sizing: border-box; background-color: darken(#8ebd94, 0.20); padding: 1.250em 1.250em 0; [type="file"] { border: 0; clip: rect(0, 0, 0, 0); height: 1px; overflow: hidden; padding: 0; position: absolute !important; white-space: nowrap; width: 1px; } [type="file"] + label { background-color: #000; border-radius: 4rem; color: #fff; cursor: pointer; display: inline-block; padding: 0.625em 1.250em; margin-bottom: 1.25em; } } along with media queries /* Approximately the size of a 1248px large display monitor */ @supports (grid-area: auto) { @media screen and (min-width: 78em) { that way it's easy to changing the layout without to much modification to the HTML (If at all) and making too much changes to the CSS. I have also found that i don't write that much CSS or repetitive CSS. Hope that Helps. I use SASS (A CSS Preprosser)
  5. I also find using PDO to be much cleaner. Here's an example - // ... more code above ... // Prepare the SQL query with placeholders $sql = "UPDATE gallery SET category = :category, heading = :heading, content = :content, image_path = :image_path, thumb_path = :thumb_path WHERE id = :id"; $stmt = $pdo->prepare($sql); // Bind the values to the placeholders $savePath = $saveDirectory . $destinationFilename; $stmt->bindParam(':image_path', $savePath); $stmt->bindParam(':thumb_path', $thumb_path); } else { // Prepare the SQL query with placeholders $sql = "UPDATE gallery SET category = :category, heading = :heading, content = :content WHERE id = :id"; $stmt = $pdo->prepare($sql); } // Bind the values to the placeholders $stmt->bindParam(':id', $id, PDO::PARAM_INT); $stmt->bindParam(':category', $category); $stmt->bindParam(':heading', $heading); $stmt->bindParam(':content', $content); // Execute the prepared statement $stmt->execute(); // Check if the update was successful if ($stmt->rowCount() > 0) { echo json_encode(['success' => true, 'message' => 'Record updated successfully.']); } else { echo json_encode(['success' => false, 'message' => 'No record updated.']); }
  6. Figuring out the offset and using it in the query really helps - $sql = 'SELECT * FROM gallery WHERE page =:page AND category =:category ORDER BY id DESC, date_added DESC LIMIT :perPage OFFSET :blogOffset'; $stmt = $pdo->prepare($sql); // Prepare the query: $stmt->execute(['page' => $page, 'perPage' => $perPage, 'category' => $category, 'blogOffset' => $offset]); // Execute the query with the supplied data: return $stmt->fetchAll(PDO::FETCH_ASSOC); and this might help // Grab the current page the user is on if (isset($_GET['page']) && !empty($_GET['page'])) { $current_page = urldecode($_GET['page']); } else { $current_page = 1; } $per_page = 1; // Total number of records to be displayed: // Grab Total Pages $total_pages = $gallery->total_pages($total_count, $per_page); /* Grab the offset (page) location from using the offset method */ /* To figure out offset -> $offset = $per_page * ($current_page - 1) */ $offset = $gallery->offset($per_page, $current_page); Just an example of pagination
  7. You really don't need if statement or try/catch blocks and that is something a human pointed me out on another forum. I believe he's also on this forum as well. For example I have this function(method in OOP) $sql = 'SELECT * FROM gallery WHERE page =:page AND category =:category ORDER BY id DESC, date_added DESC LIMIT :perPage OFFSET :blogOffset'; $stmt = $this->pdo->prepare($sql); // Prepare the query: $stmt->execute(['page' => $page, 'perPage' => $perPage, 'category' => $category, 'blogOffset' => $offset]); // Execute the query with the supplied data: return $stmt->fetchAll(PDO::FETCH_ASSOC); No try/catch block, if statement as any errors are caught by exception. Something to read up on is this // Register the exception handler method set_exception_handler([$errorHandler, 'handleException']); here's a good link on it https://www.php.net/manual/en/function.set-exception-handler.php For debugging ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); and a good link in using PDO as in my opinion it is easier to implement and more versatile - https://phpdelusions.net/pdo Even the website writes " Although there are several error handling modes in PDO, the only proper one is PDO::ERRMODE_EXCEPTION. So, one ought to always set it this way, either by adding this line after creation of PDO instance, $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); or as a connection option, as demonstrated in the example above. And this is all you need for the basic error reporting"
  8. I use chatGPT as a tool. For programming I just use it to help with the coding, but I have found out that it's reasoning skills is limited. What I mean if you don't know how to code it will go astray and leave you in even more confused. It also doesn't know the best coding practices especially when it comes to security. I have also stumped it a few times where ChatGPT will just leave you hanging. I find out it's best when you know how to code and just steer it in the right direction and go to forums like this to get help from a real human. Where it really shines well at least for me is rewording my comments as I'm not the greatest when it come to my grammar. Here's an example of what I'm saying - I utilize ChatGPT as an aid, primarily for assistance with coding. However, I've discovered that its reasoning capabilities are somewhat restricted. In other words, if you lack coding knowledge, it may lead you astray and create further confusion. Moreover, ChatGPT isn't well-versed in best coding practices, particularly regarding security. There have been instances when it left me hanging without a solution. I've found that it works best when you have coding knowledge and can guide it in the right direction while seeking additional support from real humans on forums like this. Where ChatGPT truly excels, at least for me, is in rephrasing my comments since I'm not particularly skilled in grammar.
  9. To be truthful you need to watch or read a tutorial on pagination as that what I did. The following is basically the steps to take to do pagination. // Grab the current page the user is on if (isset($_GET['page']) && !empty($_GET['page'])) { $current_page = urldecode($_GET['page']); } else { $current_page = 1; } $per_page = 1; // Total number of records to be displayed: // Grab Total Pages $total_pages = $gallery->total_pages($total_count, $per_page); /* Grab the offset (page) location from using the offset method */ /* $per_page * ($current_page - 1) */ $offset = $gallery->offset($per_page, $current_page); // Figure out the Links that you want the display to look like $links = new Links($current_page, $per_page, $total_count, $category); // Finally grab the records that are actually going to be displayed on the page $records = $gallery->page($per_page, $offset, 'gallery', $category); Granted there is much more coding, but the above is the basic steps in pagination. To see it in action just visit my website.
  10. $mail->SMTPSecure = "PHPMailer::ENCRYPTION_STARTTLS"; should be this I believe $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; Incorrect URL <a href='http://localhost/myproject/verify-email.php?token=$verify_token'>Click Me </a> Instead of using md5(rand()) for generating the password, you should use PHP's built-in password hashing functions like password_hash(). You have two calls to the sendemail_verify() function. Remove the first one (before the "send or not?" echo statement) as it is redundant and might lead to confusion. You are using $_POST['password'] as the value for the $verify_token variable. Instead, you should generate a random token using functions like bin2hex(random_bytes($length)).
  11. I know PDO can look confusing at first, but once you get the hang of using PDO it's so much easier that mysqli in my opinion. Here's your code in PDO though I haven't tested it out. <?php if (isset($_POST['flagged'])) { try { $dsn = "mysql:host=localhost;dbname=$database;charset=utf8mb4"; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; $pdo = new PDO($dsn, "root", "", $options); $sql = "UPDATE `reservations` SET flagged = 'Yes' WHERE id = :id"; $stmt = $pdo->prepare($sql); $flaggedId = $_POST['flagged']; $stmt->bindParam(':id', $flaggedId, PDO::PARAM_INT); $stmt->execute(); echo "<style>body {background-color: red;}</style>"; } catch (PDOException $e) { // Handle any errors though not for a production server echo "Error: " . $e->getMessage(); } } Here's a nice link on how to use PDO -> https://phpdelusions.net/pdo I still use that website when I have a brainfart. 🤣
  12. The following are the basic steps in doing pagination. // Grab the current page the user is on if (isset($_GET['page']) && !empty($_GET['page'])) { $current_page = urldecode($_GET['page']); } else { $current_page = 1; } $per_page = 1; // Total number of records to be displayed: // Grab Total Pages $total_pages = $gallery->total_pages($total_count, $per_page); /* Grab the offset (page) location from using the offset method */ /* $per_page * ($current_page - 1) */ $offset = $gallery->offset($per_page, $current_page); // Figure out the Links that you want the display to look like $links = new Links($current_page, $per_page, $total_count, $category); // Finally grab the records that are actually going to be displayed on the page $records = $gallery->page($per_page, $offset, 'gallery', $category); and this the actual function/method in grabbing the record(s) to be displayed $sql = 'SELECT * FROM gallery WHERE page =:page AND category =:category ORDER BY id DESC, date_added DESC LIMIT :perPage OFFSET :blogOffset'; $stmt = $this->pdo->prepare($sql); // Prepare the query: $stmt->execute(['page' => $page, 'perPage' => $perPage, 'category' => $category, 'blogOffset' => $offset]); // Execute the query with the supplied data: return $stmt->fetchAll(PDO::FETCH_ASSOC);
  13. I remember when I was in college the classes I took required Dreamweaver, but all the instructors would say "Even thought the syllabus and I'm required to show how to use Dreamweaver when you get into the real world ditch Dreamweaver and use a real IDE". That was many moons ago and even back then all the students groaning having to pay for Dreamweaver. 😂 Back then it wasn't subscription based, but we at least received a student discount.
  14. If you want to keep the login form on the same page, you can modify the code to only redirect when necessary. For example, you can check if the user has submitted the login form and then only redirect them if the login fails. Here's a simple example: if (session_status() == PHP_SESSION_NONE) { session_start(); } if (isset($_POST['submit'])) { // Assuming there's a submit button in the login form // Validate user credentials, and set $_SESSION['logged-in-user'] if successful // ... } else { if (empty($_SESSION['logged-in-user'])) { // Show the login form and any error messages here // ... } else { // Redirect to a different page, or show content for logged-in users // ... } } This code will only show the login form if the user is not logged in and hasn't submitted the form. Once they submit the form and successfully log in, the page will show content for logged-in users or redirect to another page as desired.
  15. First of all this is the proper way of doing this line <?php echo '<td><button type="submit" name="status" value="'.htmlspecialchars($value['id']).'">status</button></td>'; ?> Second I don't why you are doing the following? if(!$customer_details) Plus showing how you handle the database connection and how you change the values would be helpful.
  16. Well, I hope it is just for practice as that code has a lot of security vulnerabilities to it even if you got all the syntax errors ironed out.
  17. I have been developing another JavaScript game though I have a Trivia game that is what you are looking for? If you look at the JavaScript either by using inspect or viewing the source code it might give an idea in what direction to take? https://www.fanoflego.com/trivia.php This is the game I have been developing -> https://www.phototechguru.com/hangman/can_you_solve.php that might also help? This GitHub Repository might also help? https://github.com/Strider64/phototechguru though the Trivia game is an older version of it.
  18. You missing the point - JavaScript is Client Side and PHP is Server Side. You need to use AJAX or FETCH have communication between the two. Example: // Add an event listener to the edit form's submit event editForm.addEventListener("submit", async function(event) { // Prevent the default form submit behavior event.preventDefault(); // Create a FormData object from the edit form const formData = new FormData(editForm); console.log("form data", formData); // Send a POST request to the update_question.php endpoint with the form data const response = await fetch("update_question.php", { method: "POST", body: formData, }); // Check if the request was successful if (response.ok) { const result = await response.json(); console.log(result); // If the response has a "success" property and its value is true, clear the form if (result.success) { const searchTerm = document.getElementById("searchTerm").value; await displayRecord(searchTerm); } } else { console.error( "Error submitting the form:", response.status, response.statusText ); // Handle error response } }); });
  19. I don't know exactly it is called, but sometimes you have to give your ISP `permission` to use certain email clients. I know Gmail for example does and I had to change some settings on my email server portion.
  20. Here a simple breakdown $cookie_name = 'my_cookie'; $cookie_value = 'my_value'; $cookie_domain = 'www.example.com'; $cookie_lifetime = strtotime('+6 months'); $cookie_options = array( 'expires' => $cookie_lifetime, 'path' => '/', 'domain' => $cookie_domain, 'secure' => true, 'httponly' => true, 'samesite' => 'Lax' ); setcookie($cookie_name, $cookie_value, $cookie_options); a login example - // Verify the username and password if (verify_credentials($username, $password)) { // Generate a unique token $token = bin2hex(random_bytes(32)); // Store the token in the user's database record (or other persistent storage mechanism) store_token_in_database($user_id, $token); // Set a cookie with the token and a 6-month expiration time setcookie('login_token', $token, [ 'expires' => strtotime('+6 months'), 'path' => '/', 'domain' => 'example.com', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax' ]); // Store the token in the user's session $_SESSION['login_token'] = $token; // Redirect the user to the dashboard or home page header('Location: dashboard.php'); exit; } else { // Invalid username or password $error = 'Invalid username or password'; }
  21. I suggest looking into using PDO https://phpdelusions.net/pdo as well as the code is so much cleaner in my opinion as well. Here's an example of what I'm talking about -> $sql = "INSERT INTO lego_trivia (points, question, answer, canvas_images) VALUES (:points, :question, :answer, :canvas_images)"; $stmt = $pdo->prepare($sql); // Bind the values to the placeholders $stmt->bindValue(':points', $points, PDO::PARAM_INT); $stmt->bindValue(':question', $question); $stmt->bindValue(':answer', $answer); $stmt->bindValue(':canvas_images', $savePath); // Execute the prepared statement $insertSuccess = $stmt->execute();
  22. If it's still not working then you didn't fix it. 🤔 echo json_decode(['Name' => $data['name'], 'email' => $data['email'], //... the rest]);
  23. Don't know the real difference, but if you want to use emojis then UTF8mb4 is the way to go -> "Database character encoding: Ensure that your database is using the utf8mb4 character set and the utf8mb4_unicode_ci collation. This character set supports storing emojis and other Unicode characters properly." Though you still use `<meta charset="UTF-8">` in the HTML and set the following if you're using PDO -> $dsn = "mysql:host=localhost;dbname=your_database_name;charset=utf8mb4"; $pdo = new PDO($dsn, $username, $password);
  24. I have setup a little Codepen giving the basic structure of using grids, Flexbox and media queries. I still use a variation of it now with my websites. Here's the link -> https://codepen.io/Strider64/pen/gOGqrxo In my opinion it's better than just throwing all div elements all over the place. Just another option and I think you will be surprise how less CSS you use.
  25. My hangman type of game is setup differently, but I keep everything together. Here's my table setup CREATE TABLE `lego_trivia` ( `id` int NOT NULL, `question` varchar(255) COLLATE utf8mb4_general_ci NOT NULL, `answer` varchar(255) COLLATE utf8mb4_general_ci NOT NULL, `canvas_images` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, `points` int NOT NULL DEFAULT '10' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; and here's just one of my PHP files <?php require_once '../assets/config/config.php'; require_once "../vendor/autoload.php"; use FanOfLEGO\Database; $pdo = Database::pdo(); // Parse the input data $data = json_decode(file_get_contents('php://input'), true); if (!$data) { try { errorOutput('Invalid input data', 400); } catch (JsonException $e) { } exit(); } $current_id = (int) $data['current_id']; try { $stmt = $pdo->prepare('SELECT id, canvas_images FROM lego_trivia WHERE id > :current_id ORDER BY id LIMIT 1'); $stmt->bindValue(':current_id', $current_id, PDO::PARAM_INT); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); if ($result) { // Makes it, so we don't have to decode the json coming from javascript header('Content-type: application/json'); $data = ['next_id' => $result['id'], 'image' => $result['canvas_images']]; //canvas_images is the path output($data); } else { // Reached the end of the table output(['end_of_table' => true]); } } catch (PDOException $e) { errorOutput($e->getMessage(), 500); } function errorOutput($output, $code = 500) { http_response_code($code); echo json_encode(['error' => $output]); } function output($data) { http_response_code(200); echo json_encode($data); } and a link to the some-what finished game https://www.fanoflego.com/hangman/can_you_solve.php My point is that it is easier to keep everything organized if it is in one table though have a separate table for high scores is something I will will be working on next.
×
×
  • 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.