I don’t know exactly what you are trying to do, but login status and retrieving data should be two different things. I personally just check to see if a user is logged in.
Example →
<?php
require_once __DIR__ . '/../config/config.php';
require_once "vendor/autoload.php";
use Intervention\Image\ImageManagerStatic as Image;
use brainwave\{
ErrorHandler,
Database,
LoginRepository as Login,
ImageContentManager
};
$errorHandler = new ErrorHandler();
// Register the exception handler method
set_exception_handler([$errorHandler, 'handleException']);
$database = new Database();
$pdo = $database->createPDO();
// Check to see user is login in, if not redirect them to the home or login in page:
$login = new Login($pdo);
if (!$login->check_login_token()) {
header('location: index.php');
exit();
}
?>
then I use my script to retrieve the data →
'use strict';
//edit_puzzle.js
(function () {
document.addEventListener("DOMContentLoaded", function () {
const searchForm = document.getElementById("searchForm");
const editForm = document.getElementById("data_entry_form");
const id = document.getElementById("id");
const image_for_edit_record = document.getElementById("image_for_edited_record");
const category = document.getElementById("category");
const difficulty_level = document.querySelector('#difficulty_level');
const description = document.getElementById('description');
const resultInput = document.getElementById("searchTerm");
async function displayRecord(searchTerm = null) {
const requestData = {};
if(searchTerm !== null) requestData.searchTerm = searchTerm;
try {
const response = await fetch("search_puzzle_records.php", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestData),
});
const data = await response.json();
console.log(data); // Add this line
if (data.message) {
resultInput.value = '';
resultInput.placeholder = data.message;
} else if (data.error) {
console.error(data.error);
} else {
const row = data[0];
console.log('row', row);
id.value = row.id;
image_for_edit_record.src = row.image_path;
image_for_edit_record.alt = "Puzzle Image";
// Set the value for the category
for (let option of category.options) {
if (option.value === row.category) {
option.selected = true;
break;
}
}
// Set the value for the difficulty level
for (let option of difficulty_level.options) {
if (option.value === row.difficulty_level) {
option.selected = true;
break;
}
}
description.textContent = row.description;
}
} catch (error) {
console.error("Error:", error);
}
}
searchForm.addEventListener("submit", function (event) {
// Prevent the default form submit behavior
event.preventDefault();
// Get the value of the search term input field and the select box
const searchTermInput = document.getElementById("searchTerm").value;
// Use the input value if it's not empty, otherwise use the select value
const searchTerm = searchTermInput !== "" ? searchTermInput : null;
// Call the displayRecord function with the search term and selected heading
displayRecord(searchTerm);
});
// 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();
event.stopImmediatePropagation();
// 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("update_puzzle_records.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 = "";
document.getElementById("description").textContent = "";
document.getElementById("difficulty_level").selectedIndex = 0; // set to the first option
document.getElementById("category").selectedIndex = 0; // set to the first option
editForm.reset(); // Resetting the edit form
searchForm.reset(); // Resetting the search form
}
} else {
console.error(
"Error submitting the form:",
response.status,
response.statusText
);
// Handle error response
}
});
});
})();
I use FETCH / PHP / JavaScript as I find FETCH (jQuery has something similar, but I use Vanilla JavaScript) →
'use strict';
//edit_puzzle.js
(function () {
document.addEventListener("DOMContentLoaded", function () {
const searchForm = document.getElementById("searchForm");
const editForm = document.getElementById("data_entry_form");
const id = document.getElementById("id");
const image_for_edit_record = document.getElementById("image_for_edited_record");
const category = document.getElementById("category");
const difficulty_level = document.querySelector('#difficulty_level');
const description = document.getElementById('description');
const resultInput = document.getElementById("searchTerm");
async function displayRecord(searchTerm = null) {
const requestData = {};
if(searchTerm !== null) requestData.searchTerm = searchTerm;
try {
const response = await fetch("search_puzzle_records.php", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestData),
});
const data = await response.json();
console.log(data);
if (data.message) {
resultInput.value = '';
resultInput.placeholder = data.message;
} else if (data.error) {
console.error(data.error);
} else {
const row = data[0];
console.log('row', row);
id.value = row.id;
image_for_edit_record.src = row.image_path;
image_for_edit_record.alt = "Puzzle Image";
// Set the value for the category
for (let option of category.options) {
if (option.value === row.category) {
option.selected = true;
break;
}
}
// Set the value for the difficulty level
for (let option of difficulty_level.options) {
if (option.value === row.difficulty_level) {
option.selected = true;
break;
}
}
description.textContent = row.description;
}
} catch (error) {
console.error("Error:", error);
}
}
searchForm.addEventListener("submit", function (event) {
// Prevent the default form submit behavior
event.preventDefault();
// Get the value of the search term input field and the select box
const searchTermInput = document.getElementById("searchTerm").value;
// Use the input value if it's not empty, otherwise use the select value
const searchTerm = searchTermInput !== "" ? searchTermInput : null;
// Call the displayRecord function with the search term and selected heading
displayRecord(searchTerm);
});
// 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();
event.stopImmediatePropagation();
// 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("update_puzzle_records.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 = "";
document.getElementById("description").textContent = "";
document.getElementById("difficulty_level").selectedIndex = 0; // set to the first option
document.getElementById("category").selectedIndex = 0; // set to the first option
editForm.reset(); // Resetting the edit form
searchForm.reset(); // Resetting the search form
}
} else {
console.error(
"Error submitting the form:",
response.status,
response.statusText
);
// Handle error response
}
});
});
})();
Here’s my search PHP thrown in →
<?php
// Send a response to the client with the content type set to application/json.
header('Content-Type: application/json');
// Include the necessary files and classes for this script.
require_once __DIR__ . '/../config/config.php';
require_once "vendor/autoload.php";
// Use some classes for error handling, database connection and login-related actions.
use brainwave\ErrorHandler;
use brainwave\Database;
use brainwave\LoginRepository as Login;
// Instantiate an ErrorHandler object.
$errorHandler = new ErrorHandler();
// Set a custom exception handler function.
set_exception_handler([$errorHandler, 'handleException']);
// Create a new Database object and establish a PDO connection.
$database = new Database();
$pdo = $database->createPDO();
// Instantiate a Login object.
$login = new Login($pdo);
// Main try-catch block.
try {
// Get the request body and decode it as JSON.
$request = json_decode(file_get_contents('php://input'), true);
// Extract the search term and heading from the request, if they exist.
$searchTerm = $request['searchTerm'] ?? 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 puzzle_images ADD FULLTEXT(description);
if($searchTerm !== null) {
$sql = "SELECT * FROM puzzle_images WHERE MATCH(description) AGAINST(:searchTerm IN NATURAL LANGUAGE MODE) LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':searchTerm', $searchTerm);
} 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.
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
// If results were found, return them to the client as JSON.
if ($row) {
echo json_encode($row);
} else {
echo json_encode(['message' => 'No results found.']);
}
// Catch any exceptions that occur during database interaction.
} catch (PDOException $e) {
echo json_encode(['error' => $e->getMessage()]);
}
I use async/await so that the data wouldn’t be missed (I am not using the correct term)
Hope that helps a little?
Oh, error messages shouldn’t be displayed, but either logged in or emailed.