Jump to content


  • Posts

  • Joined

  • Last visited

  • Days Won


Everything posted by Strider64

  1. $sql = "SELECT * FROM agencies_data WHERE agency_user =:username"; $stmt = $db->prepare($sql); // $db is the PDO Connection $stmt->execute([':username' => $_POST['user']); // I am 99 percenct certain : in :username is not needed / just for clarity. while ($row = $stmt->fetch(PDO::FETCH_ASSOC) { // Process results though I do not understand having a form inside a // form that has been submitted } I would concentrate in getting PDO working then onward to the logic of what you are trying to accomplish. I would pull the record one at a time to edit if that is what you are trying to accomplish? $sql = "SELECT * FROM agencies_data WHERE agency_user =:username"; $stmt = $db->prepare($sql); // $db is the PDO Connection $stmt->execute([':username' => $_POST['user']); // I am 99 percenct certain : in :username is not needed / just for clarity. $result = $stmt->fetch(PDO::FETCH_ASSOC) <input class="form-control" type="text" name="oid" value="<?= $result['agency_user'] ?>" > though that would mean you have to modify the code somewhere else.
  2. A good website to understand PDO that I found is this one -> https://phpdelusions.net/pdo and I suggest creating a PHP sandbox to play around with PDO. After reading this thread I think you're concentrating too much on the mysql and other databases (which PDO can handle) than PHP PDO? I have been using PDO for sometime now, but I don't think it's easier to learn than mysqli, though once learned it is more versatile.
  3. I have gotten inspiration out of this person that I found on CodePen - https://codepen.io/annastasshia especially this pen https://codepen.io/annastasshia/pen/YzpEajJ in the past. I no longer used my modification of that code, but for something that you are doing I think would fit very well as I easily modified to include pagination. https://github.com/Strider64/phototechguru/blob/master/photogallery.php
  4. I have been coding in PHP for about 7 or 8 years, but have been programming since the early 1980s. I still remember COBOL with punch cards and I believe Apple Basic was my first programming language.
  5. Here's my version though I believe you need PHP 8.0 to use it? (Though I could be wrong) https://github.com/Strider64/phototechguru/blob/master/src/Database.php The to use it then simply do the following: public static function fetch_by_column_name($sql) { $stmt = Database::pdo()->prepare($sql); // Database::pdo() is the PDO Connection $stmt->execute([ static::$searchItem => static::$searchValue ]); return $stmt->fetch(PDO::FETCH_ASSOC); }
  6. Should be if ($_SERVER['REQUEST_METHOD'] === 'POST')
  7. It's looks like you are trying to do too many things at the same time. What I can guess is your are trying to do a contact page that sends email, pagination and accessing a database table? Though that is only a guess. My suggestion would to take you one thing at a time and start of basic. Learn the fundamentals of PHP and I know it can be boring, but it gives you a solid foundation on coding in PHP. I have been using PHP for a long time now and I still learn new things from online tutorials and from people who know more than me about PHP. There are plenty of tutorials just make sure that it's a current tutorial. Like already stated if you know the problem then show us that section of the code or HTML markup with the code. Though just looking at what you shown us, a configuration file at the top of the page would help you out for a lot of things and prevent you from typing in repetitive code.
  8. Maybe the following will help: <?php session_start(); //unset($_SESSION['vehicle']); //die(); if (!isset($_SESSION)) { $_SESSION['vehicle'] = null; // Pretend coming from a database table: } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $_SESSION['vehicle'] = $_POST['vehicle']; //echo "<pre>" . print_r($_POST['vehicle'], 1) . "</pre>"; } ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Checkboxes</title> </head> <body> <form method="post"> <label for="yacht" class="vehicle"><?= $_SESSION['vehicle']['yacht'] ? 'I own a Yacht' : 'Yacht'?></label> <input id="yacht" type="checkbox" name="vehicle[yacht]" value="yacht" <?php echo ($_SESSION['vehicle']['yacht']) ? 'checked' : NULL; ?>> <br> <label for="sportsCar" class="vehicle"><?= $_SESSION['vehicle']['sportsCar'] ? 'I own a Porsche 911' : 'Sports Car'?></label> <input id="sportsCar" type="checkbox" name="vehicle[sportsCar]" value="sportsCar" <?php echo ($_SESSION['vehicle']['sportsCar']) ? 'checked' : NULL; ?>> <br> <label for="plane" class="vehicle" ><?= $_SESSION['vehicle']['plane'] ? 'I own a Cessna Jet' : 'Plane'?></label> <input id="plane" type="checkbox" name="vehicle[plane]" value="plane" <?php echo ($_SESSION['vehicle']['plane']) ? 'checked' : NULL; ?>> <br> <button class="submitButton" type="submit" name="submit" value="enter">submit</button> </form> </body> </html>
  9. I don't like the yellow text and text directly on an image. I like the image of the foxes, but the I don't care for centered text (should be left-aligned in my opinion), plus heading should be higher with it not directly on the image. I'm assuming this website is just being constructed? If that is the case changes shouldn't be too hard to implement once you get enough feed back. I would also design for smartphones first and work you way out to larger screens with it comes to responsive design. Though I didn't see any grids and flex was limit in scope? I would look at other websites to get better ideas for this website. That's what I try do for my own.
  10. My advice take about an hour or two to learn PDO and here's a good link that I still use sometime - https://phpdelusions.net/pdo It will save you a lot of time in the long run. I would also separate the logic as it will also help. Here's an example of my photo gallery and I start off with the display: <div class="container"> <?php $count = 0; foreach ($cms as $record) { echo '<p class="hideContent">' . $record['content'] . '</p>'; echo '<div class="' . $displayFormat[$count] . '">'; echo '<div class="gallery-item">'; echo '<div class="images"><img src="' . $record['image_path'] . '" alt="Photo1" data-exif="' . $record['Model'] . ' ' . $record['ExposureTime'] . ' ' . $record['Aperture'] . ' ' . $record['ISO'] . ' ' . $record['FocalLength'] . '" width="800" height="534">'; echo '</div>'; $count++; echo '<div class="title">' . '<h1 class="pictureHeading">' . $record['heading'] . '</h1>' . '<span class="exifInfo">' . $record['Model'] . '</span>' . '</div>'; echo '</div>'; echo '</div>'; } ?> </div> Here's retrieving the data (The PHP is at the top): if (isset($_GET['page']) && !empty($_GET['page'])) { $current_page = urldecode($_GET['page']); } else { $current_page = 1; } $per_page = 12; // Total number of records to be displayed: $total_count = CMS::countAllPage('blog'); // Total Records in the db table: /* Send the 3 variables to the Pagination class to be processed */ $pagination = new Pagination($current_page, $per_page, $total_count); /* Grab the offset (page) location from using the offset method */ $offset = $pagination->offset(); //echo "<pre>" . print_r($offset, 1) . "</pre>"; //die(); /* * Grab the data from the CMS class method *static* * and put the data into an array variable. */ $cms = CMS::page($per_page, $offset, 'blog'); My GitHub repository for this https://github.com/Strider64/phototechguru Proof that it works - https://phototechguru.com/photogallery.php This is just an example, but in my opinion keep your logic separated and using PHP PDO instead of mysqli will save you a lot of headaches in the long run, but do what you want with what I posted. I'm more into photography than developing lately and with warmer weather arriving it will only get worse. 🤣
  11. and make sure you are inserting all the data if that is the whole script....
  12. The only time I use include is if I have multiple pages, here's an example -> <?php include_once "assets/includes/inc.nav.php"; ?> Here's the HTML though it has a little php in it: <div class="nav"> <input type="checkbox" id="nav-check"> <h3 class="nav-title">&nbsp;</h3> <div class="nav-btn"> <label for="nav-check"> <span></span> <span></span> <span></span> </label> </div> <div class="nav-links"> <a href="index.php">Home</a> <a href="photogallery.php">Gallery</a> <a href="/admin/index.php">Admin</a> <a href="game.php">Quiz</a> <a href="contact.php">Contact</a> <?php if (isset($_SESSION['id'])) { echo '<a href="/admin/logout.php">Logout</a>'; } ?> </div> </div> for configuration files I do this: require_once 'assets/config/config.php'; require_once "vendor/autoload.php"; and put them at the top.
  13. if ($user && password_verify($this->password, $user['hashed_password'])) { unset($this->password, $user['hashed_password']); session_regenerate_id(); // prevent session fixation attacks static::$last_login = $_SESSION['last_login'] = time(); $this->id = $_SESSION['id'] = $user['id']; header("Location: ../game.php"); exit(); } I run a small blog for my own personal website and I have a trivia game that I wrote, so I don't do too much error checking as I figured it's not like a banking website. If I was error checking I would log the errors in a log of some kind and never tell the user (other than to retry) what they did wrong, why give a hacker more clues than the need? 🤔😀 Sorry about my rambling, my point of the is post is session)_regenerated_id() should be used to prevent session fixation attacks.
  14. I know I am dating myself but I remember working on database tables before the internet and what we had the option of archiving the data (soft-delete the data) then purge the data (hard delete) if it was past so many years. I have seen online services do exactly that and I believe Meta (Facebook) Messenger gives you that option of archiving the data? Email should always be used as a constraint ALONG with a username or street address or better yet date of birth. It depends on how secure you need it. I know my doctor requires me to not only give my date of birth, but have me choose what is my address from four options to verify who I am when I check in online or even in person. As a business you have to have accountability if it means you can get into legal problems.
  15. I personally design for mobile first as that also takes care of most devices that are browser standard. What I mean is all the content goes does in succession at 100 percent which looks pretty good on a smartphone and other devices that don't recognize CSS. You can still stylize for mobile (smartphones for example), but really shines for larger devices like tablets, laptops and PCs. There you have the full arsenal of CSS with Grid or Flexbox, I personally like using Grid to design the overall design of website though media queries is a must in order for it to determine what device a person is using. I developed a simple Codepen demonstrating what I mean here - https://codepen.io/Strider64/pen/gOGqrxo Everyone does their CSS a little differently, but as a whole the foundation is the same when it comes to Grid, Flexbox and media queries. That's my .02 cents
  16. If you also use grids along with Flexbox then designing a website becomes really easy to do. An example - https://codepen.io/Strider64/pen/gOGqrxo
  17. I really don't understand what your asking? Pulling data from a database and styling the HTML with CSS are totally different from each other. Take my website - https://phototechguru.com/ for example the Home Page and the Gallery Page uses the same data (they don't have to) and are obviously different in appearance. Those two links look the same to me? I don't see why you could not use the same template? You might have to make a few minor tweaks, but I don't think it would be anything drastic? Here's the PHP for the gallery page: <?php $count = 0; foreach ($cms as $record) { echo '<div class="' . $displayFormat[$count] . '">'; echo '<div class="gallery-item">'; echo '<div class="images"><img src="' . $record['image_path'] . '" alt="Photo1" data-exif="' . $record['Model'] . ' ' . $record['ExposureTime'] . ' ' . $record['Aperture'] . ' ' . $record['ISO'] . ' ' . $record['FocalLength'] . '" width="800" height="534">'; echo '</div>'; $count++; echo '<div class="title">' . '<h1 class="pictureHeading">' . $record['heading'] . '</h1>' . '<span class="exifInfo">' . $record['Model'] . '</span>' . '</div>'; echo '</div>'; echo '</div>'; } ?> here's the PHP for the index page: <?php foreach ($cms as $record) { ?> <article class="cms"> <img class="article_image" src="<?= htmlspecialchars($record['image_path']) ?>" <?= getimagesize($record['image_path'])[3] ?> alt="article image"> <h2><?= $record['heading'] ?></h2> <span class="author_style">Created by <?= $record['author'] ?> on <time datetime="<?= htmlspecialchars(CMS::styleTime($record['date_added'])) ?>"><?= htmlspecialchars(CMS::styleDate($record['date_added'])) ?></time> </span> <p><?= $record['content'] ?></p> </article> <?php } ?> Pretty darn similar in my opinion and they are totally different looking pages.
  18. I'm not too sure as I haven't done it yet, but the only difference would be when you go fetch the data that instead of directly getting from PHP that you would get it from AJAX/JSON. That way the page doesn't reload and has a more seamless appearance to the user.
  19. There is really no 100 percent correct way of coding or in this case HTML/CSS, but most web designer/developers try to follow standard coding practices. If you want to decipher all the confusion then just go to https://validator.w3.org/ yourself. In my opinion HTML/CSS can pretty forgiving which can be a good or a bad thing.
  20. I been programming since the early 1980s, but I really didn't get started with website design and development until 2009 or 2010. Like you, I was let go from a job were I spent almost 20 years working in the automotive paint business. Decided to change field and went back to college as I was collecting severance that helped. I earned a degree in Computer Graphics when I learned design first (HTML/CSS) and then started back end development PHP by teaching myself. I agree with Barand learn HTML/CSS and maybe a little JavaScript (Vanilla...no libraries like jQuery at least at first). It shouldn't take too long to learn HTML/CSS and I would advice staying away from Bootstrap until you get a firm grasp of HTML/CSS as in my opinion knowing CSS good leads to less headaches later on. Once you get a firm grasp of HTML/CSS then start tackling PHP. I recommend pure PHP and no Frameworks at first as that is just leads to taking shortcuts then when you run into a problem you might never really understanding the solution. One thing I learn the hard way is never try to write your own security code in PHP just use PHP's builtin security functions and/or use a trusted third party's application (PHPMailer or Swiftmailer comes to mind). Be very careful of tutorials on the internet and even the good ones are outdated somewhat as the programming world changes fast. That's where these types of forums come in handy. One thing over the years that I have learn first hand is designers and developers have big egos that can lead to some healthy "heated" debates. 😂 After awhile every programmer gets his or her own coding style and there's nothing wrong in that as long as it isn't fundamentally wrong.
  21. I have done comment sections in the past in PHP and what I found useful is have two database tables. One for the main reply (thread) and the other for the replies that way if the thread should be deleted or messed up somehow (though I never had that happened) then simply delete the main thread id to the replies.
  22. Here's my PDO connection class that have used over the years. Maybe this will help? use mysql_xdevapi\Exception; use PDO; use PDOException; class Database { private PDO $_connection; // Store the single instance. private static ?Database $_instance = null; // Don't initialize before it is called: // Get an instance of the Database. // @return Database: protected static function getInstance(): Database { if (!self::$_instance) { self::$_instance = new self(); } return self::$_instance; } public static function pdo(): PDO { $db = static::getInstance(); return $db->getConnection(); } // Constructor - Build the PDO Connection: public function __construct() { try { $db_options = [ /* important! use actual prepared statements (default: emulate prepared statements) */ PDO::ATTR_EMULATE_PREPARES => false /* throw exceptions on errors (default: stay silent) */ , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION /* fetch associative arrays (default: mixed arrays) */ , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ]; $this->_connection = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD, $db_options); } catch (PDOException $e) { //echo $e; //echo "<pre>" . print_r($e->errorInfo, 1) . "</pre>"; if ($e->errorInfo[1] === 1045) { echo "User has the wrong credentials " . $e->errorInfo[1] . "<br>"; return false; } throw $e; // If PDO Exception error can't handle it throw it to Exception: } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; // Not for a production server: } return true; } // Empty clone magic method to prevent duplication: private function __clone() { } // Get the PDO connection: protected function getConnection(): PDO { return $this->_connection; } } to use simply do $stmt = Database::pdo()->prepare($sql); I just want to add this is just to add a PDO connection string to connect the Database Table, I would never send that error message on a production server.
  23. I personally don't use bootstrap, but I'm assuming it has grids? Anyways, I use grids and HTML for a two column format. A third column would be easy as well using CSS grids. Here's the two column form using grids: <main class="content"> <div class="container"> <?php foreach ($cms as $record) { ?> <article class="cms"> <img class="article_image" src="<?= htmlspecialchars($record['image_path']) ?>" <?= getimagesize($record['image_path'])[3] ?> alt="article image"> <h2><?= $record['heading'] ?></h2> <span class="author_style">Created by <?= $record['author'] ?> on <time datetime="<?= htmlspecialchars(CMS::styleTime($record['date_added'])) ?>"><?= htmlspecialchars(CMS::styleDate($record['date_added'])) ?></time> </span> <p><?= nl2br($record['content']) ?></p> </article> <?php } ?> </div> </main> Here's a small section of the CSS: /* Approximately the size of a 1248px large display monitor */ @supports (grid-area: auto) { @media screen and (min-width: 78em) { .site { display: grid; grid-template-columns: 1fr minmax(23.4em, 54.6em); grid-template-areas: "header header" "nav nav" "main main" "sidebar sidebar" "footer footer"; justify-content: center; width: 75em; margin: 0 auto; } .masthead { grid-area: header; background-image: url(../images/img-header-001pg.jpg); background-repeat: no-repeat; } .checkStyle { grid-area: main; font-size: 1.2em; } .sidebar { grid-area: sidebar; justify-content: center; } } // End of Screen Size } // End of Last Grid Area Using grids cuts down on the CSS as well as the HTML, plus CSS really should be in a separate file and not inline. I'm assuming it's your CSS, but I'm sure you can have CSS from bootstrap that is an external fire as well that you can change?
  24. I was bored today and decided to take a break from my own develop, so I decided to fool around with this and see if I could help. I don't know exactly what you are doing and I only used one database table to do this. However, I think what you are after can easily be modified? If not that's OK as I said I was bored. 😂 I don't know why you don't use MySQL to pull in the range values of the prices? I created a mythical Bicycle Shop called Rocket Bicycles : <table id="products"> <tr> <th colspan="4">The Rocket Bicycles Inventory</th> </tr> <tr> <th>Record</th> <th>Product</th> <th>Price ($)</th> <th>Quantity</th> </tr> </table> and I used Vanilla JavaScript (I find that is just as easy and is easily transferable) 'use strict'; (function () { let data = {}; /* The Following can easily be put into HTML via js */ data.min = 0; data.max = 2000.00; /* Handle General Errors in Fetch */ const handleErrors = function (response) { if (!response.ok) { throw (response.status + ' : ' + response.statusText); } return response.json(); }; const productCard = function (record){ /* Get the Table Id */ const table = document.getElementById('products'); /* Create the Table Row element */ const tr = document.createElement('tr'); /* Create the necessary Elements for the column data */ const id = document.createElement('td'); const product = document.createElement('td'); const price = document.createElement('td'); const quantity = document.createElement('td'); /* Append the Table Row element to the Table */ table.append(tr); /* Append the Column Row data to the Table Rows */ tr.append(id); tr.append(product); tr.append(price); tr.append(quantity); /* Assign the appropiate class to the table data row */ /* Give the appropiate table data the corresponding data */ id.classList.add('normal_format'); id.textContent = record.id; product.classList.add('product_format'); product.textContent = record.product; price.classList.add('money_format'); price.textContent = "$" + record.price.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); quantity.classList.add('normal_format'); quantity.textContent = record.quantity; }; /* Success function utilizing FETCH */ const inventoryUISuccess = function (records) { /* Grabing the record data from the Database Table * and assigning the value of the objects to the * HTML table using a forEach statement in * Vanilla JavaScript. */ records.forEach(record => productCard(record)); }; /* If Database Table fails to load then hard code the correct answers */ const inventoryUIError = function (error) { console.log("The Darn Database Table did not load", error); }; /* create FETCH request for check answers */ const price_range = function (url, succeed, fail) { fetch(url, { method: 'POST', // or 'PUT' body: JSON.stringify(data) }) .then((response) => handleErrors(response)) .then((data) => succeed(data)) .catch((error) => fail(error)); }; price_range('rockets_inventory.php', inventoryUISuccess, inventoryUIError); })(); the PHP for the "Fetching of the Data": <?php require_once 'assets/config/config.php'; /* Makes it, so we don't have to decode the json coming from javascript */ header('Content-type: application/json'); /* * The below must be used in order for the json to be decoded properly. */ try { $data = json_decode(file_get_contents('php://input'), true, 512, JSON_THROW_ON_ERROR); } catch (JsonException $e) { } /* * Grab the database table data that meets the price requirements */ $sql = 'SELECT id, product, price, quantity FROM rocket_bicycles WHERE price >= :min AND price <= :max ORDER BY price '; $stmt = $pdo->prepare($sql); // Prepare the query: $stmt->execute(['min' => (float)$data['min'], 'max' => (float)$data['max']]); // Execute the query with the supplied data: $result = $stmt->fetchAll(PDO::FETCH_ASSOC); /* * If everything validates OK then send success message to Ajax / JavaScript */ if (isset($result)) { output($result); } else { errorOutput('There is a darn problem!'); } /* * Throw error if something is wrong */ function errorOutput($output, $code = 500) { http_response_code($code); try { echo json_encode($output, JSON_THROW_ON_ERROR); } catch (JsonException) { } } /* * After converting data array to JSON send back to javascript using * this function. */ function output($output) { http_response_code(200); try { echo json_encode($output, JSON_THROW_ON_ERROR); } catch (JsonException) { } } and here's the SQL for the database table -- phpMyAdmin SQL Dump -- version 5.1.1 -- https://www.phpmyadmin.net/ -- -- Host: localhost:8889 -- Generation Time: Oct 08, 2021 at 11:24 PM -- Server version: 5.7.34 -- PHP Version: 8.0.8 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; -- -- Database: `php_sandbox` -- -- -------------------------------------------------------- -- -- Table structure for table `rocket_bicycles` -- CREATE TABLE `rocket_bicycles` ( `id` int(11) NOT NULL, `product` varchar(60) DEFAULT NULL, `price` float(6,2) NOT NULL, `quantity` int(6) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `rocket_bicycles` -- INSERT INTO `rocket_bicycles` (`id`, `product`, `price`, `quantity`) VALUES (1, 'Banana Rocket', 499.99, 5), (2, 'Pink Lady ', 499.99, 8), (3, 'Speed Demon', 999.98, 2), (4, 'Quick Silver', 1500.00, 1), (5, 'Lucky Lady', 300.00, 7); -- -- Indexes for dumped tables -- -- -- Indexes for table `rocket_bicycles` -- ALTER TABLE `rocket_bicycles` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `rocket_bicycles` -- ALTER TABLE `rocket_bicycles` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; COMMIT; and a little bit of css: #products { font-family: Arial, Helvetica, sans-serif; border-collapse: collapse; width: 90%; margin: 0 auto; } #products td, #products th { border: 1px solid #ddd; padding: 8px; } #products tr:nth-child(even) { background-color: #f2f2f2; } #products tr:hover { background-color: #ddd; } #products th { padding-top: 12px; padding-bottom: 12px; text-align: center; background-color: #04AA6D; color: white; } .normal_format { text-align: center; width: 6.250em; } .product_format { text-align: left; width: 6.250em; } .money_format { width: 3.125em; text-align: right; } Sorry for the long post, but I hope it helps:
  25. When I first started coding in PHP there was a person on here (I can't remember his name) that helped me out a lot. I was hung up on securing my code and spent all night writing a script that I thought was "secure" then the next day I posted it here. He replied back to me and the first thing he wrote was to throw that script in the trash. He went on to say people who write security code work in teams and test them out before they are introduced to the wild (internet). There is nothing wrong with prepared statement and unless you are a large corporation the speed of prepared statements is fast enough. Prepared statements are as secure as they possibly can be and nothing is 100 percent secure. So I totally disagree on the use of prepared statement.
  • 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.