Need a little help mixing SQL and php

Hi, I have a form that I’m just about done with, but I don’t know how to put PHp in a value tag that already ave SQL statements in it . First, I got a sticky form to work on a much smaller scale. I followed an example on https://www.youtube.com/watch?v=4Df0l9J-2i0 and I’m attaching the end result of the video. She explained things as she went and as can be noted, I made comments in the code to help me understand. After I was successful with that example, I took what I
understood from the video and tried to applied it to the form and I focused just on the fname variable for now. The thing that messing me up is since there is already SQL statements in the value tag, I’m not sure how to proceed. I’m now getting a Parse error: syntax error,
unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE
or T_NUM_STRING in /web/html/mediaservicesunlimited.com/contactUs.php on
line 86
error message

This is just one part of PHP that I really struggle with. Also, I realize most programmer are cringing because I’m mixing HTML and PHP. I apologize for that and I do understand why it is important to separate them now, but with this form it 's hard for me to understand
how to separate them.

if someone wouldn’t mind helping me understand how to make fname field to stick, I’m pretty sure I can finish the rest of the form. I’m not a strong programmer as anyone can tell, but if I could get help with this last part, I would be really appreciative.

sticky code sample

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sticky Validation</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>    
<body>
<h2>A Simple Form for Sticky Validation</h2>
    <?php
    $nameError = "";
    $emailError = "";
    
    if($_SERVER['REQUEST_METHOD'] == 'POST'){
        validateStuff(); 
    }
    else {
        showForm($nameError, $emailError, $name, $Email); //add form variables 
    }
function validateStuff() {
        //get variables from form submission
        $name = $_POST['name'];
        $email = $_POST['email'];
                    
        if(empty($name)){
            $name = NULL; //change variable names for real form 
            $nameError = "<p>Please enter your first name.</p>";
        }
        if(empty($email)){
            $email = NULL;
            $emailError = "<p>Please enter your email address.</p>";
        }                    
        if(!($name && $email)){
            showForm($nameError, $emailError, $name, $email);    //Add variables 
        }
        if($name && $email ){
        //display an output message to user
        print "Thanks for signing up for our mailing list <b> $name.</b>";
        print "<p>We will send our newsletter to you at <b>$email</b>.</p>";
        }
} //end .of validate function 
function showForm($nameError, $emailError, $name, $email) { //add form variables 
echo <<< FORM
<form method="post" action="">
    <div>
    <label for="name">*Name:</label>
    <input name="name" type="text" id="name" placeholder="name" value = $name>
    $nameError
    </div>
    
    <div class="clear">
    <label for="email">*What is your email address?</label>
    <input name="email" type="email" id="email" placeholder="email" value = $email >
    $emailError
    </div>
    
    <div class="clear">
    <input type="submit" value="Sign Up" name="submit" />
    </div>
</form>
FORM;
}
    ?>    
    </body>
</html>

my contact page

<?php
//ini_set('display_errors', 'On');
//error_reporting(E_ALL);
require_once('functions.php');
function outputErrors($sql_errors)
{
 foreach($sql_errors as $name => $msgs)
 {
  echo('<h4 class="error">' . $name . ': ' . $msgs . '</h4>' . PHP_EOL);
 }
}

if(isset($_POST['submit']))
{
    if(isset($_POST['projectOptions'])) 
        {
            $strprojectOptions = implode(",", $_POST['projectOptions']);
        }
        else {
            $strprojectOptions = "";
        }
        //echo "interested in " . $strprojectOptions;
        //exit();  //after testing remove  these 2 lines
    }
 $sql_errors = array();
 $mysqli = databaseConnection();
 if(!$stmt = $mysqli->prepare("INSERT INTO clients(fname, lname, orgName, address, city, state, zipcode, phone, fax, email, confirmEmail, projectOptions, projectOverview, year) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"))
 {
  $sql_errors["Prepare"] = $mysqli->error . PHP_EOL;
 }
 else
 {
  if(!$stmt->bind_param('ssssssiiissisi', $_POST["fname"], $_POST["lname"], $_POST["orgName"], $_POST["address"], $_POST["city"], $_POST["state"], $_POST["zipcode"], $_POST["phone"], $_POST["fax"], $_POST["email"], $_POST["confirmEmail"], $_POST["projectOptions"], $_POST["projectOverview"], $_POST["year"]))
  {
   $sql_errors["bind_param"] = $stmt->error . PHP_EOL;
  }
  else
   {
   if(!$stmt->execute())
   {
    $sql_errors["execute"] = $stmt->error . PHP_EOL;
   }
   $stmt->close();
  }
 }
 $mysqli->close();
 header('contactTest.php');

?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style type="text/css">
 .error
 {
  color: #FF0000;
 }
</style>
</head>
<body>
    <?php
    $fname = "";  //start user's input validation 
    if($_SERVER['REQUEST_METHOD'] == 'POST'){
        validateStuff(); 
    }
    else {
        showForm($fname); //add form variables 
    }
function validateStuff() {
        //get variables from form submission
        $fname = $_POST['fname'];
        if(empty($fname)){
            $fname = NULL; //change variable names for real form 
            $nameError = "<p>Please enter your first name.</p>";
        }
} //end of user's validation function 
?>
 <?php if(isset($sql_errors) && sizeof($sql_errors) > 0) outputErrors($sql_errors);?>
 <?php
 function showForm($fname, $nameError) {  //Add form variables 
 echo <<<FORM
 <form action="contactUs.php" method="post">
  <label>
   <input id="fname" type="text" name="fname" size="15" placeholder="First Name" value ="<?php echo isset($_POST['fname']) ? $_POST['fname'] : '';?>" >
   <input type="text" name="lname" size="20" placeholder="Last Name"><?php echo !empty($error['lname']) ? $error['lname'] : '';?>
   <input type="text" name="orgName" placeholder="Organization's Name"maxlength="50">
  </label><br />
  <label> <!--new row -->
   <input id="address" type="text" name="address" size="15" placeholder="Street Addresss" maxlength="50">
   <input id="city" type="text" name="city" placeholder="City" size="10" maxlength="25">
   <select id="state" name="state" placeholder="State" value="">
    <option value ="">Please choose a state</option>
    <?php states($state); ?>
   </select>
   <input id = "zipcode" type="number" name="zipcode" placeholder="Zip Code" size="5" maxlength="5">
  </label><br />
  <label> <!--new row -->
   <input type="text" name="phone" placeholder="Phone Number:(including area code)" size="10" maxlength="10">
   <input type="text" name="fax" size="10" placeholder="Fax Number: (including area code)" maxlength="10">
  </label><br />
  <label> <!--new row-->
   <input type="text" id = "email" name="email" placeholder="Email Address" />
   <input type="text" id = "confirmEmail" name="confirmEmail" placeholder="Confirm Email Address" />
  </label><br />
  <label> <!--new row -->
   What would you like help with?
   <table id="projectOptions">
    <tr span=2>
     <td><input type="checkbox" name="projectOptions[]" id="projectOptions[]" value="socialMedia">Social Media</td>
     <td><input type="checkbox" name="projectOptions[]" id="projectOptions[]" value="webContent">Web Content Management</td>
    </tr>
    <tr>
     <td><input name="projectOptions[]" type="checkbox" checked="checked" id="projectOptions[]" value="marketingMaterial">Marketing Material Creation</td>
     <td><input type="checkbox" name="projectOptions[]" id="projectOptions[]" value="seo">SEO (Search Engine Optimization)</td>
    </tr>
    <tr>
     <td><input type="checkbox" name="projectOptions[]" id="projectOptions[]" value="videoEditing"> Video Editing</td>
     <td><input type="checkbox" name="projectOptions[]" id="projectOptions[]" value="webDesign">Web Design</td>
    </tr>
   </table>
  </label>
  Overview about the project:<textarea rows="5" cols="10" placeholder="Overview of Project"></textarea><br />
  If you are not a robot, what year is it? <input type="text" name="year" size="4" maxlength="4"><br />
  <input type="submit" name="submit" value="Contact Me!">
  <input type="reset" name="reset" value="Cancel">
 </form>
FORM;
}
?>
</body>
</html>

I think the problem is that you’re trying to execute php code within a heredoc string. You can expect it to output variable values, but from what I have read (zero personal experience, unfortunately) you can’t execute code such as echo. Hence this section:

echo <<<FORM
 <form action="contactUs.php" method="post">
  <label>
   <input id="fname" type="text" name="fname" size="15" placeholder="First Name" value ="<?php echo isset($_POST['fname']) ? $_POST['fname'] : '';?>" >

is going to be a problem. What you could do is create a separate variable, call it $fname, and evaluate it prior to the heredoc separators:

$fname = isset($_POST['fname']? $_POST['fname'] : '');
echo <<<FORM
 <form action="contactUs.php" method="post">
  <label>
   <input id="fname" type="text" name="fname" size="15" placeholder="First Name" value ="$fname" >

There do seem to be other ways to get around the issue, if indeed this is the issue.

There’s more problems with your code then just line 86.

  • if(isset($_POST['submit'])) should be replaced with if($_SERVER['REQUEST_METHOD'] == 'POST']). You do have it, but it’s not being used properly.
  • The lines that read

If you are not a robot, what year is it?

Will fail because spam bots WILL submit everything on the page including that text field you want them to type in. If you want spam protection, use honeypot.

  • The HEREDOCs are weird, you might as well just end PHP tags before your HTML stuff and start the PHP tag again once your HTML stuff ends.
  • You are printing the MySQLi error message to the user which should never be done.
  • You should sanitize all your user inputs (I am actually impressed that you are using prepared statements).

this means the escape characters end up in the database. not sure if that’s a good idea.

1 Like

I made some of the suggested changes but I’m getting this error message.

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /web/html/mediaservicesunlimited.com/contactUs.php on line 84

<?php
//ini_set('display_errors', 'On');
//error_reporting(E_ALL);
require_once('functions.php');
function outputErrors($sql_errors)
{
 foreach($sql_errors as $name => $msgs)
 {
  echo('<h4 class="error">' . $name . ': ' . $msgs . '</h4>' . PHP_EOL);
 }
}

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if(isset($_POST['projectOptions'])) 
        {
            $strprojectOptions = implode(",", $_POST['projectOptions']);
        }
        else {
            $strprojectOptions = "";
        }
        //echo "interested in " . $strprojectOptions;
        //exit();  //after testing remove  these 2 lines
    }
 $sql_errors = array();
 $mysqli = databaseConnection();
 if(!$stmt = $mysqli->prepare("INSERT INTO clients(fname, lname, orgName, address, city, state, zipcode, phone, fax, email, confirmEmail, projectOptions, projectOverview, year) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"))
 {
  $sql_errors["Prepare"] = $mysqli->error . PHP_EOL;
 }
 else
 {
  if(!$stmt->bind_param('ssssssiiissisi', $_POST["fname"], $_POST["lname"], $_POST["orgName"], $_POST["address"], $_POST["city"], $_POST["state"], $_POST["zipcode"], $_POST["phone"], $_POST["fax"], $_POST["email"], $_POST["confirmEmail"], $_POST["projectOptions"], $_POST["projectOverview"], $_POST["year"]))
  {
   $sql_errors["bind_param"] = $stmt->error . PHP_EOL;
  }
  else
   {
   if(!$stmt->execute())
   {
    $sql_errors["execute"] = $stmt->error . PHP_EOL;
   }
   $stmt->close();
  }
 }
 $mysqli->close();
 header('contactTest.php');

?>

Which of those is line 84? As far as I know a parsing error will mean that your code doesn’t execute - the entire file is parsed to check for unbalanced brackets, quotes and other issues prior to even trying to run anything.

line 84 is

this is strange. It doesn’t want to display that line of code. Line 84 is the beginning form tag
form action = “contactUs.php… .”

Hmm, then what do you propose?

You don’t need to escape anything you are writing to a database when you use prepare statements.

Escaping is only for when data and code are in the same statement and using a prepare statement keeps them completely separate.

What if you don’t want HTML entities in the database and would rather have them escaped and output to the screen via its HTML name? So instead of having

<html>

You would have

&lt;html&gt;

This would eliminate the possibility of a user attempting to re-design your webpage like such.

<style type="text/css">
*, html, body {
    display: none;
}
</style>

Or even

<style type="text/css">
.site-header {
    display: none;
}

.site-content {
    content: "My own content that I put in here because I can.";
}
</style>

I mean you could escape on input and then escape again on output and use strtr to convert the messy double escape back to its HTML name. I mean it would be redundant, but just a thought.

You do that escape when writing to HTML. If you were going to output from the database to PDF or Word or whatever then an HTML escape would be meaningless. With a PDF or Word doc <html> would just be a part of the text that should be displayed as entered (or stripped out depending on what you actually want when producing the output)
.
Even if you are storing HTML in the database that will only ever be written as HTML you save 6 characters per tag by not escaping the data until you need to.

You always escape LAST with the escape being appropriate to the use.

1 Like

Then what is the point of saying this

You don’t escape input - you validate or sanitize input. (Source Trying to understand php code - #26 by felgall)

When you sanitize, it also escapes characters. So what is the point of saying sanitize when you should just validate?

No it doesn’t. Sanitizing just removes invalid characters - it does not escape anything.

What character sanitizing removes depends on what characters are considered valid so ’ and < might be valid characters and be left completely untouched by sanitizing.

Anyway if sanitizing were to include escaping then which of the millions of different types of escaping would it include? Each different output where code and data are jumbled together requires a DIFFERENT ESCAPE.

Then it doesn’t make any sense when I say

You should sanitize all your user inputs (I am actually impressed that you are using prepared statements).

And then Dormilich says

this means the escape characters end up in the database. not sure if that’s a good idea.

And then you liked that comment and say

No it doesn’t. Sanitizing just removes invalid characters - it does not escape anything.

What character sanitizing removes depends on what characters are considered valid so ’ and < might be valid characters and be left completely untouched by sanitizing.

Anyway if sanitizing were to include escaping then which of the
millions of different types of escaping would it include? Each different
output where code and data are jumbled together requires a DIFFERENT
ESCAPE.

It doesn’t make sense if you say one thing and do a totally different thing. It’s either you validate or sanitize or you don’t do it at all. You can’t say “sanitize user input” and when someone says “sanitize user input” too and then you go and say “you don’t escape user input”. That doesn’t make any lick of sense at all if the other person said the same exact thing you said. It’s like you’re going against your words and at the same time trying to defend your own words. That just doesn’t make any sense.

Using prepare statements means that any escapes end up in the database as using prepare statements means that they don’t get treated as escape characters as no escapes are needed.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.