ovi_gm Posted September 3, 2020 Share Posted September 3, 2020 Hello everyone, I am new to php and I need a confirmation if this is the correct approach for a code I wrote. Basically, I have a contacts.php page where I have a bootstrap table and a modal with some fields to add a new contact. I managed to write all the code, it works perfect but I want to know if this approach is ok. The application will be much more complex and I don;t want to start on the wrong foot here. I have 2 files: contacts.php and add_new_contact.php. First file, contacts.php: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <!-- ............ --> </head> <body> <!-- ............ here is the page layout--> <!-- Then I have my modal from bootstrap --> <div class="modal fade" id="addContact" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <form action = "add_new_contact.php" method="post"> <!-- .....content with all the inputs --> <button type="submit" class="btn btn-primary">Save to database</button> </form> </div> </body> </html> Now, in form action I am telling html to go to add_new_contact.php where I wrote the code for inserting all the values to the database. When doing this, it opens the page and it stays blank because there is no html there. So, in that php file I added a redirect code to the initial contacts.php. Here is the code: Second file: add_new_contact.php: <?php //all the code needed to insert the contact in the database header("Location: http//..../contacts.php"); exit(); ?> So, this works fine. But is this the best way to do it? Thank you. Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/ Share on other sites More sharing options...
mac_gyver Posted September 3, 2020 Share Posted September 3, 2020 1 hour ago, ovi_gm said: But is this the best way to do it? no. this results in a bad User eXperience (UX), takes more code, and gets your users used to automatically changing urls on your site, which increases the chance of a phishing site working. the form processing code should be on the same page as the form and the only redirect, upon successfully completing the form processing code, should be to the exact same url of the current page, to cause a get request for that page. any navigation to other pages should be via navigation links that the user can choose where he/she wants to go to. the form processing code would go above the start of the html document. you should also re-populate the form field values/selections when you re-display the form when there are validation errors. you didn't provide any details, but post method form processing code should - detect that a post method form was submitted before accessing any of the form data. if there is more than one form on a page, add logic to detect a unique value in the form data (a hidden field) to control which form processing code to execute. keep the submitted form data as an array, then use elements in the array throughout the rest of the code. trim all input data before validating it. you can do this with one array_map() statement, since you are keeping and operating on the data as a array. validate all the inputs, storing validation error messages in an array, using the field name or another appropriate name as the array index. this array is also an error flag. if the array is empty, there are no errors and you can use the submitted data. you can test/display the contents of this array at the appropriate point in the html document. if there are no validation errors, use the submitted data. if there are no (new) errors after using the submitted data, redirect to the exact same url of the page to cause a get request. if you want to display a one-time success message, store it in a session variable, then test/display/clear that variable at the appropriate point in the html document. Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581109 Share on other sites More sharing options...
ovi_gm Posted September 3, 2020 Author Share Posted September 3, 2020 Thank you very much for your time to write this message. The fact is that this is how I did it first, with the code on the same page, but I got items added to the database every time I did a refresh which is not ok. This is my code (I am writing only what is essential). I modified it like there's a single column in the database table (named "name"). <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <!-- Bootstrap core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" type"text/css" href="css/style.css"> <script src="http://cdn.ckeditor.com/4.6.1/standard/ckeditor.js"></script> </head> <body> <?php $name = $_POST["name"]; $servername = "localhost"; $username = "admin"; $password = "1234"; $dbname = "database"; $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); try { $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO contacts (name) VALUES ('$name')"; $conn->exec($sql); } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?> ------- HTML CONTENT ------------- ------- AND THEN THE MODAL ------- <div class="modal fade" id="addContact" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <form action = "contact.php" method="post"> <!-- .....content with all the inputs --> <input type="text" name = "name" value="" class="form-control" placeholder="Name of contact..."> <button type="submit" class="btn btn-primary">Save to database</button> </form> </div> I tried to put an if statement for the php code: if (isset($_POST['submit'])) { and here were the SQL statements } I even tried to set the name to null after the php code and then, at page refresh, check if the name is null or not. It doesn't work. It inserts the same record into the database everytime a do a refresh of the page. I am very good at Visual Basic programming and I think the philosophy of php is a bit different. There are some logic things that I don't get yet. Pls help. Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581113 Share on other sites More sharing options...
gw1500se Posted September 3, 2020 Share Posted September 3, 2020 Your SQL statements section is where you need to eliminate duplicates. Check to see if the record exists and if it does don't insert it. Perhaps you just do an update instead or let the user know it is an attempt to insert the same data. Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581114 Share on other sites More sharing options...
ovi_gm Posted September 3, 2020 Author Share Posted September 3, 2020 I know what you mean. Still, it doesn't seem right to me. You should be able to somehow execute that php ONLY when the submit button is pressed. What if I don't care if there are 2 or more contacts with the same name? It could be many identical entries only with the ID being different. Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581115 Share on other sites More sharing options...
gw1500se Posted September 3, 2020 Share Posted September 3, 2020 You are confusing me. PHP DOES only execute when the submit button is clicked. What makes you think it gets executed otherwise? Then you need to check for identical IDs. You didn't post your schema so it is difficult to be more specific. Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581116 Share on other sites More sharing options...
ovi_gm Posted September 3, 2020 Author Share Posted September 3, 2020 (edited) Ok. Schema is very simple. It is a database with a single table named contacts. The table has 2 columns: a primary Key ID and a name. I simplified it for the purpose of this topic. When I access my bootstrap modal, I enter for example name "Jim" in the input box. Then I click Submit. Then I have a new record in the database with ID 1 (or whatever is incremented). Now, everytime I refresh my page and do nothing else, there is a new record in the database with the new incremented ID and the same name (Jim). My logic says that php code is running everytime I hit reload. Otherwise, I don't understand how these entries appear. Edited September 3, 2020 by ovi_gm Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581117 Share on other sites More sharing options...
benanamen Posted September 3, 2020 Share Posted September 3, 2020 You need to implement PRG. (POST, REDIRECT, GET) Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581118 Share on other sites More sharing options...
gw1500se Posted September 3, 2020 Share Posted September 3, 2020 Part of the problem is way you generate your IDs. How do you know that it is the same Jim? For your immediate problem, you don't have the submit button associated with a form. You need to tell PHP what mode you are using (POST or GET). Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581119 Share on other sites More sharing options...
ovi_gm Posted September 3, 2020 Author Share Posted September 3, 2020 Shouldn't there be a line in the PHP code that tells it to run when the submit button is clicked? Something's missing. I have many pages on this site. If I click on another page and then come back to this page, there is an empty record added to the database. And it makes sense to be like this because there is a php code that gets executed every time the page is loaded. I'm really stuck here.... Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581120 Share on other sites More sharing options...
gw1500se Posted September 3, 2020 Share Posted September 3, 2020 Yes, you need to learn form handling. Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581121 Share on other sites More sharing options...
benanamen Posted September 3, 2020 Share Posted September 3, 2020 9 minutes ago, gw1500se said: Yes, you need to learn form handling. That particular tutorial has issues. Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581122 Share on other sites More sharing options...
ovi_gm Posted September 4, 2020 Author Share Posted September 4, 2020 Well, I researched today for hours and I couldn't find any solution to the problem. There are some solutions with an IF statement that seem to be very logical but they don't work. It just doesn't execute the if statement. if( isset($_POST) ) { //submit data to MySQL } By the way. Is there anything simple that I could write so that I know if an IF statement works or not? For example like a beep or something? Just to check if the code gets to a certain point or not... Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581151 Share on other sites More sharing options...
gw1500se Posted September 4, 2020 Share Posted September 4, 2020 Did you add a form to enclose your submit button? Show your HTML. Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581155 Share on other sites More sharing options...
ovi_gm Posted September 5, 2020 Author Share Posted September 5, 2020 It's shown above. Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581174 Share on other sites More sharing options...
Barand Posted September 5, 2020 Share Posted September 5, 2020 I have re-structured your code for you, adding a list of contacts so you can see if they are added. <?php $servername = "localhost"; $username = "admin"; $password = "1234"; $dbname = "test"; $conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); ## ## Has data been posted? ## if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (trim($_POST['name']) != '') { // use prepared statement $stmt = $conn->prepare("INSERT INTO contacts (name) VALUES (?)"); $stmt->execute( [ $_POST['name'] ] ); } // reload page header("Location: #"); exit; } ## ## Create contacts check list ## $res = $conn->query("select id , name from contacts order by id "); $list = ''; foreach ($res as $row) { $list .= "<tr><td>" . join ('</td><td>', $row) . "</td></tr>\n"; } ?> <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <!-- Bootstrap core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" type"text/css" href="css/style.css"> <script src="http://cdn.ckeditor.com/4.6.1/standard/ckeditor.js"></script> </head> <body> <div class="modal fade" id="addContact" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <form method="post"> <!-- .....content with all the inputs --> <input type="text" name = "name" value="" class="form-control" placeholder="Name of contact..."> <button type="submit" class="btn btn-primary">Save to database</button> </form> </div> <hr> <h3>Contacts Check List</h3> <table style='width: 400px;'> <tr><td>ID</td><td>Name</td></tr> <?=$list?> </table> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/311425-is-this-the-correct-approach/#findComment-1581175 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.