I am trying to create a form builder that will enable users generate survey form/page.
After the form is generated the form attribute is stored on a table.
Question 1:
Where can I store the form attribute knowing fully well that the number of fields user might add in the form is unknown.
Question 2:
Where and how do I store data submitted through the generated form when some one for example completes the survey form.
Should I create new tables on fly for each of the form attributes? If yes what if over a million forma are created which translates to a million tables.
Is this where multi-tenancy comes into play.
Please provide your answer based on best practices.
I think I get what you're asking, but why not create one table with 100 columns, labelled 1-100. Set a limit on the amount of fields a user can create(Limit 100).
Then, POST the fields and add a sql query to store the values...?
COMMENT ANSWER
If the user is already signed in filling this form I would personally do the POST request on the same page.
<?php if (isset($_POST['field1'])){
$valueforField1 = $_POST['field1'];
$valueforField2 = $_POST['field2'];
$valueforField3 = $_POST['field3'];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Survey (field1, field2, field3) // I guess you would `have to add 100 fields here to accommodate the fields in your DB Also, you can set a default value in MySQL that way if field 56-100 is not set it has a value like 0 or add the value in this php file`
VALUES ('$valueforField1', '$valueforField2', '$valueforField3')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close(); ?>
COMMENT ANSWER or if you want to wait for the user to log in you can store all the values in a SESSION variable.
<?php
session_start();
if (isset($_POST['field1'];)){
if (!(isset($_SESSION['email']))){
$_SESSION['field1'] = $_POST['field1'];
// You would have to do 100 of these
}
}
?>
Related
I'm sending data to a db from a web form but every time I run it the data is stored in the db in six new rows rather than just one.
The form is just a standard form with inputs for email/password and a submit button. The action of the form runs this:
<?php
// connect to db
$link = new mysqli("localhost", "root", "", "db_name");
if (!$link) {die('Database Error: Could not connect: ' . mysql_error());}
// username and password sent from form
$email = $_POST['email'];
$password = ($_POST['password']);
// encrypt
$salt = substr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), 0, 16);
$em = crypt($email, '$6$'.$salt);
$pw = crypt($password, '$6$'.$salt);
// insert to db
$insert = "INSERT INTO users (email, password) VALUES ('$em', '$pw')";
$link -> query($insert);
// check succes/fail
if ($link->query($insert) === TRUE) {
echo "New record created successfully";}
else {
echo "Error: " . $sql . "<br>" . $link->error;
}
// close the db connection
$link->close();
I know this brings up a question about sanitizing inputs with encryption/salting. This page says that it's a reasonable method. Please feel free to bring that up, but I'm not really looking for an argument over best practices for sanitizing user inputs.
I'm wondering if anyone cal tell me why the data would be stored 6 times instead of just once. I changed the $6$ to $1$ but it still added 6 rows.
You have some silly seo-friendly links implementation on your site that makes it run your php code on every reques, and 5 links to non-existent resources in your html.
I'm learning PHP and SQL by running MAMP on my Mac, and accessing the database through phpMyAdmin.
I've made one PHP script to add a new user to a table, one for comparing inputted data with the table (login) and one to close an account. All of the scripts are very basic and the data isn't sanitized at all, as I'm just getting used to the basics of PHP.
I've noticed that after I run the script for account creation (inserting data), a few seconds after the script is run, a new row is added to the table with an id (which I've set to auto increment) but no other data.
I'm just wondering if the reason for this is something obvious in MySQL that I'm just missing.
The following is the account creation script:
<?php
//Get values from HTML form
$varUsername = $_POST['username'];
$varPassword = $_POST['password'];
$varPasswordHash = password_hash($varPassword, PASSWORD_DEFAULT);
//Establish connection to database
$server = "localhost";
$username = "root";
$password = "root";
$database = "members";
$connection = mysqli_connect($server, $username, $password, $database);
if(!$connection)
{
die("Connection failed: " . mysqli_connect_error());
}
//Send data to database
$action = "INSERT INTO details (USERNAME, PASSWORD) VALUES ('$varUsername', '$varPassword')";
if(mysqli_query($connection, $action))
{
echo 'Account created.';
}
else
{
echo 'Account creation failed: ' . mysqli_error($connection);
}
mysqli_close($connection); //End connection to database
?>
and the HTML form to go with it:
<html>
<body>
<form action="sign_up.php" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit">
</form>
</body>
</html>
I'm making a guess right now...
I would add an extra if-statement to the script itself. Like this:
if (isset($_POST['submit-form'])) {
// All the above to insert the data into the script...
}
It would make sense if you visit the sign_up.php itself and notice there is a new entry made into your database.
You'll have to modify your HTML a little, to make the if-statement work.
Just add name='submit-form' to the submit button: <input type="submit" name="submit-form">
This will make the script more complete.
Also a little update on the matter as I just read that it adds an empty row after you submit an empty form.
You can check wether the fields are filled in with, guess what, another if-statement:
if (empty($_POST['username'])) {
echo 'Please enter your username...';
} else
if (...)
You do not verify if the POSTed values have anything in them, thus submitting an empty form results in an empty entry in the DB with just the ID.
I am developing a php/mysql system.
I have a table juncfees which has the fields - juncid, matterid, staffid, fee. The fee stores to hourly rate to be charged for a matter.
The matterid refers to a matter table and staffid refers to a staff table but I don’t think that is relevant for what I want to achieve.
Every year the fees will be subject to an annual rise and what I want to be able to do is to have a page that will enable an admin to do this without involving me. In the past I have changed the values using code such as UPDATE juncfees SET fee=’45’ WHERE staffid=‘5’; This works fine but I would rather others could do it without direct database access.
I was imagining a page where there was a dropdown list of staff to give me the staffid and a box where the new fee could be entered then a button which, once clicked, would update all of the relevant data.
Is this possible and, if so, how do I go about doing it? (Of course, if there’s a better way then I am happy to follow that route.)
Many thanks
Here is an adapted sample from w3.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE juncfees SET fee='".$_POST['fee']."' WHERE staffid='".$_POST['staffid']."'";
if ($conn->query($sql) === TRUE) {
echo "Records updated successfully";
} else {
echo "Error updating records: " . $conn->error;
}
$conn->close();
?>
The HTML is just a simple form:
<form action="update.php" method="post">
StaffID: <input type=text name=staffid><br>
Fee: <input type=text name=fee><br>
<input type=submit>
</form>
HTML form is just an example, actually any markup or language which can post http data can trigger the PHP code (which is pretty much all of them). So if you want to create a desktop application to do this that would be quite easy as well.
using System.Net;
function postData(float fee, int id)
{
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/update.php");
var postData = "fee="+fee;
postData += "&staffid="+id;
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
Keep in mind, this is just the most basic of example and has no protection as far as user access or from SQL injection.
I'm trying to check for an existing entry in MySQL before executing the INSERT statement. If the user enters a name already in the database (field is set to unique) then they should be prompted to re-enter the name.
The problem I'm having is that if the new entry matches a record in any form then the error message displays and no INSERT happens.
For example, if the user enters DUMMY_NEW and there is a record DUMMY_OLD they aren't able to add the record even though DUMMY_NEW does not exist in the table.
I've searched and tried other answers already but can't seem to get this to work.
Code with extraneous bits removed for clarity:
//Create connection to database using mysqli
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
//Set variables according to user input on previous form
$Server_Name = $_POST['Server_Name'];
//Check for duplicate server name - if exists inform user else run INSERT ($stmt)
$checkdup = "SELECT * FROM dcr_table WHERE SERVER_NAME = '".$Server_Name."'";
$dupresult = $conn->query($checkdup);
if($dupresult = 1)
{
print "<br>Error! <p></p>";
echo "" . $Server_Name . " already exists in the DCR";
print "<p></p>Please check the Server Name and try again";
}
else {
//Define the INSERT statement
$stmt = "INSERT INTO dcr_master (Server_Name, Description,..., ... , ... )";
//Execute the INSERT statement
$conn->query($stmt);
//Success and return new id
echo "<br><p></p>Record Added!<p></p>";
echo "New id: " . mysqli_insert_id($conn);
//Drop the connection
$conn->close();
};
Edit:
I'm aware of the injection vulnerability. The MySQL account only has SELECT, INSERT and UPDATE rights to the table. The end user must supply the password or submit will fail. This is small app with limited user access at the moment. MySQL escape strings will be implemented after current issue is resolved.
Edit 2:
Using Hobo Sapiens method does work in reporting an existing entry however a new (empty) row is still added to the table. The record ID still auto-increments so what I get is id#300 - record, id#301 - blank, id#302 - record. Is this a result of the IGNORE in the INSERT statement?
Your code creates a race condition if two people attempt to create the same ame at the same time and you're not handling the fallout properly.
If you have set the SERVER_NAME column to UNIQUE then you needn't check for the existence of a server name before you perform your INSERT as MySQL will do that for you. Use INSERT IGNORE ad check the number of affected rows after the query has executed to find out if it worked:
//Create connection to database using mysqli
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
//Set variables according to user input on previous form
$Server_Name = $_POST['Server_Name'];
//Define the INSERT statement with IGNORE keyword
$stmt = "INSERT IGNORE INTO dcr_master (Server_Name, Description,..., ... , ... )";
if ($conn->query($stmt) === false) {
die("Database error:".$conn->error);
}
// Check for success
if ($conn->affected_rows == 0) {
print "<br>Error! <p></p>";
echo "" . $Server_Name . " already exists in the DCR";
print "<p></p>Please check the Server Name and try again";
} else {
//Success and return new id
echo "<br><p></p>Record Added!<p></p>";
echo "New id: " . $conn->insert_id;
}
This is an atomic operation so no race condition, and it involves only one call to the database.
I recommend you use either the OOP style or the procedural style for mysqli_*() but don't mix them. Usual warnings about SQL injection apply.
Use mysqli_num_rows
$row_cnt = $dupresult->num_rows;
if ($row_cnt > 0) {
echo "There is a matching record";
}else {
//insert into table
}
This statement:
if($dupresult = 1)
will always return 1. You should first retrieve the first query result (if any), like so:
$row=$dupresult->fetch_array(MYSQLI_NUM);
and then compare the result against NULL:
if(!$row)
First time question, long time reader :)
I am building forms dynamically from Columns in a MYSQL DB. These columns
are created/ deleted etc.. elsewhere on my App. My form runs a query against a
SQL View and pulls in the column names and count of columns. Simple! build the form,
with the HTML inputs built with a PHP for loop, and it echos out the relevant HTML for the new form fields. All very easy so far.
Now i want a user to update these dynamically added fields and have the data added to the relevant columns - same table
as existing columns. So, as the input fields are named the same as the columns, they are posted to a PHP script for processing.
Problem is, while i have the actual field names inserted in to the SQL INSERT query, i cannot figure out how to extract the POST
data from the POST dynamically and add this to the VALUEs section of the query.
Here is my attempt....
The Query works without the variables added to it.
It works like this, first section/ is to retrieve the columns names from earlier created VIEW - as these are identical to POST names from the form. Then output to array and variable for insertion to Query. It looks like the implode function works, in that the relevant column names are correct in the statement, but i fear that my attempt to inject the column names on to the POST variables is not working.
$custq = "SELECT * FROM customProperties";
$result = $database->query($custq);
$num_rows = mysql_numrows($result);
while (list($temp) = mysql_fetch_row($result)) {
$columns[] = $temp;
}
$query = '';
foreach($columns as $key=>$value)
{
if(!empty($columns[$key]))
{
$values .= "'".'$_POST'."['".$value."'], ";
}
}
$q = "INSERT INTO nodes
(deviceName,
deviceInfo,
".implode(", ", $columns).",
nodeDateAdded,
status
)
VALUES
('" . $_POST['deviceName'] . "',
'" . $_POST['deviceInfo'] . "',
".$values."
CURDATE(),
'1'
)";
$result = $database->query($q)
Any help is much appreciated. I will feed back as much as i can. Please note, relativity new to PHP, so if i am all wrong on this, i will be glad for any tips/ advice
Regards
Stephen
If you want to get the values of every POST input without knowing the input names then you can do it this way:
//get all form inputs
foreach($_POST as $name => $value)
{
echo $name . " " . $value . "<br>";
}
If you want to get the value of certain POST inputs where you know the name of the input field then you can do it this way:
if(isset( $_GET["deviceName"]))
{
$deviceName = $_POST["deviceName"];
}
if(isset( $_GET["deviceInfo"]))
{
$deviceInfo = $_POST["deviceInfo"];
}
To connect to a database and insert the info then you have to do something like this:
$host = "localhost";
$dbuser = "username";
$pass = "password";
$datab = "databasename";
//Create DB connection
$con=mysqli_connect($host, $dbuser, $pass,$datab);
if (mysqli_connect_errno($con))
{
echo "ERROR: Failed to connect to the database: " . mysqli_connect_error();
}
else
{
echo "Connected to Database!";
}
//insert into database
mysqli_query($con, "INSERT INTO nodes (deviceName, deviceInfo) VALUES ('$deviceName', '$deviceInfo')");
(Don't forget to add mysql_real_escape_string to the $_POST lines after you get it working.)