-
Posts
484 -
Joined
-
Last visited
-
Days Won
14
Posts posted by Strider64
-
-
There's no `WHERE` in `INSERT INTO`
-
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
-
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.
-
I would studied up on using CSS Grids, CSS Flexbox and media queries for responsive that way you can control the any page layout.
-
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.
-
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.
-
// 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;
-
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.
-
3 minutes ago, LeonLatex said:
@mac_gyver, If you look in bottom of my first posting you find my login form. I dont have a registration form yet because so early in the development process i manually put the testing user accounts in mysql manually. I dont have time to use more time on this now, so i will start develop another system, and this time with email confirmation and a confirmation code. Is less use of time to put a new one together than looking for errors in this login system. I dont think there is only one error. The system has going through many changes through the last year, so it's time to let the old one rest. Any way, thanks for using time for trying to help ?
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).
-
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. -
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.
-
1
-
-
19 minutes ago, Adamhumbug said:
Hi All,
As i am trying to learn more and more i wanted to know if there was a way of looking at a raw fetchall() when running functions in php.
I have a function call on my page which is set to var_dump the return.
Is it possible to show the whole array on that page?
Sure, I just do something like this
echo "<pre>" . print_r($results, 1) . "</pre>";
It's a great way to debug also.
-
/* ----- 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?
-
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
-
-
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'];
-
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.
-
1
-
-
1 hour ago, PNewCode said:
I figured it out. I was trying to add stuff to the wrong if statement. Instead I just changed the following, and now it works

if (isset($_POST["submit"])) { $pname = ""; if(!empty($_FILES["file"]["name"])){ $allowed_img = array('gif', 'png', 'jpg', 'jpeg');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.
-
1
-
-
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.
-
3 hours ago, rick645 said:
however, the end user should not be asked to specify the extension as well
They don't have to if you design and develop the website correct.
-
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.
-
2 hours ago, Barand said:
If you want to hide them, why include them in the query in the first place?
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.
-
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
-
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. ?
-
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.

Form get value and assign to variable to be used for sql query
in PHP Coding Help
Posted
My approach would be to divide the content into three files, although it's feasible to combine everything into a single file. Nonetheless, I'd still make an effort to keep the code and HTML distinct and separate as much as possible.
Here's an example of what I'm trying to express:
My HTML form (edit_cms.php):
A little bit of my JavaScript code (edit_cms.js):
and my PHP file with a little bit of the code that gets the results (search_cms_records.php):
My argument is that debugging becomes simpler when most of the code is organized and separated as much as possible within its respective programming language.