-
Posts
473 -
Joined
-
Last visited
-
Days Won
12
Community Answers
-
Strider64's post in TypeError: arrayOfObjects is not iterable was marked as the answer
// 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;
-
Strider64's post in Problem sending formdata to php using fetch was marked as the answer
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.
-
Strider64's post in How to view raw php fewtchAll() output was marked as the answer
Sure, I just do something like this
echo "<pre>" . print_r($results, 1) . "</pre>"; It's a great way to debug also.
-
Strider64's post in Create link out of a global and set a variable was marked as the answer
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
-
Strider64's post in Php mysql user delete option. This one is tricky was marked as the answer
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).
-
Strider64's post in How do promises program flow work in javascript? was marked as the answer
I did an online tutorial and the following is the basically setup for promises for me as it explains it clearly for me.
/* Create High Score Data using fetch */ const createHSTable = (retrieveUrl, succeed, fail) => { let max = 5; // Maximum Records to Be Displayed let maximum = {}; maximum.max_limit = max; fetch(retrieveUrl, { method: 'POST', // or 'PUT' body: JSON.stringify(maximum) }) .then((response) => handleErrors(response)) .then((data) => succeed(data)) .catch((error) => fail(error)); }; createHSTable('retrieveHighScore.php', retrieveHSTableUISuccess, retrieveHSTableUIError); First it handles any errors
/* Handle General Errors in Fetch */ const handleErrors = function (response) { if (!response.ok) { throw (response.status + ' : ' + response.statusText); } return response.json(); }; Second it handles success
/* retrieve User Data from hs_table */ const retrieveHSTableUISuccess = function (info) { displayHSTable(info); }; Lastly it handles failure 😔
/* If Database Table fails to save data in mysql table */ const retrieveHSTableUIError = function (error) { console.log("Database Table did not load", error); }; A nice thing about failure is that you can have it where it doesn't actually fail (example database table not loading):
Here's an example what I'm trying to say:
/* If Database Table fails to load then answer a few hard coded Q&A */ const quizUIError = (error) => { /* * If game database table fails to load then give a few questions * and answers, so that the game will still work properly. */ failed = true; mainGame.style.display = 'grid'; d.getElementById('content').scrollIntoView(); console.log("Database Table did not load", error); gameData = [{ "id": 1, "user_id": 1, "hidden": "no", "question": "[Blank] is the length of time when the film or digital sensor inside the camera is exposed to light, also when a camera's shutter is open when taking a photograph. The amount of light that reaches the film or image sensor is proportional to the [Blank].", "category": "photography", "answers": [ "Shutter Speed or Exposure Time", "ISO", "", "" ] }, { "id": 2, "user_id": 1, "hidden": "no", "question": "[Blank] was one of the earliest photographers in American history, best known for his scenes of the Civil War. He studied under inventor Samuel F. B. Morse, who pioneered the daguerreotype technique in America. [Blank] opened his own studio in New York in 1844, and photographed Andrew Jackson, John Quincy Adams, and Abraham Lincoln, among other public figures.", "category": "photography", "answers": [ "Robert Capa", "Steve McCurry", "Ansel Adams", "Matthew Brady" ] } ] totalQuestions = gameData.length; //console.log(gameData[gameIndex]); createQuiz(gameData[gameIndex]); };
That's just my way of handling promises and there could be more promises (or less) it's just depends in what you're doing. I find commenting functions makes it easier when you have to look at the code in the future.
-
Strider64's post in New site, grid, flex, flexbox, design and what to choose. How to do it? was marked as the answer
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)
-
Strider64's post in php redirect using header() resulting in "page is not redirecting properly" was marked as the answer
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.
-
Strider64's post in trying to hide a button was marked as the answer
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.
-
Strider64's post in What's the difference between UTF8 and UTF8mb4 was marked as the answer
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);
-
Strider64's post in display inline problem was marked as the answer
.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
-
Strider64's post in Please Review my code and highlight my mistake was marked as the answer
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.