Jump to content

Strider64

Members
  • Posts

    466
  • Joined

  • Last visited

  • Days Won

    12

Everything posted by Strider64

  1. 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.
  2. 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 } }); });
  3. 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.
  4. 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'; }
  5. 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();
  6. If it's still not working then you didn't fix it. 🤔 echo json_decode(['Name' => $data['name'], 'email' => $data['email'], //... the rest]);
  7. 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);
  8. 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.
  9. 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.
  10. <?php $host = 'localhost'; // your database host $dbname = 'mydatabase'; // your database name $username = 'myusername'; // your database username $password = 'mypassword'; // your database password try { $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set additional PDO attributes if needed } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } ?>
  11. Like requinix says you should show the full code as it sounds more than hiding a submit button. For example: /* Success function utilizing FETCH */ const sendUISuccess = function (result) { //console.log('Result', result); if (result) { document.querySelector('#recaptcha').style.display = "none"; submit.style.display = "none"; document.querySelector('.pen').setAttribute('src', 'assets/images/target.png'); //messageSuccess.style.display = "block"; document.querySelectorAll('form > *').forEach(function (a) { a.disabled = true; }); } }; // Function to handle errors when sending data to the database const sendUIError = function (error) { console.log("Database Table did not load", error); }; // Function to handle errors when saving data to the database const handleSaveErrors = function (response) { if (!response.ok) { throw new Error(`Save request failed with status ${response.status}: ${response.statusText}`); } return response.json(); }; // Function to save the data to the database const saveDataToDatabase = (url, onSuccess, onError, data) => { fetch(url, { method: 'POST', body: JSON.stringify(data) }) .then(response => handleSaveErrors(response)) .then(data => onSuccess(data)) .catch(error => onError(error)); }; This is a portion of my JavaScript that uses Fetch to get a response back after a user sends the message. It hides the submit button, but verifies the message was sent and a few other things.
  12. I love using fetch and full name can be used -> JavaScript function searchUser(fullName) { // Construct the SQL query as a string with a parameter placeholder const query = 'SELECT * FROM users WHERE full_name = ?'; // Send a POST request to the PHP script with the SQL query and the user's full name as the request body fetch('search_user.php', { method: 'POST', body: JSON.stringify({ query: query, fullName: fullName }) }) .then(response => { if (response.ok) { return response.json(); } throw new Error('Network response was not ok.'); }) .then(data => { // Handle the response data console.log(data); }) .catch(error => { console.error('There was a problem with the fetch operation:', error); }); } // Call the searchUser function with the full name you want to search for searchUser('John Smith'); Example being done in PHP <?php // Get the SQL query and the user's full name from the POST request body $query = $_POST['query']; $fullName = $_POST['fullName']; // Create a new PDO object to connect to the database $dsn = 'mysql:host=localhost;dbname=mydatabase'; $username = 'myusername'; $password = 'mypassword'; try { $pdo = new PDO($dsn, $username, $password); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); exit(); } // Prepare the SQL query as a statement $stmt = $pdo->prepare($query); // Execute the statement with the user's full name as the parameter $stmt->execute(array($fullName)); // Fetch the results as an associative array $results = $stmt->fetchAll(PDO::FETCH_ASSOC); // Send the results as JSON data to the client header('Content-Type: application/json'); echo json_encode($results); ?>
  13. Here's a simple login (not tested) that might get you started? $dsn = 'mysql:host=localhost;dbname=database'; $username = 'username'; $password = 'password'; try { $pdo = new PDO($dsn, $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare("SELECT id, hashed_password FROM users WHERE username = :username LIMIT 1"); $stmt->execute(array(':username' => $username)); if ($stmt->rowCount() == 1) { $user = $stmt->fetch(PDO::FETCH_ASSOC); if (password_verify($password, $user['hashed_password'])) { session_start(); unset($password); session_regenerate_id(); $_SESSION['last_login'] = time(); $_SESSION['id'] = $user['id']; header("Location: admin.php"); exit(); } } $error[] = 'Invalid username or password.'; } catch (PDOException $e) { die('Error: ' . $e->getMessage()); } That reads it in and the following writes the user's username and password $username = 'exampleuser'; $password = 'secretpassword'; // Hash the password using the default algorithm (currently bcrypt) $hashed_password = password_hash($password, PASSWORD_DEFAULT); // Connect to the MySQL database using PDO $dsn = 'mysql:host=localhost;dbname=database'; $username = 'username'; $password = 'password'; try { $pdo = new PDO($dsn, $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Prepare an SQL statement to insert the username and hashed password into the users table $stmt = $pdo->prepare("INSERT INTO users (username, hashed_password) VALUES (:username, :hashed_password)"); $stmt->bindParam(':username', $username); $stmt->bindParam(':hashed_password', $hashed_password); // Execute the statement $stmt->execute(); echo "New record created successfully"; } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } and I even throw in the SQL for a MYSQL database table CREATE TABLE users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, username VARCHAR(30) NOT NULL UNIQUE, hashed_password VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
  14. .outer-div { width: 100%; text-align: center; } .logo-div, .translate-div { display: inline-block; vertical-align: middle; } .logo-div { background-color: red; color: #fff; text-align: left; padding: 1.25em; margin: 0.625em; } .translate-div { background-color: blue; color: #fff; text-align: right; padding: 1.25em; margin: 0.625em; } <div class="outer-div"> <div class="logo-div">Logo and company name</div> <div class="translate-div">Google translate dropdown menu</div> </div> https://codepen.io/Strider64/pen/ZEMZQwa
  15. To address this issue, you can try adding an additional WHERE clause to the SQL query to filter the results based on the input class, as follows: $sql = "SELECT rank FROM ( SELECT ord.id , seq := seq+1 as seq , rank := CASE WHEN ord.grand_total = prev THEN rank ELSE seq END as rank , prev := ord.grand_total as grand_total FROM ( SELECT id , g.grand_total FROM student_exam_result g WHERE g.class = ? ORDER BY grand_total DESC LIMIT 18446744073709551615 ) ord JOIN (SELECT seq:=0, rank:=0,prev:=0) init ) ranked JOIN student_exam_result g ON g.id = ranked.id WHERE class = ? AND index_number = ? AND term = ? AND year = ?"; $stmt = $conn->prepare($sql); $stmt->bind_param('sssss', $session_classs, $session_classs, $session_indexx, $session_termm, $session_yearr); $stmt->execute(); $stmt->bind_result($position); $stmt->fetch(); In this updated query, the WHERE g.class = ? clause has been added to the subquery to ensure that only students from the input class are included in the calculation of their positions. Additionally, the bind_param statement has been updated to include an additional s parameter to match the added input parameter. Note that this solution assumes that the class column in the student_exam_result table exactly matches the input session_classs value. If there are any discrepancies between the input value and the column values, you may need to adjust the query accordingly.
  16. <!DOCTYPE html> <html> <head> <title>Two Frames Example</title> <script> function loadFrames() { document.getElementById("frame1").src = "page1.html"; document.getElementById("frame2").src = "page2.html"; } </script> </head> <body> <a href="#" onclick="loadFrames()">Click Here for Page 1 and Page 2</a> <br><br> <iframe id="frame1"></iframe> <iframe id="frame2"></iframe> </body> </html>
  17. $query = $db->query("SELECT * FROM msg"); // Start an HTML table to display the results echo "<table>"; echo "<tr><th>ID</th><th>Message</th><th>Sender</th></tr>"; // Loop through the rows of data and add them to the table while ($row = $query->fetch(PDO::FETCH_ASSOC)) { echo "<tr>"; echo "<td>" . $row["id"] . "</td>"; echo "<td>" . $row["message"] . "</td>"; echo "<td>" . $row["sender"] . "</td>"; echo "</tr>"; } // Close the HTML table echo "</table>"; This code uses an HTML table to display the query results, with column headings for each field. Inside the while loop, each row of data is output as an HTML table row (<tr>) with cells for each column (<td>). The final echo statement closes the HTML table. Note that this code assumes that the columns in the msg table are named id, message, and sender. If your column names are different, you should update the code to reflect the correct column names.
  18. Personally I would throw that script into file 13 and use PDO as it is more versatile and it isn't obsolete like mysql is. A good reference on PDO is this https://phpdelusions.net/pdo I would come up with a script something like the following -> <?php // Start the session session_start(); // Connect to the database $dsn = 'mysql:host=localhost;dbname=mydatabase'; $username = 'myusername'; $password = 'mypassword'; $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); try { $pdo = new PDO($dsn, $username, $password, $options); } catch (PDOException $e) { die('Database connection failed: ' . $e->getMessage()); } // Check if the login form was submitted if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Retrieve the submitted form data $username = $_POST['username']; $password = $_POST['password']; // Validate the form data if (empty($username) || empty($password)) { echo 'Please enter your username and password.'; exit(); } // Query the database to verify the username and password $sql = "SELECT * FROM users WHERE username = :username LIMIT 1"; $stmt = $pdo->prepare($sql); $stmt->bindParam(':username', $username); $stmt->execute(); $user = $stmt->fetch(); if ($user && password_verify($password, $user['password'])) { // Set session variables to indicate that the user is logged in $_SESSION['loggedin'] = true; $_SESSION['username'] = $user['username']; // Redirect the user to a protected page header('Location: protected.php'); exit(); } else { echo 'Incorrect username or password.'; exit(); } } ?> Just my opinion and I think it would save you a lot of headaches in the long run.
  19. I think you're making things more difficult that it really needs to be? Here's an example of how you can save an image path in PHP: $image_path = "images/my_image.jpg"; In this example, the variable $image_path is set to the path of the image file "my_image.jpg" located in the "images" directory. You can then use this variable to display the image on a webpage or perform other operations with the image file. To display an image in HTML, you can use the <img> tag and set the src attribute to the path of the image file. <img src="images/my_image.jpg" alt="My Image">
  20. I'm asking a stupid question but way are you validating a person name? The Late Prince would had have trouble with that. 🤣 The person's age is another head scratcher. If some of that information is not right simply have it where a person can edit the information, have it idiot proof like the person's age as an example or have a confirmation page.
  21. Personally, I just upload images privately to my own website, but I came across a tutorial a long time ago that stated simply doing this would help. Though it would be a memory hog and something a visitor would not appreciate, so I never used it. protected function file_contains_php() { $contents = file_get_contents($this->file['tmp_name']); $position = strpos($contents, '<?php'); return $position !== false; } There was a member (I forget his name) here a long time ago that taught me a valuable lesson in programming and that is professionals who write security code do it for a living. They test it out, verify before making it public and even then they sometimes get it wrong. So do you think you can? He was referring to me and the script I just wrote. I agreed with him and used a third party script even though it was painful in trashing that script as I spent all night writing it. 🤣
  22. There are plenty of good online help on PDO - https://phpdelusions.net/pdo
  23. first of all you should use an unique index for email and I don't understand the also having for username (though that too). Though I now can see both...tired. Second take a look at this $sql = "SELECT * FROM register WHERE username:username AND email:email"; See anything missing? I give you a hint it's between username :username and also email :email. Here's a good link https://phpdelusions.net/pdo and I even still use it from time to time.
  24. I think I might chime in as well. I think you're trying to do too much with all that code. Coding should work for you, not against you. This is how I generally start off developing a web page. First, I design my web page with HTML/CSS on how I want it to look then I proceed onto coding the page. Then I try to keep as much as the code separated as much as possible, by that I mean having most of the PHP at the top of the file (page) and the HTML at the bottom of the page. The JavaScript in a separate file (though I might have a little amount of JavaScript sprinkle in) and if I'm using FETCH/JSON the PHP in a separate file as well. When I do have PHP in the HTML I try to keep it to the bare minimum instead of encapsulating all the HTML with an echo statement. Even the HTML I use over and over for other pages I have as a separate file with an include statement though that is usually done when I have most of the website up and running. A fragmented Example: <body class="site"> <header class="headerStyle"> <!-- Button to open the modal login form --> <button id="myButton" onclick="document.getElementById('id01').style.display='block'">Login</button> <!-- The Modal --> <div id="id01" class="modal"> <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">&times;</span> <!-- Modal Content --> <form class="modal-content animate" method="post"> <div class="imgcontainer"> <img src="assets/images/img-john-pepp-150-150-001.jpg" alt="Avatar" class="avatar"> </div> <div class="container"> <label for="uname"><b>Username</b></label> <input type="text" placeholder="Enter Username" name="user[username]" required> <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="user[hashed_password]" required> <button type="submit" name="submit" value="login">Login</button> <label> <input type="checkbox" checked="checked" name="user[remember]"> Remember me </label> </div> <div class="container" style="background-color:#f1f1f1"> <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel </button> <span class="psw">Please <a href="register.php">Register</a></span> </div> </form> </header> <?php include_once 'assets/includes/inc.navigation.php'; ?> <section class="main"> <?php foreach ($cms as $record) { echo '<header class="sectionHeader">'; echo '<h2 class="sectionHeadingText">'. $record['heading'] . '</h2>'; echo '</header>'; echo '<article class="sectionArticle">'; echo '<img class="imageArticle right-side" src="' . $record['image_path'] . '" alt="LEGO Bookstore">'; echo '<p class="articleText">' . nl2br($record['content']). '</p>'; echo ' </article>'; echo '<footer class="sectionFooter">'; echo '<p class="sectionText">Written by ' . $record['author'] . ' on ' . CMS::styleDate($record['date_added']) .' </p>'; echo '</footer>'; } ?> <div class="flex_container"> <?= $pagination->links(); ?> </div> </section> Though coders do have their own preferences, but this is my preference as I find it easier to go straight to the problem if I am having one instead of hunting through a LOT OF HTML.
  25. Not trying to sound rude, but you might think about dusting off your resume if that is one of your job duties. If it isn't (which has happen to me in the past) explained to him/her that you don't know how to accomplish the task.
×
×
  • 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.