Jump to content

Saving to mysql database not working!


rocky48

Recommended Posts

I have not done any php coding for some time and I can't figure out why this coding is not working?

I am trying to create a form for my club so that members can fill in a form online.

I have written a form which is in html which using POST collects the data from the form and should INSERT it into the database.

Here is the html file:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="generator" content="RSD 5.0.3519">
  <title>Senior Form</title>
  <link rel="stylesheet" href="css/bootstrap4.min.css">
  <link rel="stylesheet" href="css/wireframe-theme.min.css">
  <script>document.createElement( "picture" );</script>
  <script class="picturefill" async="async" src="js/picturefill.min.js"></script>
  <link rel="stylesheet" href="css/main.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Averia+Sans+Libre:400,b%7CRoboto:400,900,b">
</head>

<body class="body-3"><div class="responsive-picture picture-1 align-content-md-center">
    <picture>
      <img alt="Placeholder Picture" width="1200" height="300" src="./images/1066MFC%20Banner.jpg" loading="lazy">
    </picture>
  </div>
  <nav class="container-grid navbar navbar-expand-lg navbar-dark bg-dark">
    <h3 class="navbar-brand">MENU</h3><button type="button" class="btn navbar-toggler navbar-toggler-icon button Dropdown-toggle" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-label="Toggle navigation"></button>
    <div class="container-grid collapse navbar-collapse" id="navbarNavDropdown">
      <ul class="list-container navbar-nav">
        <li class="list-item-container nav-item">
          <a class="link-text nav-link" href="index.html" title="">HOME</a>
        </li>
        <li class="list-item-container nav-item">
          <a class="link-text nav-link" href="about.html" title="">ABOUT</a>
        </li>
        <li class="list-item-container nav-item dropdown">
          <a class="link-text nav-link dropdown-toggle" href="members.html#navbarNavDropdown" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">MEMBERS</a>
          <div class="container-grid dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
            <a class="link-text dropdown-item" href="members.html" title="">Members</a>
            <a class="link-text dropdown-item" href="aerodrome.html" title="PEBSHAM AERODROME">Pebsham Aerodrome</a>
            <a class="link-text dropdown-item" href="emergency%20numbers.html">Emergency Numbers</a>
          </div>
        </li>
        <li class="list-item-container nav-item">
          <a class="link-text nav-link" href="newmem.html" title="New-Member">NEW MEMBER</a>
        </li>
        <li class="list-item-container nav-item">
          <a class="link-text nav-link" href="contact.html" title="">CONTACT</a>
        </li>
      </ul>
      <a class="link-text text-link-4" href="https://1066modelflying.club/coppermine/index.php" title="Gallery">GALLERY</a>
    </div>
  </nav>
 

<h1>SENIOR RENEWAL FORM</h1>
<form name="senior_data" method="post"
<fieldset><ledgend>Please enter your infomation in the form below: </legend>
<h2>2023 Senior Membership Renewal Form</h2>
<p>Please remember that the club & BMFA membership runs out at the end of December.
<br>

2023 1066 MFC Membership &#163;10.00<br>
BMFA Membership/Insurance &#163;40.00<br>
Family Partner Senior &#163;27.00<br>
CAA Operator Fee &#163;10.00<br>
BMFA Membership Reward Card &#163;4.50<br>
British Drone Flyers Association Members &#163;5.00<br>
</p><br>
<p><b>Name:</b><br> <input type="text" name="name" size="20" maxlength="40"/></p>
<label for="dob"><b>Date of birth:</b></label>
<input type="date" id="dob" name="dob "
       value=""
       min="1900-01-01" max="2050-12-31">
<p><b>
<br>
<label for="addr">Address:</label><br>
<textarea id="addr" name="addr" rows="4" cols="50">
</textarea>
<br>
<label for="phone">Phone number:</label>
<input type="tel" id="phone" name="phone"
       
       required>
<br>
<label for="mob">Mobile number:</label>
<input type="tel" id="mob" name="mob"
       
       required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
    <br>
<label for="bmfa_no">BMFA No:</label>
<input type="text" id="bmfa_no" name="bmfa_no">
    <br>
<label for="caa_no">CAA Operator No:</label>
<input type="text" id="caa_no" name="caa_no"><br>

<label for="club_membership">Do you wish that the club obtains your BMFA membership, Insurance & CAA renewal:</label>
  <select name="club_membership" id="club_membership">
    <option value="blank ">  </option>
    <option value="NO">NO</option>
    <option value="YES">YES</option>
  </select>
  <br>
  <label for="Ctry">Are you a Country Member:</label>
  <select name="Ctry" id="Ctry">
    <option value="blank ">  </option>
    <option value="NO">NO</option>
    <option value="YES">YES</option>
  </select>
<br>
   <label for="caa">If you answered YES to the previous question,. have you a current BMFA and CAA membership:</label>
  <select name="caa" id="caa">
    <option value="blank ">  </option>
    <option value="NO">NO</option>
    <option value="YES">YES</option>
    <option value="na">N/A</option>
  </select>
  <br>
<label for="rewd">Do you wish to purchase a BMFA Membership/Reward Card:</label>
  <select name="rewd" id="rewd">
    <option value="blank ">  </option>
    <option value="NO">NO</option>
    <option value="YES">YES</option>
  </select>
 <br> 
  <label for="fam">Are you a family member:</label>
  <select name="fam" id="fam">
    <option value="blank ">  </option>
    <option value="NO">NO</option>
    <option value="YES">YES</option>
  </select>
  <br>
  <label for="bdf">Do you wish to join the British Drone flyers Association, instead of the BMFA:</label>
  <select name="bdf" id="bdf">
    <option value="blank ">  </option>
    <option value="NO">NO</option>
    <option value="YES">YES</option>
  </select>
  <p>Please note that if you join the BDF you can also fly fixed wing/ helicopters as well!</p>
  
  <br>
  <label for="pay_opt">Ho do you wish to pay:</label>
  <select name="pay_opt" id="pay_opt">
    <option value="blank ">  </option>
    <option value="chq">CHEQUE</option>
    <option value="csh">CASH</option>
    <option value="bacs">BACS</option>    
  </select>
  <br>
    <p><b>Payment required: &#163;</b><input type="text" name="pay" size="20" maxlength="40"/></p>
    <br>
    <p style="background-color:tomato;">I apply for membership of the 1066 Model Flying Club and agree to abide by the rules. 
By doing so agree to allow the club to use your details in respect of the GDPR regulations for the processing of your renewal, a copy of which can be found on the club website members page.
</p>
    <br>
  <label for="date">Date:</label>
<input type="text" id="date" name="date"
       pattern="[0-9]{2}/[0-9]{2}/[0-9]{4}"
       required>
 <br>   
 <label for="sign">Sign here:</label>
 <input type="text" id="sign" name=sign"
             required>
    <br>
    <input type="submit" value="submit">

Here is the file that copies the posted output and inserts it into the database:

<?php
 include ("conn/connect_seniorform.php");
 $conn=get_db_conn_senior();
 if ($_SERVER["REQUEST_METHOD"]== "POST"{
    $id = $REQUEST['id'];
    $name = $REQUEST['name'];
    $dob = $REQUEST['dob'];
    $addr = $REQUEST['addr'];
    $phone= $REQUEST['phone'];
    $mob = $REQUEST['mob'];
    $email =$REQUEST['email'];
    $bmfa_no = $REQUEST['bmfa_no'];
    $caa_no = $REQUEST['caa_no'];
    $rewd = $REQUEST['rewd'];
    $fam = $REQUEST['fam'];
    $ctry = $REQUEST['ctry'];
    $ctry_bmfa = $REQUEST['ctry_bmfa'];
    $bdf = $REQUEST['bdf'];
    $pay_opt = $REQUEST['pay_opt'];
    $pay = $REQUEST['pay'];
    $date = $REQUEST['date'];
    $sign = $REQUEST['sign'];
    
    $sql = "INSERT INTO senior_dat VALUES ($id,$name,$dob,$addr,$phone,$mob,$email,$bmfa_no,$caa_no,$rewd,$fam,$ctry,$ctry_bmfa,$bdf,$pay_opt,$pay,$date,$sign");
 if(mysqli_query($conn,$sql)){
    echo "<h3> Form saved OK"</h3>;
 }else{
    echo nl2br(You have an input error);
 }
 }
 mysqli_close($conn);
?>

I do not get any errors, but nothing appears in the database. As I have not done any php coding in years I used some methods I found on the web.

Can anyone tell me where I am going wrong?

Link to comment
Share on other sites

Here is a cleaned-up version of your php:

// Turn on error checking
error_reporting(E_ALL);
ini_set('display_errors', '1');

//  check if a form has been submitted
if ($_SERVER["REQUEST_METHOD"]== "POST"
 {
    $id = $_POST['id'];
    $name = $_POST['name'];
    $dob = $_POST['dob'];
    $addr = $_POST['addr'];
    $phone= $_POST['phone'];
    $mob = $_POST['mob'];
    $email =$_POST['email'];
    $bmfa_no = $_POST['bmfa_no'];
    $caa_no = $_POST['caa_no'];
    $rewd = $_POST['rewd'];
    $fam = $_POST['fam'];
    $ctry = $_POST['ctry'];
    $ctry_bmfa = $_POST['ctry_bmfa'];
    $bdf = $_POST['bdf'];
    $pay_opt = $_POST['pay_opt'];
    $pay = $_POST['pay'];
    $date = $_POST['date'];
    $sign = $_POST['sign'];
    
    $sql = "INSERT INTO senior_dat VALUES ($id, $name, $dob, $addr, $phone, $mob, $email, $bmfa_no, $caa_no, $rewd, 
				$fam, $ctry, $ctry_bmfa, $bdf, $pay_opt, $pay, $date, $sign");
	if(mysqli_query($conn, $sql))
		echo "<h3>Form saved OK</h3>";	// YOU HAD AN ERROR HERE
	else
		echo "You have an input error";	// YOU HAD AN ERROR HERE 
 }

Corrected the ending lines of echo statements.  Changed your use of $_REQUEST to be $_POST.  It's a post form so USE post values.

As for the comment about the query being wrong, other than the misplaced ')',  I can't say since I don't know your table layout.   Also - you s/b doing some kind of validation on all of that input and, as suggested also, you s/b using a prepared statement instead of just trying to use user input to update your db.

I didn't even look at your enormously complex html code.

Edited by ginerjm
Link to comment
Share on other sites

until you get your code to work for one form field, there's no good point in writing out php code and html markup for all the form fields, that you will need to make multiple changes to before getting it to the point of working. pick one field, such as the visitor's last name (most people have two names and your form and database table needs two fields, so that you can distinguish between the first and last name, for example is someone Martin Ross or Ross Martin.)

in the php code, there's actually only one line worth keeping, e.g. checking if a post method form was submitted. you should -

  1. have any error related settings in the php.ini on your system so that ALL php detected errors will get reported. the initial php syntax errors present will prevent your code from running at all, so any error related settings in your code won't take effect.
  2. use 'require' for things your code must have for it to work and include/require are not functions. the () around the filename are unnecessary clutter.
  3. keep the form data as a set, in a php array variable, then operate on elements in this array variable throughout the rest of the code, i.e. don't copy variables to other variables for nothing. this is just a waste of your time typing.
  4. as has already been mentioned, use $_POST for the post input data. you also have a mistake in the syntax for $REQUEST (there's an under-score after the $, which is another good reason to get your code to fully work for one form field, before worrying about all the code needed for the rest of the fields.)
  5. trim all the input data, mainly so that you can detect if it consists of all white-space characters, before validating it. after you do item #3 on this list, you can trim all the data at once using a single line of php code.
  6. validate all the input data before using it, storing user/validation errors in an array, using the field name as the array index.
  7. after the end of all the validation logic, if there are no errors (the array will be empty), use the submitted form data.
  8. you should switch to the much simpler and more modern PDO database extension, especially since you will be converting this query to be a prepared query in order to prevent any sql special characters in the values from being able to break the sql query syntax, which is how sql injection is accomplished.
  9. you should use exceptions for database statement errors and in most cases simply let php catch and handle any database exception. the exception to this rule is when inserting/updating duplicate or out of range user submitted values. in this case, you code should catch the exception, test if the error number is for something that your code is designed to handle, such as a duplicate index error for fields that must be unique, e.g. the email field, and setup a message telling the visitor exactly what was wrong with the data that they submitted. for all other error numbers, just rethrow the exception and let php handle it.
  10. list out the columns you are providing values for in the insert query. this will let you eliminate things like the id column, which the value you are  currently attempting to provide doesn't exist, e.g. there's no id field in the form and any php code referencing it will be producing php errors.
  11. if you were putting values directly into the sql query statement (you won't be when using a prepared query), you would need to put single-quotes around any literal string values, so that they don't produce sql errors about non-existent columns named the same as the data values.
  12. not sure why you are applying nl2br() to a value that doesn't have any new-line characters in it.
  13. after the end of all the post method form processing logic, if there are no errors, you would preform a redirect to the exact same url of the current page to cause a get request for that page.
  14. any redirect needs an exit/die statement after it to stop php code execution.
  15. to display a one-time success message, store it in a session variable, then test, display, and clear the session variable at the appropriate location in the html document.
  16. if at item #7 or #13 on this list, there are errors, your code will continue on to redisplay the html document, display any user/validation errors, redisplay the form, repopulating the form field values/selections with the existing values, so that the user doesn't need to keep re-entering data over and over when there are errors.
  17. any external, unknown, dynamic value that you output in a html context should have htmlentities() applied to it when it is being output, to help prevent cross site scripting.
  18. there's no good point in closing database connections since php will automatically destroy everything that was created on a page when your script ends.

 

Edited by mac_gyver
  • Great Answer 1
Link to comment
Share on other sites

Thanks for the information!

I'm thinking its the connection code that isn't working!

I have used the following format before and haven't had any problems.  I've redacted the login data for obvious reasons.  I have double checked the loin data and know that it is correct.

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//set up a connection
function get_db_conn_senior() {
	$host_name = "xxxxxxxxxxxxxxx";
	$database = "xxxxxxxxxx";	// Change your database name
	$username = "xxxxxxxxxx";  	// Your database user id 
	$password = "xxxxxxxxxx";	// Your password
    
    //connect to server and select database; you may need it
    $conn = new mysqli($host_name, $username, $password, $database);
   echo "Connected";
   
    //if connection fails, stop script execution
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    return $conn;
}
?>

I have put the echo in to see if it connects, but no message is shown.

But surely if it did not connect I would get the fail message?

I cut down the html file to one input, but still not populating the database.

What can I do next to get this working?

Link to comment
Share on other sites

I found on my host a connection script so I tried that and it works and gives my a message to say that it is connected.

I put that a the top of my shortened script and entered my name in the name input box.

I then checked the database and nothing was written.

I have tried to use some prepared statements, but it did not work.

As this is new to me I may have got the script wrong.

Can you help?

<?php
 
  $host_name = 'xxxxxx';
  $database = 'xxxx';
  $user_name = 'xxxx';
  $password = 'xxxx';

  $link = new mysqli($host_name, $user_name, $password, $database);

  if ($link->connect_error) {
    die('<p>Failed to connect to MySQL: '. $link->connect_error .'</p>');
  } else {
    echo '<p>Connection to MySQL server successfully established.</p>';
  }

//  check if a form has been submitted
if ($_SERVER["REQUEST_METHOD"]== "POST"
{
        $name = $POST['name'];
   
    
    $sql = $mysqli->prepare("INSERT INTO senior_dat VALUES (?)");
 $label = 'PHP';
 $sql->bind_param("is",$label);
$sql->execute
    echo "<h3> Form saved OK"</h3>;
 else
    echo "nl2br(You have an input error)";
 }

?>

 

Link to comment
Share on other sites

your posted connection code works for me, so it probably isn't being executed at all.

what output do you get? and if it's a blank page, what does the 'view source' in your browser show?

are you requesting your main page using a URL to the web server on your development system? the url should be similar to - http://localhost/your_main_file.php NOT something like file:///C:/xampp/htdocs/your_main_file.php, which is a file system path and doesn't cause the php code to be executed.

your first posted code contains a number of php syntax errors that will prevent it from running at all. until you actually do item #1 on my list, php will not help you with php syntax errors in all your files because putting the php error related settings in a file won't cause the settings to take effect because the code in that file doesn't run when there's a php syntax error in that file.

beyond the above points, you would need to post your current code to get any help with it.

if you incorporate all the practices listed, which are designed to make your code secure, in all contexts, provide a good User eXperience (UX), by letting the user know when they did something that they can correct and prevent them from having to keep retyping information over and over, result in simple general-purpose code, that doesn't have you typing a bunch unnecessary things that don't contribute to a working application, through the php error related settings (item #1 in my list), the validation logic (item #6), and having error handling (item #9), your code will either work or it will tell you why it isn't.

here's an example showing all the posted points -

<?php

// initialization
session_start();

// why not have the connection code actually make the connection too, so that you don't need another line of code?
require "conn/connect_seniorform.php";
// note: this code uses the much simpler and more modern PDO database extension
// when you make the connection -
// set the character set to match your database tables, so that no character conversion occurs over the connection 
// set the error mode to use exceptions, so that all the database statements will use exceptions (this is the default now in php8, but set it anyways)
// set emulated prepared queries to false, you want to run real prepared queries
// set the default fetch mode to assoc, so that you don't need to specify it in each fetch statement

$post = []; // array to hold a trimmed working copy of the form data
$errors = []; // array to hold user/validation errors

// post method form processing
if($_SERVER["REQUEST_METHOD"]==="POST")
{
	// inputs: first_name (add others once code is working)
	
	// trim all the input data at once
	$post = array_map('trim',$_POST); // if any input is an array, use a recursive trim call-back function here instead of php's trim
	
	// validate all inputs
	// first name
	if($post['first_name'] === '')
	{
		$errors['first_name'] = "First Name is required";
	}
	
	// validate other inputs here...
	
	// if no errors, use the input data
	if(empty($errors))
	{
		$sql = "INSERT INTO senior_dat (first_name) VALUES (?)";
		$stmt = $pdo->prepare($sql);

		// note: the following try/catch error handling deals with having a (single) unique column (email) defined in your database table
		// if you have multiple unique columns defined, you would execute a SELECT query inside the catch code to find which column(s) contain duplicate values matching the input data and setup an error message for each one
		try { // a 'local' try/catch to handle a specific error type 
			$stmt->execute([
				$post['first_name'],
				]);
		} catch (PDOException $e) {
			if($e->errorInfo[1] == 1062) // duplicate key error number
			{
				$errors['email'] = "Email is already in use";
			} else { 
				throw $e; // re-throw the pdoexception if not handled by this logic 
			}
		}
	}
	
	// if no errors, success
	if(empty($errors))
	{
		$_SESSION['success_message'] = "Form saved OK";
		die(header("Refresh:0"));
	}
}

// hrml document starts here...
?>

<?php
// display and clear any success message
if(!empty($_SESSION['success_message']))
{
	echo "<p>{$_SESSION['success_message']}</p>";
	unset($_SESSION['success_message']);
}
?>

<h1>SENIOR RENEWAL FORM</h1>
<?php
// display any errors
if(!empty($errors))
{
	echo '<p>'; echo implode('<br>',$errors); echo '</p>';
}
?>
<form method="post">
<label><b>First Name:</b><br><input type="text" name="first_name" size="20" maxlength="40" value="<?=htmlentities($post['first_name']??'',ENT_QUOTES)?>"></label>
<br>
<input type="submit" value="submit">
</form>

if you insist on using the overly complicated and inconsistent mysqli database extension, adding the following line of code, before the point where you make the database connection, will cause it to use exceptions for errors (item #9 on my list) -

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

 

Link to comment
Share on other sites

Here is your lastest code with some notes.  But you REALLY SHOULD USE MAC_GYVER'S CODE.  PDO is so much easier to use.

// TURN ON ERROR CHECKING
error_reporting(E_ALL);
ini_set('display_errors', '1');
 
$host_name = 'xxxxxx';
$database = 'xxxx';
$user_name = 'xxxx';
$password = 'xxxx';
$link = new mysqli($host_name, $user_name, $password, $database);
if ($link->connect_error) 
	die('Failed to connect to MySQL: '. $link->connect_error);
else 
	echo 'Connection to MySQL server successfully established.';

//  check if a form has been submitted
if ($_SERVER["REQUEST_METHOD"]== "POST"
{
	$name = $POST['name'];
	//  WHAT IF THE FORM WASN'T SUBMITTED?
	//  SINCE YOU ARE ONLY INSERTING ONE VALUE PERHAPS YOU S/B NAMING IT IN YOUR QUERY
	$sql = $mysqli->prepare("INSERT INTO senior_dat VALUES (?)");
	$label = 'PHP';
	$sql->bind_param("is",$label);
	// READ THE MANUAL ON THIS SO YOU CAN USE IT CORRECTLY. OR CHANGE TO THE NON-DEPRECATED FUNCTION.
	// AND ADD THE SEMI.
	$sql->execute
	//  HOW CAN YOU ISSUE THIS MESSAGE WHEN YOU AREN'T CHECKING IF THE EXECUTE RAN?
	echo "<h3> DATA saved OK"</h3>;
}
else
	echo "You have an input error";

 

Link to comment
Share on other sites

re: your last post above. if you are seeing the form, given that there are php syntax errors still present, it is likely that you are not requesting the page using a url -

15 minutes ago, mac_gyver said:

are you requesting your main page using a URL to the web server on your development system? the url should be similar to - http://localhost/your_main_file.php NOT something like file:///C:/xampp/htdocs/your_main_file.php, which is a file system path and doesn't cause the php code to be executed.

 

Link to comment
Share on other sites

Hi Mac

I am running it on my host server, so don't need URL!

I Have been looking at your code an d I have a couple of queries!

I have been working on the assumption that the form code had to be on a separate file and it post it to that php file which is stated in the form header?

Is this a different way of doing this using PDO?

Also, you have a comment saying html document here!

Is this where I would put any page header code?

 

Link to comment
Share on other sites

Hi Mac

Trying to use your code, but having problems with posting multiple values!

I believe this was a mistake in your code:

try { // a 'local' try/catch to handle a specific error type 
			$stmt->execute([			//<<Whats this [ for?
				$post['fname'],
				]);					//<<Here!
		} catch (PDOException $e) {
			if($e->errorInfo[1] == 1062) // duplicate key error number
			{
				$errors['email'] = "Email is already in use";
			} else { 
				throw $e; // re-throw the pdoexception if not handled by this logic 

I altered it to post 2 values:

try { // a 'local' try/catch to handle a specific error type 
			$stmt->execute(array($post(['fname'],['lname']))
				
		} catch (PDOException $e) {
			if($e->errorInfo[1] == 1062) // duplicate key error number
			{
				$errors['email'] = "Email is already in use";
			} else { 
				throw $e; // re-throw the pdoexception if not handled by this logic 
			}
		}
	
        }

But I get an error:

Quote


Parse error: syntax error, unexpected '}', expecting ')' in /homepages/30/d593365489/htdocs/MFC1066/Mac1.php on line 50

I probably got this code wrong as I am  not sure of the correct syntax for posting multiple $POST's.

Can you show me the correct syntax for this example and how in the future I can add all my form fields into this code.

Link to comment
Share on other sites

the ->execute() method call accepts an array of values that correspond to the ? place-holders in the sql query. The [ and ] you are asking about are php's array definition syntax. the single $post['fname'] variable is a single value/element within that array.

to supply more than one value, you supply more than one variable within that array. if $post['fname'] is one variable and $post['lname'] is another variable, wouldn't that look like [ $post['fname'], $post['lname'] ]

 

 

 

Link to comment
Share on other sites

Hi Mac

 

Tried your line with square brackets around the execute: $stmt->execute[ $post['fname'], $post['lname']]

but still gives an error: Parse error: syntax error, unexpected ',', expecting ']' in /homepages/30/d593365489/htdocs/MFC1066/Mac1.php on line 48

But surely it's got to have a comma and and an opening square bracket?

Here's the complete file:

<?php

// initialization
session_start();

// why not have the connection code actually make the connection too, so that you don't need another line of code?
require "conn/connect_seniorform.php";
// note: this code uses the much simpler and more modern PDO database extension
// when you make the connection -
// set the character set to match your database tables, so that no character conversion occurs over the connection 
// set the error mode to use exceptions, so that all the database statements will use exceptions (this is the default now in php8, but set it anyways)
// set emulated prepared queries to false, you want to run real prepared queries
// set the default fetch mode to assoc, so that you don't need to specify it in each fetch statement

$post = []; // array to hold a trimmed working copy of the form data
$errors = []; // array to hold user/validation errors

// post method form processing
if($_SERVER["REQUEST_METHOD"]==="POST")
{
	// inputs: first_name (add others once code is working)
	
	// trim all the input data at once
	$post = array_map('trim',$_POST); // if any input is an array, use a recursive trim call-back function here instead of php's trim
	
	// validate all inputs
	// first name
	if($post['fname'] === '')
	{
		$errors['fname'] = "First Name is required";
	}
	
        if($post['lname'] === '')
	{
		$errors['lname'] = "Last Name is required";
	}
	// validate other inputs here...
	
	// if no errors, use the input data
	if(empty($errors))
	{
		$sql = "INSERT INTO senior_dat (fname), (lname) VALUES (?,?)";
		$stmt = $pdo->prepare($sql);

		// note: the following try/catch error handling deals with having a (single) unique column (email) defined in your database table
		// if you have multiple unique columns defined, you would execute a SELECT query inside the catch code to find which column(s) contain duplicate values matching the input data and setup an error message for each one
		try { // a 'local' try/catch to handle a specific error type 
			$stmt->execute[ $post['fname'], $post['lname']]
				
		} catch (PDOException $e) {
			if($e->errorInfo[1] == 1062) // duplicate key error number
			{
				$errors['email'] = "Email is already in use";
			} else { 
				throw $e; // re-throw the pdoexception if not handled by this logic 
			}
		}
	
        }
	// if no errors, success
	if(empty($errors))
	{
		$_SESSION['success_message'] = "Form saved OK";
		die(header("Refresh:0"));
	}
}

// hrml document starts here...
?>

<?php
// display and clear any success message
if(!empty($_SESSION['success_message']))
{
	echo "<p>{$_SESSION['success_message']}</p>";
	unset($_SESSION['success_message']);
}
?>

<h1>SENIOR RENEWAL FORM</h1>
<?php
// display any errors
if(!empty($errors))
{
	echo '<p>'; echo implode('<br>',$errors); echo '</p>';
}
?>
<form method="post">
<label><b>First Name:</b><br><input type="text" name="first_name" size="20" maxlength="40" value="<?=htmlentities($post['first_name']??'',ENT_QUOTES)?>"></label>
<br>
<label><b>Last Name:</b><br><input type="text" name="first_name" size="20" maxlength="40" value="<?=htmlentities($post['first_name']??'',ENT_QUOTES)?>"></label>
<br>
<input type="submit" value="submit">
</form>

Any suggestions?

Link to comment
Share on other sites

13 minutes ago, rocky48 said:

Any suggestions?

the ->execute() syntax is a method/function call. the () are part of that syntax. it takes an array as the call-time parameter. 

the example code i posted only needed to have each additional field added to the validation logic, the sql query, and the array of parameters in the ->execute() call. this is a simple A-B pattern matching exercise.

 

Link to comment
Share on other sites

Managed to figure that out, but have another problem!

 Parse error: syntax error, unexpected end of file in C:\wamp64\www

Im know that this can be un-equal curly brackets, but they look OK.

On the web it said that it can be an unclosed php code.

Looking at the code, you have <? but within quotes? Is the error check mistaking them for php code terminator?

Quote

<label><b>First Name:</b><br><input type="text" name="first_name" size="20" maxlength="40" value="<?=htmlentities($post['fname']??'',ENT_QUOTES)?>"></label>

Here is the file:

<?php

// initialization
session_start();
error_reporting(E_ALL);
ini_set('display_errors','1');
// why not have the connection code actually make the connection too, so that you don't need another line of code?
require "conn/connect_seniorform.php";
// note: this code uses the much simpler and more modern PDO database extension
// when you make the connection -
// set the character set to match your database tables, so that no character conversion occurs over the connection 
// set the error mode to use exceptions, so that all the database statements will use exceptions (this is the default now in php8, but set it anyways)
// set emulated prepared queries to false, you want to run real prepared queries
// set the default fetch mode to assoc, so that you don't need to specify it in each fetch statement

$post = []; // array to hold a trimmed working copy of the form data
$errors = []; // array to hold user/validation errors

// post method form processing
$status="";
if($_SERVER["REQUEST_METHOD"]=="POST"){
    $fname=$POST['fname'];
    $lname=$POST['lname'];
    $email=$POST['email'];
    if(empty($fname)|| empty($lname)|| $email){
        $status="All fields are compulsory.";
    }else{
        if(strlen($fname)>= 255 || !preg_match("/^[a-zA-Z-'\s+$/", $fname)){
            $status="Please enter a valid name";
        }else{ if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
            $status="Please Enter a valid email";
        }else{   
            $sql="INSERT INTO senior_dat(fname,lname) VALUES (:fname, :lname)";
            $stmt=$pdo->prepare($sql);
            $stmt->execute(['fname'=>$fname], ['lname'=>$lname]);
            $status="Your entrys have been accepted";
            $fname="";
            $email="";
            
        }
        }  
   }    
// hrml document starts here...
?>
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="generator" content="RSD 5.0.3519">
  <title>Senior Form</title>
  <link rel="stylesheet" href="css/bootstrap4.min.css">
  <link rel="stylesheet" href="css/wireframe-theme.min.css">
  <script>document.createElement( "picture" );</script>
  <script class="picturefill" async="async" src="js/picturefill.min.js"></script>
  <link rel="stylesheet" href="css/main.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Averia+Sans+Libre:400,b%7CRoboto:400,900,b">
</head>

<body class="body-3"><div class="responsive-picture picture-1 align-content-md-center">
    <picture>
      <img alt="Placeholder Picture" width="1200" height="300" src="./images/1066MFC%20Banner.jpg" loading="lazy">
    </picture>
  </div>
  <nav class="container-grid navbar navbar-expand-lg navbar-dark bg-dark">
    <h3 class="navbar-brand">MENU</h3><button type="button" class="btn navbar-toggler navbar-toggler-icon button Dropdown-toggle" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-label="Toggle navigation"></button>
    <div class="container-grid collapse navbar-collapse" id="navbarNavDropdown">
      <ul class="list-container navbar-nav">
        <li class="list-item-container nav-item">
          <a class="link-text nav-link" href="index.html" title="">HOME</a>
        </li>
        <li class="list-item-container nav-item">
          <a class="link-text nav-link" href="about.html" title="">ABOUT</a>
        </li>
        <li class="list-item-container nav-item dropdown">
          <a class="link-text nav-link dropdown-toggle" href="members.html#navbarNavDropdown" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">MEMBERS</a>
          <div class="container-grid dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
            <a class="link-text dropdown-item" href="members.html" title="">Members</a>
            <a class="link-text dropdown-item" href="aerodrome.html" title="PEBSHAM AERODROME">Pebsham Aerodrome</a>
            <a class="link-text dropdown-item" href="emergency%20numbers.html">Emergency Numbers</a>
          </div>
        </li>
        <li class="list-item-container nav-item">
          <a class="link-text nav-link" href="newmem.html" title="New-Member">NEW MEMBER</a>
        </li>
        <li class="list-item-container nav-item">
          <a class="link-text nav-link" href="contact.html" title="">CONTACT</a>
        </li>
      </ul>
      <a class="link-text text-link-4" href="https://1066modelflying.club/coppermine/index.php" title="Gallery">GALLERY</a>
    </div>
  </nav>
 
<?php
// display and clear any success message
if(!empty($_SESSION['success_message']))
{
	echo "<p>{$_SESSION['success_message']}</p>";
	unset($_SESSION['success_message']);
}
?>

<h1>SENIOR RENEWAL FORM</h1>
<?php
// display any errors
if(!empty($errors))
{
	echo '<p>'; echo implode('<br>',$errors); echo '</p>';
}
?>
<form method="post">
<label><b>First Name:</b><br><input type="text" name="first_name" size="20" maxlength="40" value="<?=htmlentities($post['fname']??'',ENT_QUOTES)?>"></label>
<br>
<label><b>Last Name:</b><br><input type="text" name="first_name" size="20" maxlength="40" value="<?=htmlentities($post['lname']??'',ENT_QUOTES)?>"></label>
<br>
<label><b>email:</b><br><input type="text" name="first_name" size="20" maxlength="40" value="<?=htmlentities($post['email']??'',ENT_QUOTES)?>"></label>    
<br>
<input type="submit" value="submit">
</form>
</body>
</html>

 

Link to comment
Share on other sites

if($_SERVER["REQUEST_METHOD"]=="POST"){

The above is your problem.  It would look better like this:

if($_SERVER["REQUEST_METHOD"]=="POST")
{

Once again this is something you s/b able to locate for yourself.

IMO, putting the braces on their own lines helps to make it clear where the open and close ones are as well as make it clear where the indented code begins and ends.  If you indent, that is.

Do you have an intelligent editor that highlights different types of text such as php, html, and plain text?  That's how I located it for you.

I think you are missing an 'empty' as well.

Edited by ginerjm
Link to comment
Share on other sites

I am 74 years old and now struggle with programming and not that experienced.

I did a lot of programming over 10 years ago, but my memory is not so good.

I use Komodo Edit which does help to format as i type.

Please don't use abbreviations, I worked out what s/b was, but what does IMO and OP stand for?

You may say why am I trying to struggle with programming, but it keeps my brain cells working!

Don't forget you may be in the same position one day!

Link to comment
Share on other sites

Komodo does highlight braces!

I believe that the problem is in the code between lines 21 to 43.

The first opening curly brace (Ln22)does not have a closing curly brace!

The curly brace on line 28 highlights the closing curly brace on line 43. That seems wrong to me! Should it be an elseif?

Also on line 31 the closing brace is on line 42, which to me seems wrong.

With so many else statements I am very confused as to where the braces should go!

The line numbers are based on the copy of the file I last posted.

Could you help me get the braces in the right place?

Link to comment
Share on other sites

Here's my entry for this competition...

$status="";
if($_SERVER["REQUEST_METHOD"]=="POST") {
    $fname=$POST['fname'];
    $lname=$POST['lname'];
    $email=$POST['email'];
    if(empty($fname)|| empty($lname)|| $email){
        $status="All fields are compulsory.";
    }elseif(strlen($fname)>= 255 || !preg_match("/^[a-zA-Z-'\s+$/", $fname)){
        $status="Please enter a valid name";
    }elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        $status="Please Enter a valid email";
    }else{   
        $sql="INSERT INTO senior_dat(fname,lname) VALUES (:fname, :lname)";
        $stmt=$pdo->prepare($sql);
        $stmt->execute(['fname'=>$fname], ['lname'=>$lname]);
        $status="Your entrys have been accepted";
        $fname="";
        $email="";
        
    }
}    

BTW, what's the prize?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.