Jump to content
  • Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
FoxfireTX

Need Help getting form data to insert in table with php

Recommended Posts

I am new to php and am having a real problem getting it to write to SQL tables from form input.  I finally managed to get a 3 column test form to insert the data into a test table, so moved on to the next test of inserting a 10 column form that includes 4 check boxes following the script of the one I got to insert.  But I cannot get it to insert the data.  I also have the problem that my localhost is running php 7.1 while the SQL side of the server is using php 5.6, thus the many single quotes versus double quotes or no quotes.  With the first test script, I debugged line by line, and figured out if I get a bunch of warnings in netbeans and my local server but no red flags it most likely will work on the server.  But this script has me at a loss.  I have stripped out anything superfluous such as the thank you html, the email send portion, and debugged it line by line with the server.  The connection is good, it takes a second as if it is inserting, I get zero warnings or errors at this point,  but in the end it has not inserted the data into the table.  I have checked and rechecked the database name, table name, columns etc and nothing.  I appreciate any ideas and help from anyone here.  Thanks so much!

This is the form portion of the html:

                  <form class="contact-form" role="form" action="volunteers2remote.php" method="post"  onsubmit="document.getElementById('updatesButton').disabled=true;

                        document.getElementById('updatesButton').value='Submitting, please wait...';">
                        <div class="form-group">
                            <label for="firstname" class="hidden">First Name</label>
                            <input type="text" class="form-control" name="firstname" id="firstname" value="" required="required" placeholder="First Name">
                        </div>
                        <div class="form-group">
                            <label for="lastname" class="hidden">Last Name</label>
                            <input type="text" class="form-control" id="lastname" name="lastname" value="" required="required" placeholder="Last Name">
                        </div>
                        <div class="form-group">
                            <label for="email" class="hidden">Email</label>
                            <input type="email" class="form-control" id="email" name="email" value="" required="required" placeholder="Email">
                        </div>
                        <div class="form-group">
                            <label for="zip" class="hidden">ZIP</label>
                            <input type="text" class="form-control field-half-width" id="zip" name="zip" placeholder="ZIP">
                        </div>
                        <div class="form-group">
                            <label for="phone" class="hidden">Phone</label>
                            <input type="text" class="form-control field-half-width" id="phone" name="phone" value="" required="required" placeholder="Phone">
                        </div>
                        <div class="form-inline">
                            I will: (uncheck those which you prefer not to do)<br>
                        
                            <input type="checkbox" name="house_party" class="cbox" id="house_party" placeholder="House Party" value="yes" checked><label for="party" type="text" class="special">Host a house party</label>
                                
                            <input type="checkbox" name="canvass" class="cbox" id="canvass" placeholder="Canvass" value="yes" checked><label for="canvass" type="text" class="special">Knock on doors</label><br>
                            
                        
                            <input type="checkbox" name="phonebank" class="cbox" id="phonebank" placeholder="Phonebank" value="yes" checked><label for="phonebank" class="special">Make phone calls</label>
                            
                        
                            <input type="checkbox" name="anything" value="anything" class="cbox" id="any" placeholder="Anything" value="yes" checked><label for="any" class="special">Help with anything you need</label>
                            
                        </div>
                        <div class="form-group">
                            <label for="comments" class="hidden">Comments</label>
                            <textarea name="comments" id="comments" class="form-control" rows="5" placeholder="Comments"></textarea>
                        </div>
                           <button type="submit" class="btn btn-default" value="Send" id="sendButton">Send</button>
                        </form> <!-- volunteer-form -->

This is the stripped down php:        

<?php ini_set('display_errors', '1'); ?>
<?php

deleted connection info

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if (!$link) {
    die('Could not connect to database: ' . mysqli_error());
}

// define variables
$firstname = $_POST[firstname];
$lastname = $_POST[lastname];
$email= $_POST;
$zip= $_POST[zip];
$phone= $_POST[phone];
$house_party= $_POST[house_party];
$canvass= $_POST[canvass];
$phonebank= $_POST[phonebank];
$anything= $_POST[anything];
$comments= $_POST[comments];


if ($_SERVER[REQUEST_METHOD] == 'POST')
  if (empty($_POST[firstname])) {
    $nameErr = 'First name is required';
  } else {
    $firstname = test_input($_POST[firstname]);
  }
      // check if name only contains letters and whitespace
    if (!preg_match('/^[a-zA-Z ]*$/',$firstname)) {
      $firstnameErr = 'Only letters and white space allowed';
    }
 
 
  if ($_SERVER[REQUEST_METHOD] == 'POST')
  if (empty($_POST[lastname])) {
    $nameErr = 'Last name is required';
  } else {
    $lastname = test_input($_POST[lastname]);
  }    
   // check if name only contains letters and whitespace
    if (!preg_match('/^[a-zA-Z ]*$/',$lastname)) {
      $lastnameErr = 'Only letters and white space allowed';
    }
 
  if ($_SERVER[REQUEST_METHOD] == 'POST')
  if (empty($_POST)) {    
    $emailErr = 'Email is required';
  } else {
    $email = test_input($_POST);
  }
  // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = 'Invalid email format';
    }
 
 
/* Check all form inputs using  test_input function */  
if ($_SERVER[REQUEST_METHOD] == 'POST') {
  $firstname =  test_input($_POST[firstname]);
  $lastname =  test_input($_POST[lastname]);
  $email    =  test_input($_POST);
  $phone  =  test_input($_POST[phone]);
  $comments  = test_input($_POST[comments]);
}
 
if (isset($_POST['myCheckbox'])) {
  $checkBoxValue = "yes";
} else {
  $checkBoxValue = "no";
}


if(!empty($_POST['check'])) {
    foreach($_POST['check'] as $value) {
        $check_msg .= "Checked:".$value."\n";            
    }
}


if (isset($_POST[house_party])) {
  $anything = 'yes';
} else {
  $anything = 'no';
}
 
if (isset($_POST[canvass])) {
  $canvass = 'yes';
} else {
  $canvass = 'no';
}

if (isset($_POST[phonebank])) {
  $anything = 'yes';
} else {
  $anything = 'no';
}

if (isset($_POST[anything])) {
  $anything = 'yes';
} else {
  $anything = 'no';
}
$check = isset($_POST[check]) ? $_POST[check] : '';

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

//inserting data into database
if (isset($_POST[firstname], $_POST[lastname], $_POST, $_POST[zip], $_POST[phone], $_POST[house_party], $_POST[canvass], $_POST[phonebank], $_POST[anything], $_POST[comments])){
     if ($stmt = $link->prepare('INSERT INTO `volunteerstest`(`firstname`, `lastname`, `email`, `zip`, `phone`, `house_party`, `canvass`, `phonebank`, `anything`, `comments`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')) {
    $stmt->bind_param('ssssssssss', $_POST[firstname], $_POST[lastname], $_POST, $_POST[zip], $_POST[phone], $_POST[house_party], $_POST[canvass], $_POST[phonebank], $_POST[anything], $_POST[comments]);
        if (!$stmt->execute()) {
            error_log('Execute failed '.$stmt->error);
        } else {
            echo 'Data successfully inserted! firstname '.$_POST[firstname].' lastname '.$_POST[lastname].' email '.$_POST.' ZIP '.$_POST[zip].' phone '.$_POST[phone].' house_party '.$_POST[house_party].' canvass '.$_POST[canvass].' phonebank '.$_POST[phonebank].' anything '.$_POST[anything].' and comments '.$_POST[comments].'';
        }
        $stmt->close();
   } else {
        echo "data insertion failed";
    }
}
    


 
?>

 

 

Share this post


Link to post
Share on other sites

 if I get a bunch of warnings in netbeans and my local server but no red flags it most likely will work on the server. 

Warnings like what?  You shouldn't have code that has a bunch of notices or warnings.  There aren't a ton of incompatible changes between PHP 5 and 7.  There are some, but not a lot.  I'm not aware of any changes at all regarding string syntax, I don't know what you're saying with the quotes.

Your code is hard to read when you don't put it in a code box, but I can tell you're not using quotes for any array index, that should result in a notice on every line you do that.  You're also not checking for errors in every step of the database process.  Is there anything in your error log?

Share this post


Link to post
Share on other sites

The warnings in netbeans relate to filtering and not accessing Global array directly.  None of what it is happening when I upload to the server makes sense to me.  I can run the code on the website portion of the server and it runs correctly without warnings.  But when I try to insert data into a table on the SQL side, I get all kinds of warnings about single versus double quotes, etc.  As I noted, I debugged the first test line by line on the server itself to finally get it to insert the data.  This is the code that IS inserting data on the server now.  It was clean on my localhost and netbeans when I first uploaded to the server, but I got a page of warnings on the server, which I debugged line by line to get here which now runs clean and actually inserts the data to a table.  It's gotten to the point that I name them remote for the server and local for those I'm running on my local host. Where and how do I access an error log?  I really appreciate any help with this. 

 

<?php ini_set('display_errors', '1'); ?> 
<?php

define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASS', '');
define('DB_HOST', 'localhost');	

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if (!$link) {
    die('Could not connect to database: ' . mysqli_error());
}



// define variables 
$name = $_POST[name];
  $email= $_POST[email];
	 $phone= $_POST[phone];
	 


if ($_SERVER[REQUEST_METHOD] == 'POST') 
  if (empty($_POST[name])) {
    $nameErr = 'Name is required';
  } else {
    $name = test_input($_POST[name]); 
  }
  // check if name only contains letters and whitespace
    if ((!preg_match('/^[a-zA-Z ]*$/',$name))){
      $nameErr = 'Only letters and white space allowed';
    }
  
 
 if ($_SERVER[REQUEST_METHOD] == 'POST') 
  if (empty($_POST[email])) {
    $emailErr = 'Email is required';
  } else {
    $email = test_input($_POST[email]); 
  }
$email = test_input($_POST[email]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = 'Invalid email format';
}

if ($_SERVER[REQUEST_METHOD] == 'POST') {
  $name = test_input($_POST[name]);
  $email = test_input($_POST[email]);
  $phone = test_input($_POST[phone]);
  
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}	 

//inserting data into database
if (isset($_POST[name], $_POST[email], $_POST[phone])) {
     if ($stmt = $link->prepare('INSERT INTO `updatestest`(`name`, `email`, `phone`) VALUES (?, ?, ?)')) {
	$stmt->bind_param('sss', $_POST[name], $_POST[email], $_POST[phone]);
        if (!$stmt->execute()) {
            error_log('Execute failed '.$stmt->error);
        } else {
            echo 'Data successfully inserted! name '.$_POST[name].' email '.$_POST[email].' and phone '.$_POST[phone].'';
        }
        $stmt->close();
   } else {
        error_log('Prepare failed'.$link->error);
    }

}	
$>

As an experiment this morning, I added the send email code to the bottom of the volunteers2remote.php as follows:

/* message for the e-mail */

$to = 'me@att.net';
$subject = 'Volunteer from website';
$check = isset($_POST[check]) ? $_POST[check] : '';
$body = "First Name: ".$firstname ."\r\n". "Last Name: ".$lastname ."\r\n". "Email: ".$email ."\r\n". "Phone: ".$phone ."\r\n". "ZIP: ".$zip ."\r\n" . "Host a house party: ".$house_party . "\r\n" . "Canvass: ".$canvass . "\r\n" . "Phone Bank: ".$phonebank . "\r\n" . "Anything Needed: ".$anything . "\r\n" . "Comments: ".$comments ."\r\n";   


// Setup headers
$headers .= "Return-Path: " . $email;
/* Send the message using mail() function */
mail($to, $subject, $body, $headers);

I received the email just fine with all the info included, but got a blank screen in my browser, i.e., no error messages, and it it did not insert the data in the table.  So I then added the same exact email code to the bottom of the sample7remote.php above which IS inserting data and again got numerous warnings which I am still debugging, primarily syntax and T string errors:

Quote

Parse error: syntax error, unexpected 'mail' (T_STRING)

And again, I got rid of the errors by changing from double quotes around the to: definition to single quotes, etc.  Why the code works fine when it is not inserting into the database but throws error messages when it is inserting into the database is a mystery to me.  But this is the same way it worked throughout the code when I first uploaded the sample7remote to the server on Saturday.  After having it run clean through netbeans and my localhost I was stunned by a page of error messages.  At this point just trying to keep my sense humor about it:-)  Can't thank you enough for your help as I am just at a loss. 

Edited by FoxfireTX
Additional info: Now that I have figured out how to use the code box, if it would make it easier I am happy to repost the initial code in a code box.

Share this post


Link to post
Share on other sites

I should note further, we were under tight timelines initially to get the website up and running so I just used the send email function to capture the data in some way at this point.  I have a niece who works with SQL every day so she has since set up the database and tables, and now the goal is to get the data to insert into the database for future use so it doesn't have to be added manually.  Thanks!

Share this post


Link to post
Share on other sites

OK, so I went back, copied the INSERT INTO exactly from the one this working into a new doc, and went from the 10 columns of data to just the 4 required (firstname, lastname, email, phone) and adjusted the other things accordingly, but got this error message both on the server and on local host: " Parse error: syntax error, unexpected ',' in on line 124".  

So I then went back and stripped it down to three columns, firstname, email phone, and it inserted on my local host along with a page full of these messages, which I've come to expect to get it to write into the database on  the server:

  Warning: Use of undefined constant firstname - assumed 'firstname' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\volunteers3local.php on line 130 but on the server side if I do as the warning suggests it will not run further.  

WHY would adding a 4th factor send it into error mode with making the same adjustments to the rest of the INSERT code?

 

Share this post


Link to post
Share on other sites

With the $_POST[xxxxx] replace all xxxxx with single quotes 'xxxxx' so they become $_POST['xxxxx'], I've never done it like that! before and it seemed strange, but it does seem to work, but maybe newer php version are more stricter.

Share this post


Link to post
Share on other sites

This is the full code that will insert data:

<?php ini_set('display_errors', '1'); ?> 
<?php

// 1. Create connection to database
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASS', '');
define('DB_HOST', 'localhost');	

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if (!$link) {
    die('Could not connect to database: ' . mysqli_error());
}




// define variables 
$firstname = $_POST[firstname];
$lastname = $_POST[lastname];
$email= $_POST[email];
$zip= $_POST[zip];
$phone= $_POST[phone];
$house_party= $_POST[house_party];
$canvass= $_POST[canvass];
$phonebank= $_POST[phonebank];
$anything= $_POST[anything];
$comments= $_POST[comments];


if ($_SERVER[REQUEST_METHOD] == 'POST') 
  if (empty($_POST[firstname])) {
    $nameErr = 'First name is required';
  } else {
    $firstname = test_input($_POST[firstname]); 
  }
	  // check if name only contains letters and whitespace
    if (!preg_match('/^[a-zA-Z ]*$/',$firstname)) {
      $firstnameErr = 'Only letters and white space allowed';
    }
 
  
  if ($_SERVER[REQUEST_METHOD] == 'POST') 
  if (empty($_POST[lastname])) {
    $nameErr = 'Last name is required';
  } else {
    $lastname = test_input($_POST[lastname]); 
  }	
   // check if name only contains letters and whitespace
    if (!preg_match('/^[a-zA-Z ]*$/',$lastname)) {
      $lastnameErr = 'Only letters and white space allowed';
    }
  
  if ($_SERVER[REQUEST_METHOD] == 'POST')
  if (empty($_POST[email])) {    
    $emailErr = 'Email is required';
  } else {
    $email = test_input($_POST[email]); 
  }
  // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = 'Invalid email format';
    }
  
  
/* Check all form inputs using  test_input function */  
if ($_SERVER[REQUEST_METHOD] == 'POST') {
  $firstname =  test_input($_POST[firstname]);
  $lastname =  test_input($_POST[lastname]);
  $email    =  test_input($_POST[email]);
  $phone  =  test_input($_POST[phone]);
  $comments  = test_input($_POST[comments]);
}
  
if (isset($_POST['myCheckbox'])) {
  $checkBoxValue = "yes";
} else {
  $checkBoxValue = "no";
}


if(!empty($_POST['check'])) {
    foreach($_POST['check'] as $value) {
        $check_msg .= "Checked:".$value."\n";            
    }
}


if (isset($_POST[house_party])) {
  $anything = 'yes';
} else {
  $anything = 'no';
} 
  
if (isset($_POST[canvass])) {
  $canvass = 'yes';
} else {
  $canvass = 'no';
} 

if (isset($_POST[phonebank])) {
  $phonebank = 'yes';
} else {
  $phonebank = 'no';
} 

if (isset($_POST[anything])) {
  $anything = 'yes';
} else {
  $anything = 'no';
} 
$check = isset($_POST[check]) ? $_POST[check] : '';

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

//inserting data into database

if (isset($_POST[firstname], $_POST[email], $_POST[phone])) {
     if ($stmt = $link->prepare('INSERT INTO `volunteers`(`firstname`, `email`, `phone`) VALUES (?, ?, ?)')) {
	$stmt->bind_param('sss', $_POST[firstname], $_POST[email], $_POST[phone]);
        if (!$stmt->execute()) {
            error_log('Execute failed '.$stmt->error);
        } else {
            echo 'Data successfully inserted! first name '.$_POST[firstname].' email '.$_POST[email].' and phone '.$_POST[phone].'';
        }
        $stmt->close();
   } else {
        error_log('Prepare failed'.$link->error);
    }

}	
?>

But if I change the INSERT INTO to this  I get the page full of warnings and it will not insert the data:

//inserting data into database

if (isset($_POST[firstname], $_POST[lastname], $_POST[email], $_POST[phone])) {
     if ($stmt = $link->prepare('INSERT INTO `volunteers`(`firstname`, `lastname` `email`, `phone`) VALUES (?, ?, ?, ?)')) {
	$stmt->bind_param('ssss', $_POST[firstname], $_POST[lastname], $_POST[email], $_POST[phone]);
        if (!$stmt->execute()) {
            error_log('Execute failed '.$stmt->error);
        } else {
            echo 'Data successfully inserted! first name '.$_POST[firstname].' last name '.$_POST[lastname].' email '.$_POST[email].' and phone '.$_POST[phone].'';
        }
        $stmt->close();
   } else {
        error_log('Prepare failed'.$link->error);
    }

}	

 

Share this post


Link to post
Share on other sites

Do you have an example of some of the error messages?

Share this post


Link to post
Share on other sites

These are the page full of warnings I get in NetBeans and on my local host when I get it to run on the server:

" Warning: Use of undefined constant firstname - assumed 'firstname' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\volunteers3local.php on line 130"

And these are the type of messages I get on the server if I heed the warnings in NetBeans and on my localhost:

"Parse error: syntax error, unexpected 'mail' (T_STRING) "  and it will NOT insert the data.  To get the sample that works to actually insert the data, I basically changed every " to ' and where I had the single quotes ' I deleted many of them and then it ran and actually inserted the data, at least for 3 columns:-)

Share this post


Link to post
Share on other sites

Yes, to begin with, wrap all your array keys in quotation marks, that's the correct way to do it. You should show the block of code where the parse error is occurring. It's not in the code that you've posted here and that is likely why this is not working. Given the message, I'd imagine a semi-colon is missing on the previous line.

Share this post


Link to post
Share on other sites

That's where I started Saturday, and that is what would NOT run when I uploaded the pages to the server. I ended up debugging by one line at a time, and uploading again for the next line.  At the moment, when I try to go from inserting 3 columns of data to 4 columns, this is the error message from the server:

Parse error: syntax error, unexpected ',' in /.../volunteers3remote.php on line 124

And this is the code starting with line 124, which is the INSERT INTO section:

Line 124 if (isset($_POST[firstname], ($_POST[lastname], $_POST[email], $_POST[phone])) {
     if ($stmt = $link->prepare('INSERT INTO `volunteerstest`(`firstname`, `lastname`, `email`, `phone`) VALUES (?, ?, ?, ?)')) {
	$stmt->bind_param('ssss', $_POST[firstname], ($_POST[lastname], $_POST[email], $_POST[phone]);
        if (!$stmt->execute()) {
            error_log('Execute failed '.$stmt->error);
        } else {
            echo 'Data successfully inserted! first name '.$_POST[firstname].' last name '.$_POST[lastname].' email '.$_POST[email].' and phone '.$_POST[phone].'';
        }
        $stmt->close();
   } else {
        error_log('Prepare failed'.$link->error);
    }

}	
$>

If I take this down to 3 columns of data, just firstname, email and phone it runs just fine, inserts the data with the warnings about future versions.  But I have 10 columns of data for this table:-)

Share this post


Link to post
Share on other sites

So you don't think I am totally out of my mind, this is the statement I just received from the server taking that same INSERT into language down to 3 columns rather than the 4 or more:

Data successfully inserted! + the data listing

And the same code, taken down to three variables:

if (isset($_POST[firstname], $_POST[email], $_POST[phone])) {
     if ($stmt = $link->prepare('INSERT INTO `volunteerstest`(`firstname`, `email`, `phone`) VALUES (?, ?, ?)')) {
	$stmt->bind_param('sss', $_POST[firstname], $_POST[email], $_POST[phone]);
        if (!$stmt->execute()) {
            error_log('Execute failed '.$stmt->error);
        } else {
            echo 'Data successfully inserted! first name '.$_POST[firstname].' email '.$_POST[email].' and phone '.$_POST[phone].'';
        }
        $stmt->close();
   } else {
        error_log('Prepare failed'.$link->error);
    }

}	
?>

 

Share this post


Link to post
Share on other sites

Extra space?  Just tried taking that out, and still nothing but a page of warnings with this code on my localhost, did not insert the data:

if (isset($_POST[firstname], $_POST[lastname], $_POST[email], $_POST[phone])) {
     if ($stmt = $link->prepare('INSERT INTO `volunteerstest`(`firstname`, `lastname`,`email`, `phone`) VALUES (?, ?, ?, ?)')) {
	$stmt->bind_param('ssss', $_POST[firstname], $_POST[lastname], $_POST[email], $_POST[phone]);
        if (!$stmt->execute()) {
            error_log('Execute failed '.$stmt->error);
        } else {
            echo 'Data successfully inserted! first name '.$_POST[firstname].' last name '.$_POST[lastname].' email '.$_POST[email].' and phone '.$_POST[phone].'';
        }
        $stmt->close();
   } else {
        error_log('Prepare failed'.$link->error);
    }

}	

 

Share this post


Link to post
Share on other sites

I was WRONG!  Dsonesuk you GOT it!  Forgot to change the database name, and taking out that extra space did it!  Also tried it on the server and it inserted.  I cannot thank you enough, as well as everyone who tried to help!  Thank you, thank you!

Share this post


Link to post
Share on other sites

Spaces? I was pointing out the misplaced opening parenthesis. For every opening parenthesis there must be equal closing parenthesis, but it shouldn't have been there in first place.

Share this post


Link to post
Share on other sites

Just because this code is riddled with errors, make sure this is on the top of your code after using ini_set to set display_errors:

error_reporting(E_ALL);

If it is showing all errors, including notices, then that will show that you have an error on every single line where you access $_POST or $_SERVER, because you don't do it correctly anywhere.  You just do something like $_POST[firstname], and PHP is relaxed enough to catch your error and still work.  But that does not mean your code is correct, your code is not correct.  When you do something like $_POST[firstname] PHP thinks you are using a constant called "firstname", because that's the syntax for it, and when it finds that there is no constant with that name then it uses the string "firstname" instead, which is correct.

Either of these are correct:

$_POST['firstname']
	$_POST["firstname"]

This is not correct unless you've previously defined the constant:

$_POST[firstname]

You need to fix all of those errors and get the code cleaned up a little.  When you have error messages displayed and PHP reporting everything including notices, your code should run without showing any kind of error messages.  Don't guess on what the fix is, if you try to add quotes and you get a syntax error then post the code in question instead of making assumptions about what's right and what's wrong.  What you are doing in that code is never right.

Share this post


Link to post
Share on other sites

Justsomeguy, I'm trying to understand what you are saying.  I did not start with this code, I started with things in appropriate "" but the server kept giving me errors.  I was stunned with what I got back when I uploaded.  As I noted previously, when I first uploaded it was clean on my localhost and in netbeans but the server would not read it.  In my first variable, I now have it defined as :/ / define variables

$firstname = $_POST[firstname];

I only have that because I got error messages with it in either double or single quotes.  It made no sense to me as that was the way I had defined variables previously with no issues but this was the first time trying to insert data into SQL.  I went so far as to check versions of php because it made no sense.  But the only way it would proceed beyond the variables was by eliminating all single or double quotes in defining the variables. 

Share this post


Link to post
Share on other sites

You have errors and potential problem because

1) You are redefining the variables multiple times within the script.

2) running test_input function on same $_POST['postkey'] multiple times

3) potential problem using untested input ($_POST) for 'if' condition AND inserting into database

(1)this

// define variables 
$firstname = $_POST[firstname];
$lastname = $_POST[lastname];
$email= $_POST[email];
$zip= $_POST[zip];
$phone= $_POST[phone];
$house_party= $_POST[house_party];
$canvass= $_POST[canvass];
$phonebank= $_POST[phonebank];
$anything= $_POST[anything];
$comments= $_POST[comments];

Is open to an error showing if any of these is not posted, it would be better to

// define variables 
$firstname = $lastname = $email = $zip= $phone = $house_party = $canvass = $phonebank = $anything = $comments = "";

THEN check if $_POST["name_key"] isset, if yes run this through

(2) test_input function, validation etc and assign it to required variable one time and only one time only.

(3) Use this variable because it isset, validated, for any 'if' condition (check if empty "" as predefined by (1)) and inserting in to database table

Share this post


Link to post
Share on other sites

I did not start with this code, I started with things in appropriate "" but the server kept giving me errors.

That's fine.  The solution to that is to identify and fix the actual problem, not guess about quotes or whatever else.  We don't need to guess what the problem is, there are plenty of error messages where PHP will try to tell you exactly what it thinks the problem is.  The error messages aren't always 100% accurate, but that's where the programmer comes in.  The point is that you do not need to guess or mess around with quotes and end up producing incorrect code to fix errors that you don't understand.  If you post the error messages we can tell you what the problem is and help you understand that.

I only have that because I got error messages with it in either double or single quotes.

I guarantee that the quotes were not the problem.  Again, if you don't understand the errors then let us help you instead of guessing.  Programming is not an activity where you try a bunch of random things until something works, you need to understand why and how it works so that you can get it to do what you want.  And I'm telling you flat-out that your code is obviously wrong, it is not correct to refer to arrays like you're doing.  Again, with the proper error reporting settings that's going to display an error message on every line where you try to do that because none of them are correct.  Code should run without producing any messages like that.

 but this was the first time trying to insert data into SQL.

There's a hint about the actual error.  If you want to explore that further we can.  The first step is to correct your arrays.  Then if you want to talk about the correct syntax to put array values in strings we can do that too.

I went so far as to check versions of php because it made no sense.

It makes perfect sense if you understand how it works.  Basic string syntax doesn't change between PHP versions.  The most recent change to strings that I'm aware of was to add support for nowdoc blocks in addition to heredoc blocks, but neither of those use quotes at all to define the string.

But the only way it would proceed beyond the variables was by eliminating all single or double quotes in defining the variables.

And that's the point where you're incorrect.  You didn't understand the original issue so you guessed, the code appeared to run (because you don't have it printing all error messages), and you don't understand why your attempted solution works.  If you want to fix that, we can, we can help you understand.  Start by correcting all of your array references to use quotes on all of them and then if you're getting error messages we can address those.  I would recommend having PHP report all messages, including notices and warnings.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×