Jump to content


  • Posts

  • Joined

  • Last visited

  • Days Won


Everything posted by Strider64

  1. I personally find it better to have the configuration file outside the root directory require_once __DIR__ . '/../config/config.php'; // Goes one up from the root / directory
  2. Instead of using `if` statements you should be using `functions`, plus PHP has a great way of doing pagination (The following is just an example of what I'm talking about) -> // Display Record(s) by Pagination public function page($perPage, $offset, $page = "index", $category = "general"): array { $sql = 'SELECT * FROM '. $this->table . ' WHERE page =:page AND category =:category ORDER BY id ASC, 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); } I would look into pagination tutorials as that will save you a lot headaches.
  3. I would studied up on using CSS Grids, CSS Flexbox and media queries for responsive that way you can control the any page layout.
  4. You might want to check that your CSS is the same on both servers and that is correct. For example if you have `display:none;` the image won't show. Ensure that the file permissions for the image are set correctly. The web server should have read access to the image file. If you're using an Apache web server, check your .htaccess file and server configuration for any rules that might be affecting image loading.
  5. I'd also point out that you aren't using prepared statements. I'd recommend learning PDO over mysqli. Additionally, you seem to rely heavily on sessions when ideally, only the user's ID should be stored in them and maybe a token.
  6. // Import the arrayOfObjects from the data module. const arrayOfObjects = require("./data"); // Iterate through each object in the arrayOfObjects. for (const obj of arrayOfObjects) { // Log the id and name properties of the current object to the console. console.log(`ID: ${obj.id}, Name: ${obj.name}`); } For the data module that contains the array of objects: // Define an array of objects with properties id and name. const arrayOfObjects = [ { "id": 1, "name": "bla bla" }, // Object with id 1 and name 'bla bla' { "id": 2, "name": "bla bla bla" } // Object with id 2 and name 'bla bla bla' ]; // Export the arrayOfObjects so it can be imported and used in other modules. module.exports = arrayOfObjects;
  7. If you are `editing` the data anywhere else and that data isn't clean then you will have to look at that code as well. I hope I'm making sense.
  8. You don't need a registration form/page as all you have to do is hash your password that you want to use. That's what I do when I develop my website(s).
  9. Here's a good website that helped me with composer when I first started out using it. https://devdojo.com/bobbyiliev/use-composer-like-a-pro-the-dependency-manager-for-php It might not help you with this project, but it'll give you a better understanding on how to use it.
  10. You need to do something like this -> // 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 edit_update_blog.php endpoint with the form data const response = await fetch("edit_update_blog.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) { resultInput.value = ''; // Clear the current value of the search input field resultInput.placeholder = "New Search"; // Set the placeholder to `New Search` image_for_edit_record.src = ""; image_for_edit_record.alt = ""; editForm.reset(); // Resetting the edit form searchForm.reset(); // Resetting the search form // Reset select box to default (first) option const selectBox = document.querySelector('select[name="heading"]'); selectBox.selectedIndex = 0; } } else { console.error( "Error submitting the form:", response.status, response.statusText ); // Handle error response } }); also using `console.log` helps in debugging, plus your `sql_connection.php` is expecting back json data back.
  11. Sure, I just do something like this echo "<pre>" . print_r($results, 1) . "</pre>"; It's a great way to debug also.
  12. /* ----- Upload File / Image ----- */ function uploadFile(uid) { const url = 'process.php'; const form = document.querySelector('form'); form.onsubmit = function(e) { e.preventDefault(); const files = document.querySelector('[type=file]').files; const formData = new FormData(); for (let i = 0; i < files.length; i++) { let file = files[i]; formData.append('files[]', file); formData.append('uploadid', uid); } fetch(url, { method: 'POST', body: formData }).then(response => { return response.text(); }).then(data => { console.log(data); }); }; return; } Instead of using the addEventListener method for the form submission, you can directly bind the function to the form's onsubmit?
  13. Personally, if I were writing a chess game I would use JavaScript and Canvas not PHP for the main coding part of the game.
  14. I just wanted to add that when I took a course in web design one of the things to do is keep the form simple as possible. I'm assuming all that data is coming from a form? If that case I would simplify it down a bit as most visitors will leave that website if they see a HTML form that l large. An example of what I'm talking about. <form class="registerStyle" action="register.php" method="post"> <input id="secret" type="hidden" name="user[secret]" value=""> <div id="qr-code-container" class="d-none"> <img id="qr-code-image" src="" alt="QR Code"> <p id="qr-code-info">Scan QR Code for 2FA</p> </div> <div class="first"> <label for="first_name">First Name</label> <input id="first_name" type="text" name="user[first_name]" value="" tabindex="2" required> </div> <div class="last"> <label for="last_name">Last Name</label> <input id="last_name" type="text" name="user[last_name]" value="" tabindex="3" required> </div> <div class="screenName"> <label class="text_username" for="username">Username <span class="error"> is unavailable!</span> </label> <input id="username" class="io_username" type="text" name="user[username]" value="" tabindex="4" required> </div> <div class="telephone"> <label for="phone">Phone (Optional)</label> <input id="phone" type="tel" name="user[phone]" value="" placeholder="555-555-5555" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" tabindex="5"> </div> <div class="emailStyle"> <label class="emailLabel" for="email">Email <span class="emailError"> is invalid</span> </label> <input id="email" type="email" name="user[email]" value="" tabindex="1" autofocus required> </div> <div class="password1"> <label for="passwordBox">Password</label> <input class="passwordBox1" id="passwordBox" type="password" name="user[password]" value="" tabindex="6" required> <label for="passwordVisibility">Show Passwords (private computer)</label> <input class="passwordBtn1" id="passwordVisibility" type="checkbox" tabindex="7"> </div> <div class="password2"> <label for="redoPassword">ReEnter Password</label> <input class="passwordBox2" id="redoPassword" type="password" name="user[comfirm_password]" value="" tabindex="8" required> </div> <div class="birthday"> <label for="birthday">Birthday (optional)</label> <input id="birthday" type="date" name="user[birthday]" value="1970-01-01" tabindex="9"> </div> <div class="submitForm"> <button class="submitBtn" id="submitForm" type="submit" name="submit" value="enter" tabindex="10"> Submit </button> </div> </form> or at least pull the data in easier -> Example: $user = $_POST['user'];
  15. My suggestion is to use composer https://getcomposer.org/ as it will save you a lot a headaches and you don't have to reinvent the wheel. Then you can just do something like the following -> <?php // Include the configuration file and autoload file from the composer. require_once __DIR__ . '/../config/config.php'; require_once "vendor/autoload.php"; // Import the ErrorHandler and Database classes from the PhotoTech namespace. use brainwave\{ ErrorHandler, Database, Links, ImageContentManager, LoginRepository as Login }; // Instantiate the ErrorHandler class $errorHandler = new ErrorHandler(); // Set the exception handler to use the handleException method from the ErrorHandler instance set_exception_handler([$errorHandler, 'handleException']); // Create a new instance of the Database class $database = new Database(); // Create a PDO instance using the Database class's method $pdo = $database->createPDO(); $login = new Login($pdo); if ($login->check_login_token()) { header('location: dashboard.php'); exit(); } $cms = new ImageContentManager($pdo); a sample class -> <?php // ErrorHandler.php namespace brainwave; use PDOException; use Throwable; use JsonException; class ErrorHandler implements ErrorHandlerInterface { public function handleException(Throwable $e): void { if ($e instanceof PDOException) { error_log('PDO Error: ' . $e->getMessage()); } elseif ($e instanceof JsonException) { error_log('JSON Error: ' . $e->getMessage()); } else { error_log('General Error: ' . $e->getMessage()); } } } I would also check out namespace for PHP classes.
  16. This is taken from my website project -> $file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION)); $extensions = array("jpeg", "jpg", "png"); if (in_array($file_ext, $extensions, true) === false) { $errors[] = "extension not allowed, please choose a JPEG or PNG file."; } /* * If no errors save ALL the information to the * database table. */ if (empty($errors) === true) { // Code that does it.... } I know my variable naming isn't exact, but it should give you a basic way in doing it. I have the GitHub repository -> https://github.com/Strider64/brain-wave-blitz/blob/master/create_cms.php feel free to look around.
  17. A simple way in my opinion would to do something like the following. fetch('https://example.com/data-endpoint') // replace with your actual URL .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); // this returns a promise }) .then(data => { console.log(data); // this will log the whole data to the console // you can access any data point like this: console.log(data.newOffers); // logs: null console.log(data.usedOffers[0].price); // logs: 49.23 // if you want to loop through all the usedOffers you can do something like this: data.usedOffers.forEach(offer => { console.log(`Offer ID: ${offer.id}`); console.log(`Price: ${offer.price}`); console.log(`Delivery Rate: ${offer.deliveryRate}`); // ... and so on for other properties }); }) .catch(e => { console.log('There was a problem with the fetch operation: ' + e.message); }); I'm half asleep that from the JavaScript side, but I find JavaScript more flexible than PHP and easier.
  18. They don't have to if you design and develop the website correct.
  19. I do it a little different way - I do all the time figure in JavaScript (I use Vanilla JavaScript) -> "use strict"; // Function to calculate the time remaining till a certain end time const getTimeRemaining = (countdown_date) => { // Parse the end time and current time into milliseconds const endtimeParsed = Date.parse(countdown_date); const nowParsed = Date.parse(new Date()); // Calculate the total remaining time in milliseconds const total = endtimeParsed - nowParsed; // Breakdown the total time into days, hours, minutes, and seconds const seconds = Math.floor((total / 1000) % 60); const minutes = Math.floor((total / 1000 / 60) % 60); const hours = Math.floor((total / (1000 * 60 * 60)) % 24); const days = Math.floor(total / (1000 * 60 * 60 * 24)); // Return a time object that has the total remaining time and the breakdown return { total, days, hours, minutes, seconds }; }; // Function to display a countdown clock on the webpage const myClock = (id, countdown_date) => { // Find the clock and its components by their IDs const clock = document.getElementById(`display_clock${id}`); const daysSpan = clock.querySelector(`.day${id}`); const hoursSpan = clock.querySelector(`.hour${id}`); const minutesSpan = clock.querySelector(`.minute${id}`); const secondsSpan = clock.querySelector(`.second${id}`); // Function to update the clock display const updateClock = () => { // Get the remaining time const time = getTimeRemaining(countdown_date); // Update the display of each component of the clock // padStart() is used to ensure that all components are two digits daysSpan.textContent = time.days; hoursSpan.textContent = String(time.hours).padStart(2, '0'); minutesSpan.textContent = String(time.minutes).padStart(2, '0'); secondsSpan.textContent = String(time.seconds).padStart(2, '0'); // If the total remaining time is zero or less, stop the clock by clearing the interval if (time.total <= 0) { clearInterval(timeInterval); } } // Call updateClock once immediately, then at regular intervals updateClock(); const timeInterval = setInterval(updateClock, 1000); }; function fetchRoutine() { // Define the data you want to send to the server const grabDate = "myDate=endDate"; // Define the options for the fetch call const fetchOptions = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' }, body: grabDate }; // Make the fetch call fetch('countdown_date.php', fetchOptions) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } // If the response was ok, proceed to parse it as JSON return response.json(); }) .then(data => { console.log('data', data); document.getElementById("countdown_date").textContent = data.date_format; document.getElementById("display_title").textContent = data.title; let countdown_date = new Date(Date.parse(data.time_left)); myClock(1, countdown_date); }) .catch(error => { console.error('There has been a problem with your fetch operation:', error); }); } fetchRoutine(); Here's the HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Countdown Clock</title> <link rel="stylesheet" href="reset.css"> <link rel="stylesheet" href="countdown.css"> </head> <body> <div class="info"> <h1 id="display_title"></h1> <h2 id="countdown_date"></h2> </div> <div id="display_clock1"> <figure class="box"> <div class="day1"></div> <figcaption>Days</figcaption> </figure> <figure class="box"> <div class="hour1"></div> <figcaption>Hours</figcaption> </figure> <figure class="box"> <div class="minute1"></div> <figcaption>Minutes</figcaption> </figure> <figure class="box"> <div class="second1"></div> <figcaption>Seconds</figcaption> </figure> </div> <script src="count_down.js"></script> </body> </html> and the css *{ -webkit-box-sizing: border-box; box-sizing: border-box; } div.info { display: block; width: 100%; max-width: 300px; height: auto; text-align: center; padding: 2px; margin: 10px auto; } div.info::after { content: ''; display: block; clear: both; } h1 { font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif; font-size: 1.2em; line-height: 1.5; } h2 { font-family: Arial, Helvetica, sans-serif; font-size: 1.0em; font-style: italic; font-weight: 300; } div#display_clock1 { display: block; width: 100%; max-width: 190px; height: auto; margin: 5px auto; background-color: pink; } div#display_clock1 figure.box { float: left; display: block; width: 100%; max-width: 40px; height: 70px; color: #fff; text-align: center; padding: 0; margin-left: 5px; } div#display_clock1 figure.box div { background-color: #2e2e2e; height: 50px; line-height: 50px; } div#display_clock1 figure.box figcaption { font-family: Arial, Helvetica, sans-serif; font-size: 0.6em; line-height: 20px; font-weight: bold; color: #000; } it's an old script that I made changes to, so it used a little PHP <?php header('Content-type: application/json'); $endDate = filter_input(INPUT_POST, 'myDate'); if ($endDate === 'endDate') { $count_down_date = new DateTime('2023-07-17 00:00:00', new DateTimeZone("America/Detroit")); $data['time_left'] = $count_down_date->format("Y/m/d H:i:s"); $data['date_format'] = $count_down_date->format("l - F j, Y"); $data['title'] = "Countdown to "; output($data); } function errorOutput($output, $code = 500) { http_response_code($code); echo json_encode($output); } /* * If everything validates OK then send success message to Fetch / JavaScript */ function output($output) { http_response_code(200); echo json_encode($output); } This could be done in JavaScript or even pulling from a Database Table. Like I said it's an old script that I modernized it a little.
  20. There are times that it needs to be done, for example if a game has multiple choices and there are only 2 possible answers. This is a JavaScript pulling data from a database table using fetch -> // This line sets the text content of the button to the corresponding answer (ans1, ans2, ans3, ans4) // with a "📷" character at the beginning. button.textContent = `📷 ${[ans1, ans2, ans3, ans4][index]}` || ""; // If there's no corresponding answer, the button is disabled (its pointer events are set to "none"). // Otherwise, the button is enabled (its pointer events are set to "auto"). if (![ans1, ans2, ans3, ans4][index]) { button.style.pointerEvents = "none"; } else { button.style.pointerEvents = "auto"; } Though I have of admit most of the time is a waste of time coding for empty fields.
  21. if you file is outside the root directory you should use include(__DIR__ . "/../includes/db.php"); $_SERVER['DOCUMENT_ROOT'] returns the root directory defined by the server configuration file
  22. I have been developing an online trivia game for years now and I have finally wrapped this around my head. (Well, at least I think 😂 ) HTML <div id="answers"> <button class="buttonStyle" id="ans1"></button> <button class="buttonStyle" id="ans2"></button> <button class="buttonStyle" id="ans3"></button> <button class="buttonStyle" id="ans4"></button> </div> JavaScript // Function to handle the event when an answer is selected. const pickAnswer = (answerIndex) => { return () => { choice = answerIndex; checkAnswer(); // Only show the next button if the next question exists if (index < triviaData.length - 1) { nextButton.style.display = "block"; // show the next button after an answer is chosen } }; }; // The `startGame` function takes an object as an argument with properties: ans1, ans2, ans3, ans4, id, question. // These properties represent the answers to the current question, the question's id, and the question itself, respectively. const startGame = ({ ans1, ans2, ans3, ans4, id, question }) => { // This line sets the id of the current question to the "data-record" attribute of the element with id "currentQuestion". document.querySelector("#currentQuestion").setAttribute("data-record", id); // This line sets the display number of the current question (index + 1) to the text content of the element with id "currentQuestion". document.querySelector("#currentQuestion").textContent = (index + 1).toString(); // This line sets the text content of the element with id "question" to the question itself. document.querySelector("#question").textContent = question; // This loop iterates over each of the answer buttons. answerButtons.forEach((button, index) => { // This line checks if there was a previous "pickAnswer" event listener attached to the button, // and if so, removes it. const previousPickAnswer = button.__pickAnswer__; if (previousPickAnswer) { button.removeEventListener("click", previousPickAnswer); } // This line creates a new "pickAnswer" event listener, and attaches it to the button. const newPickAnswer = pickAnswer(index + 1); button.addEventListener("click", newPickAnswer, false); button.__pickAnswer__ = newPickAnswer; // This line sets the text content of the button to the corresponding answer (ans1, ans2, ans3, ans4) // with a "📷" character at the beginning. button.textContent = `📷 ${[ans1, ans2, ans3, ans4][index]}` || ""; // If there's no corresponding answer, the button is disabled (its pointer events are set to "none"). // Otherwise, the button is enabled (its pointer events are set to "auto"). if (![ans1, ans2, ans3, ans4][index]) { button.style.pointerEvents = "none"; } else { button.style.pointerEvents = "auto"; } }); }; I comment the script out and I think it's self-explanatory. OK, I'm tired as this is the latest I have stayed up. 🤣
  23. I use classes as I like mobility of the code going from one website to the another is easier for me. I don't use Frameworks or Libraries. I like using Vanilla JavaScript as I don't have to think about having a library. I find out that I really don't write that much more code just using good old plain JavaScript. Here's a JavaScript Online Trivia game that I updating. I am using CodePen to do a mockup first of it -> https://codepen.io/Strider64/pen/NWEpZdj Like already stated everyone has their own coding style and I am sure you will find yours.
  24. Maybe something like this for variable naming and form field names? $fullName = filter_input(INPUT_POST, 'fullName'); $phone = filter_input(INPUT_POST, 'phone'); $email = filter_input(INPUT_POST, 'email'); $propertyType = filter_input(INPUT_POST, 'propertyType'); $address = filter_input(INPUT_POST, 'address'); $priceRange = filter_input(INPUT_POST, 'priceRange'); $bedrooms = filter_input(INPUT_POST, 'bedrooms'); $bathrooms = filter_input(INPUT_POST, 'bathrooms'); $preApproved = filter_input(INPUT_POST, 'preApproved'); if ($preApproved === "yes") { echo $preApprovalAmount; } $parkingType = filter_input(INPUT_POST, 'parkingType'); $buyingTimeline = filter_input(INPUT_POST, 'buyingTimeline'); $exploreZips = filter_input(INPUT_POST, 'exploreZips'); $dreamHomeWish = filter_input(INPUT_POST, 'dreamHomeWish');
  25. 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).
  • 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.