-
Posts
2,134 -
Joined
-
Last visited
-
Days Won
42
Everything posted by benanamen
-
I updated the LoginAttemptsLog.class.php to implement an interface. All works as expected. I would like feedback to make sure it is correct and the interface name LoginLogger.class.php is suitable for this Interface as well as the documentation. Secondly, I purposely added an extra char to an interface function to cause an error. What I noticed is that my set_exemption_handler function is not being called for this fatal error. Is there a different handling for class errors? Fatal error: Class LoginAttemptsLog contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (LoginLogger::logSuccessfulAttemptX) The new interface LoginLogger.class.php <?php /** * A login attempt logger */ interface LoginLogger { /** * Logs a login attempt * * @param string $username the attempted username to log */ function logFailedAttempt($username); function logSuccessfulAttempt($username); } LoginAttemptsLog.class.php <?php class LoginAttemptsLog implements LoginLogger { /** * @var PDO the connection to the underlying database */ protected $database; /** * Connection to underlying database * @param PDO $database */ public function __construct(PDO $database) { $this->database = $database; } /** * Log failed login attmpt * @param string $username */ public function logFailedAttempt($username) { $this->logAttempt($username, false); } /** * Log succesful login attempt * @param string $username */ public function logSuccessfulAttempt($username) { $this->logAttempt($username, true); } /** * Insert login attempt status * @param string $username * @param boolean $successful */ protected function logAttempt($username, $successful) { $attemptStmt = $this->database->prepare(' INSERT INTO user_login (login_status, login_ip, login_username, login_datetime) VALUES (?, INET_ATON(?), ?, NOW()) '); $attemptStmt->execute([($successful ? 1 : 0), $_SERVER['REMOTE_ADDR'], $username]); } }
-
I hate when people completely waste your time @requinix. The OP has absolutely no desire to learn.
-
I see how the classes are inheriting the interface documentation when I generate the docs. It seems I have the interface knowledge mastered now. Thanks for helping me understand it!
-
PHP help mysqli_query ()expects at least 2 parameters, 1 given
benanamen replied to akhilkumar332's topic in PHP Coding Help
You keep missing the part about NOT outputting the system errors to the user. As Jaques1 is going to tell you, get rid of the try catch blocks. Let the errors bubble up and catch them with set_exception_handler. Did you not read what was said about using strip_tags? This is going to go very slow for you if you aren't going to listen to what you are told. You might want to start your own thread. -
That really turned on the light bulb. Your previous in-code comment "// the class user is free to define custom classes as well" really falls into place now. I could see how a "class user" could want to log the same data to NoSQL or a text file. In the current VarDumper code you have made it clear there are three class files involved. 1. For the interface that would give us VarDumper.class.php with the following code. What would be the proper way to document an interface? Do we use the same documentation from the HTMLVarDumper class? VarDumper.class.php <?php interface VarDumper { function dump($title, $data); } 2. My question now goes to the app directory structure best practice for class subdirectories. Would/should all three of these classes go in say a Debugging directory in the main class directory? For example, The Laravel structure is vendor\laravel\framework\src\Illuminate\ //Class root vendor\laravel\framework\src\Illuminate\Cookie vendor\laravel\framework\src\Illuminate\Database vendor\laravel\framework\src\Illuminate\Session and so on. So would/should I do similar? vendor\benanamen\src\MywhateverName\Debugging vendor\benanamen\src\MywhateverName\Logging
-
Got it! So then I should go back to the class LoginAttemptsLog that we worked on and do an Interface for that right? That makes more sense then all the back and forth I read about it. Do you know of any official documentation why Symfony does it that way or what their thinking was? I will look into DI containers after Interfaces soaks in for awhile. Thanks for all the help. I believe I am getting Interfaces now. It makes sense when I think I may want output in JSON, XML, HTML or something else.
-
The full working class is in post #5. Can you show me what you just said with the actual class. I can understand code a lot better than explanations of a new concept I am just learning. There are only two working ways I know of so far to use the group of 3 classes (interface, html class, cli class) $varDumper = new HTMLVarDumper(); $varDumper->dump('POST', $_POST); OR $varDumper = new CLIVarDumper(); $varDumper->dump('POST', $_POST);
-
After much study I am left with just a few questions. 1. Interface file naming- Should an Interface file name be named something.interface.php? 2. To use term interface in the interface name or not? When a class implements something, the only thing it could be is an interface so why would you name the interface with the term interface in it? What is best practice and why? Symfony adds "Interface", Laravel is mixed Laravel use Psr\Log\LoggerInterface as PsrLoggerInterface; use Illuminate\Contracts\Logging\Log as LogContract; class Writer implements LogContract, PsrLoggerInterface Symfony abstract class AbstractDumper implements DataDumperInterface, DumperInterface class TestEventSubscriber implements EventSubscriberInterface class TestEventSubscriberWithPriorities implements EventSubscriberInterface 3. When should I use an interface? 4. Should ALL classes be interfaced? ******************************************************************* Here is what I now understand. Anything not correct here? ******************************************************************* Interfaces can only specify public methods therefore no need to do "public function" You cannot ever call an Interface directly. Wrong/errors e.g $interface = new myInterface(); Classes that use an interface MUST have the methods in the Interface or it will error A class can implement more than one interface. Names are separated by commas. e.g class MyClass implements interface1, interface2, interface3 Interface methods have no 'guts' to them, no body. Interfaces are essentially a blueprint for what you can create. They define what methods a class must have, but you can create extra methods outside of those limitations. - stack An interface says, “This is what all classes that implement this particular interface will look like.” Thus, any code that uses a particular interface knows what methods can be called for that interface, and that’s all. - stack if you want shorter names, easier refactoring and semantic meaning you should name your types what they represent and not what they are. https://phpixie.com/blog/naming-interfaces-in-php.html Interface sets the master rules for classes that use it. For example, if I want to output the same data to JSON, XML, CLI, or HTML, all of those classes implementing the Interface MUST have at least the interface method(s). implements keywords MUST be declared on the same line as the class name like extends. PSR-2 Lists of implements MAY be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list MUST be on the next line, and there MUST be only one interface per line. PSR-2 *****************************************************************
-
Your answer reads to me that I can just call the master class (interface VarDumper) and it "knows" whether to use interface VarDumper or HTMLVarDumper, but that is not possible. Perhaps you can clarify. I don't get your third example. Reads to me like you are saying $callVarDumper = new VarDumper(VarDumper $dumper); which is not possible.
-
I have read up on interfaces and it is not clicking yet. If I have two separate classes why do I need an interface when I can just call one or the other depending on if I want the html class or the CLI class. Additionally, If I am not going to use anything other than the html class why would it need an interface?
-
Just integrated the code and having a file naming issue. The interface is named VarDumper and there are two class names, HTMLVarDumper, CLIVarDumper. The auto class loader will look for a class file named the same as the "new classname" which for my current use is new HTMLVarDumper(). If I name the file HTMLVarDumper it negates that it is also a CLIVarDumper. (Currently not implemented though) VarDumper is the more fitting filename but it won't work with the autoloader since that is not one of the class names. Is there some OOP thing I don't know about or do I just name the file HTMLVarDumper.class.php and be done with it? Edit* Wouldnt the class CLIVarDumper best be used as an extended child, thus removing the class from the HTMLVarDumper file? This would also follow the one class per file PSR right? If so how and where would you document that there is an extended CLI class of the same purpose so that it makes sense when you see the interface usage? Would the CLI class then go in a separate folder just for CLI classes?
-
Hmm. What would you have done with using only the data the OP provided. I did start out with a UNION with OP's data but wasn't sure if he needed a multi-row result. Data is still the same, just one row and a third the code.
-
You are advertising the server type and version (nginx/1.11.5) There are 87 Code errors most of which are the same ones repeated in each page. #5 and #6 from post 9 have not been addressed
-
I am just looking to learn the optimum best practices for OOP. I have just started to read up on unit testing and writing tests. Have not actually wrote one yet. OOP is finally starting to make sense to me.
-
@barand, where did you get the additional flight info? OP pm you? I only had the 3 records to work with.
-
The auto scanner Sensio is mostly where it came from. So, this will not affect unit testing?
-
Continuing from https://forums.phpfreaks.com/topic/302938-oop-class-code-review/ in regards to a global being used in a class, my research shows that you do not want to use globals in a class. How then should this last line be properly dealt with? In another thread @requinix said as long as you are not changing anything it is ok. Reference https://forums.phpfreaks.com/topic/302901-oop-convert-function-to-class/?do=findComment&comment=1541244 $attemptStmt->execute([($successful ? 1 : 0), $_SERVER['REMOTE_ADDR'], $username]);
-
Once you showed the last code, yes it is easy. What is the proper way to document the code? Do you do it at ALL the functions or just the interface function? Seems redundant if documentation is exactly the same for each function. I know function alone is the same as public function. Is it best practice to always use public anyways? This is what I have done with your help. Any problems? I have not messed with CLI yet so no clue about that part right now. <?php /** * Dumps data */ interface VarDumper { function dump($title, $data); } class HTMLVarDumper implements VarDumper { /** * @param string $title * @param ?? $data */ function dump($title, $data) { echo '<pre><span style="color:red;font-weight:bold">'; echo $title . '<br>'; print_r($data); echo '</span></pre>'; } } class CLIVarDumper implements VarDumper { function dump($title, $data) { // output for CLI contexts } } // the class user is free to define custom classes as well $_POST = ['username' => 'MyUsername', 'email' => 'user@example.com']; $varDumper = new HTMLVarDumper(); $varDumper->dump('POST', $_POST);
-
I had it as a function. I am just trying to learn OOP. Can you give an example of a static method please. Good to know. I was wondering about the html when I did it. For the purpose of viewing the superglobal arrays, what other format could you possibly want besides print_r? Yes, I know. I noticed it after I posted. Too late to edit post. I realized later that the superglobals are not the only thing that could be passed to the class. Since you pointed it out, I can see how the name could be confusing. In another post I asked how to properly use superglobals with a class. The answer I got was not particularly helpful. What would be a name that makes sense to you? It should actually go right above the constructor right? I noticed later @param $title was missing. Right now I don't know what that means. Any other info would be helpful. How would I use the code you posted?
-
@clukas, With your table you don't need any relationships or junction tables and you don't need more than one query. Output from code: Array( [Flight One] => 300 [Depart One] => MIA [Arrive One] => JFK [Flight Two] => 100 [Depart Two] => JFK [Arrive Two] => LHR [Flight Three] => 200 [Depart Three] => LHR [Arrive Three] => FRA) Flight Itenerary 1. Flight 300 MIA To JFK 2. Flight 100 JFK To LHR 3. Flight 200 LHR To FRA <?php $hostdb = 'localhost'; $dbname = 'flights'; $username = 'root'; $password = ''; $pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "SELECT f1.flt_num AS 'Flight One', f1.arr_airport AS 'Depart One', f1.dep_airport AS 'Arrive One', f2.flt_num AS 'Flight Two', f2.arr_airport AS 'Depart Two', f2.dep_airport AS 'Arrive Two', f3.flt_num AS 'Flight Three', f3.dep_airport AS 'Depart Three', f3.arr_airport AS 'Arrive Three' FROM myflights AS f1, myflights AS f2, myflights AS f3 WHERE f1.id = 3 AND f2.id = 1 AND f3.id = 2"; $stmt = $pdo->prepare($sql); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); echo "<pre>"; print_r($row); echo "</pre>"; ?> Flight Itenerary <br> 1. Flight <?= $row['Flight One'] ?> <?= $row['Depart One'] ?> To <?= $row['Arrive One'] ?> <br> 2. Flight <?= $row['Flight Two'] ?> <?= $row['Depart Two'] ?> To <?= $row['Arrive Two'] ?> <br> 3. Flight <?= $row['Flight Three'] ?> <?= $row['Depart Three'] ?> To <?= $row['Arrive Three'] ?> -- ---------------------------- -- Table structure for myflights -- ---------------------------- DROP TABLE IF EXISTS `myflights`; CREATE TABLE `myflights` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dep_airport` varchar(255) DEFAULT NULL, `arr_airport` varchar(255) DEFAULT NULL, `flt_num` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of myflights -- ---------------------------- INSERT INTO `myflights` VALUES ('1', 'LHR', 'JFK', '100'); INSERT INTO `myflights` VALUES ('2', 'LHR', 'FRA', '200'); INSERT INTO `myflights` VALUES ('3', 'JFK', 'MIA', '300');
-
You are missing the closing } There are other problems. You need to use prepared statements. You never insert user supplied data directly to the DB. Dont SELECT *. Specify the columns you want. You also do not need to manually close the connection. It closes automatically. It would appear your logic is flawed. You can't throw two query parameters into mysql like that. And don't create variables for no reason. I formatted your code so it is more readable but it still needs fixing aside from the missing bracket I put in. I would recommend you use PDO. https://phpdelusions.net/pdo <?php if (isset($_POST['choices']) && !empty($_POST['choices'])) { if ($_POST['choices'] == 'four') { //variables from form entered $username = $_POST['username']; $neptune = $_POST['neptune']; $email = $_POST['useremail']; //connect to the database $dbc = mysqli_connect('localhost', 'root', '', 'happygam_main') or die('Error connecting to MySQL server'); $check = mysqli_query($dbc, "select * from ballot where username='$username' and neptune='$neptune'"); $checkrows = mysqli_num_rows($check); if ($checkrows > 0) { echo "This combination of neptune and username has already been processed"; } else { //insert results from the form input in 2 rows one with neptune one without $query = "INSERT IGNORE INTO ballot(username, useremail, neptune) VALUES('$username', '$email', '$neptune')"; $query1 = "INSERT IGNORE INTO ballot(username, neptune) VALUES('$username', '$neptune')"; $result = mysqli_query($dbc, $query, $query1) or die('Error querying database.'); mysqli_close($dbc); } } } ?>
-
Need help figuring out the most efficient way to do something.
benanamen replied to PandaDynamite's topic in PHP Coding Help
Your question is way too broad. Do you already know PHP and Mysql? Do you know PDO? What about HTML and CSS? What have you tried? Have you set up a local LAMP stack such as XAMMP? You are going to have to have some knowledge in all of those. -
The following is my further attempt to learn OOP. Is there anything technically wrong with it or is there any better practices in the code or its use? Purpose is to display dev/debugging data. Your feedback is appreciated. * Code in forum is on one page so you can easily run it if desired. <?php /** * Displays data from $_COOKIE, $_SESSION, $_GET, $_POST, $_REQUEST * @param string $debug COOKIE, SESSION, GET, POST, REQUEST */ class DebugDisplay { private $title; private $debug; public function __construct($title, $debug) { $this->title = $title; $this->debug = $debug; } public function ShowDebug() { echo '<pre><span style="color:red;font-weight:bold">'; echo $this->title . '<br>'; print_r($this->debug); echo '</span></pre>'; } } //---------------------------------------------------------------------------------------- // Test Data //---------------------------------------------------------------------------------------- $_COOKIE[] = 'COOKIE Data'; $_SESSION[] = 'SESSION Data'; $_REQUEST[] = 'REQUEST Data'; $_GET[] = 'GET Data'; $_POST[] = 'POST Data'; //---------------------------------------------------------------------------------------- // Debugging //---------------------------------------------------------------------------------------- define("DEBUG", true); // Toggle Debugging define("SHOW_DEBUG_PARAMS", DEBUG); // Display Sql & Sql Parameters define("SHOW_SESSION_DATA", DEBUG); // Display Session Data define("SHOW_POST_DATA", DEBUG); // Display Post Data define("SHOW_GET_DATA", DEBUG); // Display Get Data define("SHOW_COOKIE_DATA", DEBUG); // Display Cookie Data define("SHOW_REQUEST_DATA", DEBUG); // Display Request Data if (DEBUG === true) { echo '<div class="error_custom"><H1>DEBUGGING IS ON !!!</H1></div>'; } if (SHOW_COOKIE_DATA === true) { $show = new DebugDisplay('COOKIE', $_COOKIE); echo $show->ShowDebug(); } if (SHOW_SESSION_DATA === true) { if (isset($_SESSION)) { $show = new DebugDisplay('SESSION', $_SESSION); echo $show->ShowDebug(); } } if (SHOW_POST_DATA === true) { $show = new DebugDisplay('POST', $_POST); echo $show->ShowDebug(); } if (SHOW_GET_DATA === true) { $show = new DebugDisplay('GET', $_GET); echo $show->ShowDebug(); } if (SHOW_REQUEST_DATA === true) { $show = new DebugDisplay('REQUEST', $_REQUEST); echo $show->ShowDebug(); } Application Output
-
please help dynamic radio button insertion into database
benanamen replied to newone's topic in PHP Coding Help
You have several other issues but as to your problem. Your button group is named name='RadioGroup1' but you are trying to insert ans. There is no $_POST['ans']. There is also no $_POST['value'] either. You also gave two buttons the same value. You also have a ridiculous amount of unnecessary escaping. Your opening form tag is in the completely wrong place. The whole bit of code is quite a mess. You need to take a minute and study some basic tutorials. The whole thing needs a complete re-write. And while you're at it you should do it in PDO. https://phpdelusions.net/pdo Edit * It looks like you were already give good information on this in your other posts but you did not listen to what you were told. Your were even given code by @gingerjm that you ignored. You are just wasting our time if you're not going to do what we tell you. After seeing the other posts and responses you got you have now irritated me for wasting my time on this post. -
If you dont know html and CSS, start here :https://www.codecademy.com/learn/web Then go here https://www.codecademy.com/learn/php When you get farther along study this: https://phpdelusions.net/pdo Install XAMPP to run, test and learn on your local computer https://www.apachefriends.org/index.html