How do I insert into a form with over 100 fields - php

I've created a user form in which once the submit button is pressed I would like to send/insert the data to mysql database adding a new record. The form has over 100 input fields. How can I accomplish this. Here is my sample php code.
<html>
<head>
</head>
<body>
<?php
if (isset($_POST['submit'])){
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "hostname";
$username = "username";
$password = "password";
$dbname = "dbname";
$mystuff = "tenant_lname","tenant_fname","tenant_mname","ssn","dl_number","dl_state","birthday","tenant_hphone","tenant_wphone","tenant_cphone","curr_street","curr__unit","curr_city","curr_state","curr_zip","how_long_from","how_long_to","last_rent_mnt","last_rent_amt","own_man_name","own_man_tel","curr_reason","pre_street","pre_unit","pre_city","pre_state","pre_zip","pre_from","pre_to","pre_last_rent","pre_amt","pre_owner","pre_owner_tel","pre_reason","sec_pre_street","sec_pre_unit","sec_pre_city","sec_pre_state","sec_pre_zip","sec_pre_from","sec_pre_to","sec_pre_last_paid_mnt","sec_pre_amt","sec_pre_owner","sec_pre_owner_tel","sec_pre_reason","curr_emp_name","curr_emp_add","curr_emp_phone","curr_emp_pos","curr_emp_bus_type","curr_emp_sup","curr_emp_from","curr_emp_to","curr_emp_salary","pre_emp_name","pre_emp_add","pre_emp_phone","pre_emp_pos","pre_emp_bus_type","pre_emp_sup_name","pre_emp_from","pre_emp_to","pre_emp_salary","move_date","addntl_occ_name","addntl_occ_age","addntl_occ_relation","addntl_ft","addntl_pt","addntl_occ1_name","addntl_occ1_age","addntl_occ1_relation","addntl_occ1_ft","addntl_occ1_pt","addntl_occ2_name","addntl_occ2_age","addnt2_occ1_relation","addntl_occ2_ft","addntl_occ2_pt","addntl_occ3_name","addntl_occ3_age","addntl_occ3_relation","addntl_occ3_ft","addntl_occ3_pt","credit_yes","credit_no","det_yes","det_no","evict_yes","evict_no","bnkry_yes","bnkry_no","fel_yes","fel_no","pet_yes","pet_no","pet_numb","pet_type","furn_yes","furn_no","ins_cov_yes","ins_cov_no","ints_yes","ints_no","ints_type","smoke_yes","smoke_no","occ_smoke_yes","occ_smoke_no","explain_smoke","bnk_name","bnk_add","checking","checking_bal","saving","saving_bal","bnk_name1","bnk_add1","checking1","checking_bal1","saving1","saving_bal1","other_income","credit_name","credit_add","credit_city","credit_acct","credit_bal","credit_payment","credit_name1","credit_add1","credit_city1","credit_acct1","credit_bal1","credit_payment1","credit_acct2_name","credit_add2","credit_city2","credit_acc2","credit_bal2","credit_payment2","credit_acc3_name","credit_acc3_add","credit_acc3_city","credit_acc3_number","credit_acc3_bal","credit_acc3_payment","emer_contact_name","emer_contact_add","emer_relation","emer_phone","reg_owner_yes","reg_owner_no","reg_who","vehicle_year","vehicle_make","vehicle_model","vehicle_color","vehicle_license","veh_state","vehicle2_year","vehicle2_make","vehicle2_model","vehicle2_color","vehicle2_license","veh2_state";
$con = mysql_connect("$hostname","$username","$password");
if (!$con){
die ("Can not connect:" . mysql_error());
}
mysql_select_db("dbname",$con);
$sql = "INSERT INTO dbname ($mystuff) VALUES ('$_POST[$mystuff]')";
mysql_query($sql,$con);
mysql_close($con);
}
?>
</body>
</html>

$mystuff should be an array.
You can generate your query and form with an loop.
Do validation if these is for productive use!
$_POST is also an array, so $_POST["field1", "field2", ...] ist an syntax error.
You can only access one key at once e.g. $_POST['field1'] . ',' . $_POST['field2']
You can join all values in an array by an char (e.g. ',') with implode()
rethink your Database schema!
untested:
<html>
`enter code here`<head>
`enter code here`</head>
<body>
<?php
>if (isset($_POST['submit'])){
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "hostname";
$username = "username";
$password = "password";
$dbname = "dbname";
$mystuff = array( "tenant_lname","tenant_fname","tenant_mname","ssn","dl_number","dl_state","birthday","tenant_hphone","tenant_wphone","tenant_cphone","curr_street","curr__unit","curr_city","curr_state","curr_zip","how_long_from","how_long_to","last_rent_mnt","last_rent_amt","own_man_name","own_man_tel","curr_reason","pre_street","pre_unit","pre_city","pre_state","pre_zip","pre_from","pre_to","pre_last_rent","pre_amt","pre_owner","pre_owner_tel","pre_reason","sec_pre_street","sec_pre_unit","sec_pre_city","sec_pre_state","sec_pre_zip","sec_pre_from","sec_pre_to","sec_pre_last_paid_mnt","sec_pre_amt","sec_pre_owner","sec_pre_owner_tel","sec_pre_reason","curr_emp_name","curr_emp_add","curr_emp_phone","curr_emp_pos","curr_emp_bus_type","curr_emp_sup","curr_emp_from","curr_emp_to","curr_emp_salary","pre_emp_name","pre_emp_add","pre_emp_phone","pre_emp_pos","pre_emp_bus_type","pre_emp_sup_name","pre_emp_from","pre_emp_to","pre_emp_salary","move_date","addntl_occ_name","addntl_occ_age","addntl_occ_relation","addntl_ft","addntl_pt","addntl_occ1_name","addntl_occ1_age","addntl_occ1_relation","addntl_occ1_ft","addntl_occ1_pt","addntl_occ2_name","addntl_occ2_age","addnt2_occ1_relation","addntl_occ2_ft","addntl_occ2_pt","addntl_occ3_name","addntl_occ3_age","addntl_occ3_relation","addntl_occ3_ft","addntl_occ3_pt","credit_yes","credit_no","det_yes","det_no","evict_yes","evict_no","bnkry_yes","bnkry_no","fel_yes","fel_no","pet_yes","pet_no","pet_numb","pet_type","furn_yes","furn_no","ins_cov_yes","ins_cov_no","ints_yes","ints_no","ints_type","smoke_yes","smoke_no","occ_smoke_yes","occ_smoke_no","explain_smoke","bnk_name","bnk_add","checking","checking_bal","saving","saving_bal","bnk_name1","bnk_add1","checking1","checking_bal1","saving1","saving_bal1","other_income","credit_name","credit_add","credit_city","credit_acct","credit_bal","credit_payment","credit_name1","credit_add1","credit_city1","credit_acct1","credit_bal1","credit_payment1","credit_acct2_name","credit_add2","credit_city2","credit_acc2","credit_bal2","credit_payment2","credit_acc3_name","credit_acc3_add","credit_acc3_city","credit_acc3_number","credit_acc3_bal","credit_acc3_payment","emer_contact_name","emer_contact_add","emer_relation","emer_phone","reg_owner_yes","reg_owner_no","reg_who","vehicle_year","vehicle_make","vehicle_model","vehicle_color","vehicle_license","veh_state","vehicle2_year","vehicle2_make","vehicle2_model","vehicle2_color","vehicle2_license","veh2_state");
$sql_values=array();
foreach($mystuff as $fieldname) {
/* do validation! */
$sql_values[$fieldname] = "'" . mysql_real_excape_stiring($_POST[$fieldname]) . "'";
}
$con = mysql_connect("$hostname","$username","$password");
if (!$con){
die ("Can not connect:" . mysql_error());
}
mysql_select_db("dbname",$con);
$sql = "INSERT INTO dbname (".implode(',', $mystuff).") VALUES (" . implode(',', $sql_values) . ")";
mysql_query($sql,$con);
mysql_close($con);
}
foreach($mystuff as $fieldname) {
echo "...an input field...";
}
?>
</body>

Create inputs something like :
<input type="text" name="datas[firstname]"/>
<input type="text" name="datas[lastname]"/>
You can process the data using :
<?php
$datas = $_POST['datas'];
$columns = implode(",",array_keys($datas));
//add ' since mysql use ' for strings
$values = implode("','",$datas);
$sql = "INSERT INTO dbname (".$columns.") VALUES ('".$values."')";
Hope this help.

Related

Basic PHP entry failing

I'm setting up a wedding invitation RSVP form. I have here what should be a basic PHP and SQL data entry, but I keep getting the error:
"Could not enter data: No database selected"
UPDATE - Many thanks to all your suggestions. I have updated my code as you can see bellow. I now get a new error as follows:
"Could not connect:" (witch is a message I output myself in line 7, but it does not show the error that should follow")
Does anyone know what this means please?
Here is my [UPDATED] code:
<?php
function submit(){
$con = mysqli_connect("localhost", "jaredand_rsvp", "jar3dandcr1st1na", "jaredand_rsvp");
if (!$con)
{
die('Could not connect: ' . $con->error);
}
$name = $_POST['name'];
$partnerName = $_POST['partner_name'];
$allergies = $_POST['allergies'];
$comments = $_POST['comment'];
$going = $_POST['going'];
$sql = 'INSERT INTO rsvp '.
'(name,partner_name, allergies, comments, going) '.
'VALUES ( "'.$name.'", "'.$partnerName.'", "'.$allergies.'", "'.$comments.'", "'.$going.'")';
$result = $con->query($sql);
if(!$result )
{
die('Could not enter data: ' . $result->error);
}
echo "Entered data successfully\n";
mysqli_close($con);
}
if(isset($_POST['name']))
{
submit();
}
?>
Can anyone please advise me on what I am doing incorrectly?
That happens because mysql_connect doesn't have database name as parameter.
You should connect to the server, and then select a database by calling mysql_select_db
Cheers!
this is the right way
$con = mysql_connect("localhost","USERNAME","PASSWORD);
mysql_select_db('jaredand_rsvp', $con);
but please use "mysqli"
$con = mysqli_connect("localhost", "USERNAME", "PASSWORD, "jaredand_rsvp");
$result = $con->query($sql);
happy to help,
for security is better if you escape your values before insert :
$name = $con->real_escape_string($_POST['name']);
$partnerName = $con->real_escape_string($_POST['partner_name']);
$allergies = $con->real_escape_string($_POST['allergies']);
$comments = $con->real_escape_string($_POST['comment']);
$going = $con->real_escape_string($_POST['going']);
Try to connect to the database first and then select the database name
I hope this will fix your issue
Or you could use PDO because mysql_connect is depricated
You have used $con = mysql_connect(); at the top and bottom you are using:
mysqli_close();
First follow the same standarad. Use mysqli instead of sqli at top.i.e,
$con = mysqli_connect("localhost","USERNAME","PASSWORD", "jaredand_rsvp");
Remove the line: mysql_select_db('jaredand_rsvp');
and replace $retval = mysql_query( $sql, $con ); with
$retval = mysqli_query( $sql, $con );
Use it another Way
<?php
function submit() {
$host = "localhost";
$username = "root";
$password = "";
$dbname = "jaredand_rsvp";
$con = new mysqli($host, $username, $password, $dbname);
if ($conn -> connect_error) {
die("Connection failed: " . $conn -> connect_error);
}
$name = $_POST['name'];
$partnerName = $_POST['partner_name'];
$allergies = $_POST['allergies'];
$comments = $_POST['comment'];
$going = $_POST['going'];
$sql = 'INSERT INTO rsvp ' . '(name,partner_name, allergies, comments, going) ' . 'VALUES ( "' . $name . '", "' . $partnerName . '", "' . $allergies . '", "' . $comments . '", "' . $going . '")';
if($con->query($sql)== TRUE){
echo "Data Inserted";
}
else {
echo mysqli_error($con);
}
mysqli_close($con);
}
if (isset($_POST['name'])) {
submit();
}
?>
How about using MySQLi instead of the now depreciated MySQL?
EDIT
Okay, I see no connection being made to the database. Something like
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
If you have stored the db connect credential on a different file then i see no include or require mentioned on your this script either. Check if you have made the connection and then get back.

Inputted values not saved while inserting data from html form into sql database (html,php,sql)

The problem: insert.php connects fine, but only inserts empty values ('') when I hit 'save' on the html form. The text I type, which I'm trying to insert, isn't saved. Somewhere a connection isn't being made and that data is lost but I can't figure out exactly where. Any help?
HTML insert form (collecting data for 2 parameters, 'user' and 'thread')
<form action="insert.php" method="post">
user: <input type="text" name="user"><br>
thread: <input type="text" name="thread"><br>
<input type="submit" value="Save">
</form>
PHP code to connect to SQL, insert inputted values
<?php
$user = $_POST['user'];
$thread = $_POST['thread'];
$servername = "##.##.###";
$username = "harwoodjp";
$password = "~";
$dbname = "332";
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("SQL (&#9746)<br/> " . $conn->connect_error);
}
echo "SQL (&#9745) <br/>";
$sql = mysql_connect($servername,$username,$password);
mysql_connect($servername,$username,$password);
mysql_select_db("332project");
//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);
echo "<script>window.location='select.php'</script>"; //select.php displays the full table
//close MySQL
mysql_close($sql);
?>
try this
<?php
$user = $_POST['user'];
$thread = $_POST['thread'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
//create connection
$conn = mysql($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("SQL (&#9746)<br/> " . $conn->connect_error);
}
echo "SQL (&#9745) <br/>";
$sql = mysql_connect($servername,$username,$password);
mysql_select_db("db");
//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);
echo "<script>window.location='select.php'</script>"; //select.php displays the full table
//close MySQL
mysql_close($sql);
?>
It might be because the default form posting method is GET.
Either change your $_POST to $_GET or add method="POST" to your form tag.

PDO Insert from Web Form

What is wrong with the way that I am attempting a PDO insert using PHP and MySQL?
The MySQL database uses the same names as the ($_POST) variable.
<?php
if (!empty($_POST)) {
//Declare Database Variables Here
$dblist = ($_POST);
$keys = array_keys($data);
$dbcols = join(', ', array_values($keys));
$data = join(', ',array_values($dblist));
$dbtype = "mysql";
$dbhost = '127.0.0.1';
$dbname = 'bpstalent';
$dbuser = 'root';
$psword = 'root';
$portno = 3306;
// if table_name is submitted, display dynamic table with another form request for table name
$pdo = new PDO('mysql:host=' . $dbhost . ';port=' . $portno . 'dbname=' . $dbname . ';' . $dbuser . ';' . $psword . ';' );
echo "form submitted";
$sql = "INSERT INTO 'applicants'($dbcols) VALUES ($data)";
$stmt = $pdo->prepare($sql);
$stmt->execute();
}
else {
?>
html form here
<?
;}
?>
Also, I think you're an easy target to SQL injection. I would change
$sql = "INSERT INTO 'applicants'($dbcols) VALUES ($data)";
and replace values of $dbcols with hard coded list of columns (they can come from an array as well, just not one sent by user)
For the $data I would replace that with params what are handled by bindValue(). You can accomplish that by replacing "," with ",:" to convert names to para place holders. If echoed Your final query would look something like this:
$sql = "INSERT INTO applicants (col1, col2, col3) VALUES (:col1, :col2, :col3)";
See this example in PHP docs, it will be worth your time to secure this form:
http://www.php.net/manual/en/pdostatement.bindvalue.php
Below is a reworked sample of your script, untested, but should give you an idea of how to make things safer:
<?php
if ($_POST) {
//HARDCODE COLUMNS, DO NOT RELY ON USER INPUT, BAD THINGS WILL HAPPEN IF YOU DO
$keys = array("col1", "col2", "col3");
$dbcols = '`'.join('`, `', $keys).'`';
$placeholders = ':'.join(', :', $keys);
//RUN THROUGH POST DATA LOOKING FOR YOUR KEYS, ONLY PASS TO DATABASE DATA YOU ARE EXPECTING TO SEE
$data = array();
foreach ($keys as $k)
{
$data[$k] = $_POST[$k];
}
//CONSIDER REPLACING THIS WITH require_once() FILE
$dbtype = "mysql";
$dbhost = '127.0.0.1';
$dbname = 'bpstalent';
$dbuser = 'root';
$psword = 'root';
$portno = 3306;
$pdo = new PDO("$dbtype:host=$dbhost;port=$portno;dbname=$dbname", $dbuser, $psword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO applicants ($dbcols) VALUES ($placeholders)";
$stmt = $pdo->prepare($sql);
$stmt->execute($data);
}

Pulling multiple fields from database using forms and php

I have a database with multiple rows with various fields.
I have a form that contains a drop down list.
The drop down list displays one of the database fields (field_name) for each row in the database.
When the user selects the desired entry hits SUBMIT, that value is passed to the results.php page and can be used via $_POST.
All of this currently works.
I would like a way to send the rest of the row's fields that correspond to the row of the selected field (not just the "field_name") from the database along with what is selected from the drop down menu.
For instance, if I have a database with rows with a fields named "name", "date", and "age", I would like to have all the database rows "name"s appear in the drop down list and once submitted, pass that particular name's "date" and "age" on to the results.php for use on that page.
<html>
<head>
<title>Drop Down Test</title>
</head>
<body style="font-family: verdana; font-size: 11px;">
<?php
//Variables for connecting to database.
$hostname = "abcd";
$username = "abcd";
$dbname = "abcd";
$password = "abcd";
$usertable = "abcd";
//Connecting to database
$connection = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database!");
$db = mysql_select_db($dbname);
$query = "SELECT * FROM abcd";
$result = mysql_query($query) or die(mysql_error());
?>
<h2>Drop Down Test Form</h2>
<p>Please fill out the form below and click submit.</p>
<form action="results.php" method="POST">
<p>Drop Down Test:
<select name='event'>
<!-- Drop down -->
<?php
while($row = mysql_fetch_array($result))
{
echo '<option>' . $row['field_name']. '</option>';
}
?>
</select>
<p><input type="submit" value="Submit"><p>
</form>
you should put a value on your option like this:
echo '<option value = "'.$row['field_name'].'" name = "">' . $row['field_name']. '</option>';
then you can access it by $_POST['event'];
UPDATE
getting all the values from the select, you can use $_SESSION variables to pass it to the other php.file.
// First of all, I advice you to connect via PDO, or at least msqli, because mysql_query is depreciated.
// To connect with database you need:
DEFINE("USER", "root");
DEFINE("DBNAME", "test");
DEFINE("DBPASSWORD", "");
DEFINE("DBHOST", "localhost");
$dbh = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME,USER,DBPASSWORD,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//The query:
$sth = $dbh->prepare("SELECT name,age,date FROM test");
$sth->execute();
//the drop down form
echo '<form action="results.php" method="POST">
<select name="event"><option value=0></option>';
while ($result = $sth->fetch(PDO::FETCH_ASSOC)) { extract($result);
echo '<option value="date:'.$date.'-age:'.$age.'"/>'.$name.'</option>';
echo '</select>
<p><input type="submit" value="Submit"><p>
</form>';
}
//the event in the records.php by clicking submit
if(isset($_POST['event'])){
echo 'name:',$name'-date:',$date,'-$age',$age;
}
This did the trick (in results.php):
<?php
$hostname = "****";
$username = "****";
$dbname = "****";
$password = "****";
$usertable = "abcd";
$connection = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database!");
$db = mysql_select_db($dbname);
//it was this SQL query that was the key, namely the WHERE statement
$query = "SELECT * from abcd where field_name='$_POST[event]'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
echo "id: " . $row[0] . "<br/>";
echo "field_name: " . $row[1] . "<br/>";
//etc...
//try to throw the individual results into variables
$variable = $row[1];
echo "Check to see that the variable was passed a value: " . $variable . "<br />";
echo "Check to see that form selection carried over: " . $_POST['event'] . "<br />";
?>
I realize this is not the "up-to-date" way of doing things and I will now try to get everything "modernized".
Thanks for all the help!

putting input in a database using mysqli

I'm trying to use mysqli to insert data from a form into a database. However I'm not getting it to work :/
This is my code from the page you get to after you filled in the form. The form is not the problem because the variables $headin $author and $thecontent all have data in them. And in the real code database username password and name have real values :)
<html>
<head>
<title>Send!</title>
</head>
<body>
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
$DB_HOST = 'localhost';
$DB_USER = '**';
$DB_PASS = '***';
$DB_NAME = '***';
# $db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
echo 'Error.';
exit();
}
$author = $_POST['author'];
$heading = $_POST['heading'];
$thecontent = $_POST['thecontent'];
$query = 'INSERT INTO articles ('heading', 'author', 'content')
VALUES ('$heading','$author','$thecontent')';
$result = $db->query($query);
if ($result) {
echo $db->affected_rows."This was added.";
}
else {
echo "somethings gone very wrong.";
}
$db->close();
?>
</body>
</html>
You cannot add single quotes ' on row names and you have to add double quotes for INSERT:
$query = "INSERT INTO articles (`heading`, `author`, `content`)
VALUES ('$heading','$author','$thecontent')";
Also escape your strings:
$author = $db->real_escape_string($_POST['author']);
$heading = $db->real_escape_string($_POST['heading']);
$thecontent = $db->real_escape_string($_POST['thecontent']);

Categories