Insert data into two table from a web form - php

table person
"person_id"
"person_name"
table email
"email_id"
"email"
"person_id"
What is the sql comment for insert data form a web form into these tables?
In the web form I have a text box for name and dynamic text box for email

Read the form values into variables, securely insert into MySQL database: http://www.php.net/manual/en/function.mysql-query.php

If you want to do this by only SQL queries, you need to code a procedure like
INSERT INTO person (person_name) VALUES ('PERSON_NAME')
INSERT INTO email (email_id,email,person_id) VAUES ('EMAIL_ID','EMAIL',(SELECT LAST_INSERT_ID()))
I assumed that you can post PERSON_NAME, EMAIL_ID, EMAIL from your web form.
I think it's easy to send both EMAIL_ID, EMAIL from your autocomplete like box.

Well assuming you are using POST and you set up your connection to the db i'd do it like this (i omit validation and so on, just the sript to insert data :
$person_name = mysql_real_escape_string($_POST['person_name']);
$email= mysql_real_escape_string($_POST['email']);
$query = sprintf("INSERT INTO person ('person_name') VALUES ('%s')'",$person_name);
$result = mysql_query($query);
// always set your variables to a default value
$success = false;
// did the query execute successfully?
if($result){
$success = true;
}
if($success){
$person_id = mysql_insert_id();
$query = sprintf("INSERT INTO email ('email','person_id') VALUES ('%s','%s')",$email,$person_id);
$resultSecond = mysql_query($query);
}

There are a few steps involved. You will first need to validate the user's input - don't just put it directly into the database. Validation should be done on the server. You can perform client-side validation with Javascript too, but this should only be done to enhance the user experience - it must not replace server-side validation. To start, you could look at PHP's Filter methods, or perhaps look for a form validation library.
When you come to insert it into the database, I highly recommend using prepared statements instead of messing around with horrible escaping.
The example given on the PHP site is quite good, and should get you started. You could also checkout:
PHP PDO prepared statements
Why you Should be using PHP’s PDO for Database Access

Related

insert data to mysql inwith php

In the below script, I'm trying to submit many from php to mysql in one table,
<?php
include "koneksi.php";
$soal[] = $_POST['soal'];
$j1=$_POST['jwb_1'];
$j2=$_POST['jwb_2'];
$j3=$_POST['jwb_3'];
$j4=$_POST['jwb_4'];
$j5=$_POST['jwb_5'];
$kunci=$_POST['kunci'];
$beban=$_POST['beban'];
$id=$_POST['id_soal'];
$course=$_SESSION['course'];
$mgu=$_SESSION['m`enter code here`inggu'];
$jum=$_POST['jum'];
$i=$id;
for ($i=1;$i<=$jum;$i++){
$sq=mysql_query("insert into
t_soal(id_soal, course, soal, jawab_1,
jawab_2, jawab_3, jawab_4, jawab_5, beban,
kunci, minggu)
values('$i', '$course', '$soal', '$j1',
'$j2', '$j3', '$j4', '$j5', '$beban',
'$kunci', '$mgu')");
}
Be sure to never put your data this way. Please, be aware of SQL Injection, XSS attacks... You need to validate your inputs, parameterized and clean it. Then, put it in your mysql using SQL statement.
And try to use a good form for your SQL statement. Like this :
INSERT INTO `databaseName`.`tableName` (`id_soal`, `course`) VALUES ($i, $course);
Everything should work..(Be sure to connect correctly to your database too!)

How do i use a Fabrik (joomla component) form to connect to database table & search for match & return a result?

I am using the Joomla! component Fabrik.
The functionality I am trying to get is to have users buy a unique code from my website using e-junkie. On completion of payment, e-junkie will process a script that will send the code to a MySQL database table.
After buying, they will then be redirected to a page on the website to activate their code by filling in a form. In order to activate their code, they will need to enter data into three text fields:
First Name
Last Name
Unique Code
The form is already set up with Fabrik and displayed nicely on the website.
What I need now is when the form is submitted, I need it to connect to the database where the unique codes are stored, search the database table for the matching firstname,lastname and unique code and return a success message if a match is found and a failure message if no match is found.
Fabrik allows for PHP plugin scripts to run when the form is submitted, I will use a separate plugin for each field on the form.
So far I have come up with the snippet of code below which would be executed when the form is submitted. I am just attempting to validate the firstname field on the form at this stage just to get it working. once it is working i will duplicate the code and adapt it for the other fields (e.g lastname and uniquecode).
Problem is i just cant get it to work. It uses Joomla's JFactory/getDBO to connect to the database.
My Table name is travelcodes
The fields on the form are, firstname, lastname and uniquecode
the columns on the table are also firstname,lastname and uniquecode
$firstname = '{travelcodes___firstname}';
$value = '{tablename___firstname}';
$db =JFactory::getDBO();
$query=("SELECT firstname FROM travelcodes where field = '$firstname'");
$db->setQuery($query);
$response = $db->loadResult();
if ($response == $firstname) {
return true;
} else {
return false;
}
Any help with this would be much appreciated.
Thanks.
Bailey
I have no problem using the following setting
I think you will need to add JRequest::getVar before ('you_element') and have the setting to be onBeforeProcess
$db = JFactory::getDbo();
$date = date("Y-m-d H:i:s", time());
$value = JRequest::getVar('off_line_ap___offline_reason');
$user =& JFactory::getUser();
$uid = $user->id;
$db->setQuery("INSERT INTO d2_exchange_log (date_time, part, quantity, user_id, purpose) VALUES ('{$date}', '{$value}', '99','{$uid}', 'Test')");
$submissionsNo=$db->loadResult();

SQL Insert won't insert on all fields

I have PHP generating an HTML form and I'm trying to write a script that will update the information in the database. For some reason it works on some of the fields and not others.
Code which won't work:
PHP-Form that users can change details within
echo"<form name='details'>";
echo"<p>Surname: <input type='text'id='surname' value='".$row['Surname']."'/></p>;
<p>Telephone: <input type='text'id='phone' value='".$row['Telephone']."'/></p>;
<p>Postcode: <input type='text' id='postcode' value='".$row['Postcode']."'/></p>;
<p>House/Flat Number: <input type='text' id='number' value='".$row['Number']."'/></p>";
AJAX - sends changes to server via querystring
var sname = document.getElementById('surname').value;
var tel = document.getElementById('phone').value;
var num = document.getElementById('number').value;
var pcode = document.getElementById('postcode').value;
var queryString = "?username=" + username +"&email="+email....";
ajaxRequest.open("GET", "url" + queryString, true);
ajaxRequest.send(null);
PHP - execute update command
//connect to server
...
//get variables
$sname = $_GET['sname'];
$pcode = $_GET['pcode'];
$tel = $_GET['tel'];
$num=$_GET['num'];
//process update
$update ="UPDATE User SET Surname='$sname',Telephone='$tel',Number='$num',
Postcode='$pcode' WHERE Username='$username'";
//if query, display success
if(mysqli_query($update))
{
echo"success";
}
else
{
echo"error";
}
//else display error
The query executes fine, but the values aren't displaying within the database. My other variables (username, password etc) all update fine. All database fields are type VARCHAR(80).
EDIT: I do have the query being executed. This still results in the surname, postcode, number and telephone field not being updated.
Ignoring for the moment all the other issues with this code and approach (SQL injection issues, GET vs. POST issue, etc.), and dealing with the update not changing things as expected, there are a couple of things to check.
Try outputing the update query in your logs and make sure that it actually looks like what your expecting. It could be that the values you're meaning to push across the wire are not making it into the query or that.
Verify that running the query by hand in an standalone SQL client (mysql, squirrel, etc...) Actually updates a record. It's entirely possible that a valid update query may not match any records. (Say the username value you're looking for does not match one that's in the database.
Not knowing your infrastructure, I'd suggest some sanity checks: Are you actually pointing at the right database? Do you have a your update wrapped in a transaction that's rolling back? etc ...
A few other tips:
I would suggest looking at PDO, in particular how Prepared Statements work. The kind of query you're building above is someone to run off with all your data or worse. While not a panacea, prepared statements are a solid first step.
Take a look at Jquery's Ajax functions. In particular the post method. It provides a simple interface for making ajax calls without having to construct special url strings. Plus, switching to a POST will avoid your data showing up in webserver logs files.

How to put a PHP 'not null' condition on mysql insert statement?

I have a page with two forms on it (and two submit buttons), and the forms link the page back to itself with action="" for the INSERT INTO statements. One of the INSERT INTO statements is:
<?php
$sql="INSERT INTO panelProduct (length_mm, width_mm, aperture)
VALUES ('$_POST[p_length_mm]','$_POST[p_width_mm]','$_POST[p_aperture]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
One of the reasons I have put the form and the INSERT statements on the same page is that the form allows users to add products to an order, and there may be several products (so I thought the user could keep submitting until they're done...). The other reason was that I need to use a $_POST value sent from the previous page to do something else with the products they enter, and I don't know how to send it to more than one page.
Anyway, the problem I have found is that a new row is inserted into the database every time the page is refreshed, containing NULL values. This makes sense to me as the PHP will execute the statement above every time it encounters it. My question therefore is how I can make some sort of condition that will only execute the INSERT statement if the user enters something in the form and 'Submits'?
you could use the empty() method of PHP to check for null values in each of the variables.
Something like:
if(!empty($_POST['p_length_mm']) && !empty($_POST['p_width_mm']) && !empty($_POST['p_aperture']))
{
//execute your query here
}
else
{
//if there's an alternative you would like to happen if values are null, or just leave out.
}
Hope that does the trick.
You have to check if data come from your form. I'd suggest this approach - name your submit button (i.e. <input type="submit" name="my_submit_button" value="Whatever" /> and this condition to your insert code:
if( isset( $_POST['my_submit_button']) ) {
.. process your post data
}
Also, always remember not to trust user provided data. Verify if all data expected are present in$_POST and format matches requirements (i.e. you ask for number and received letters etc). If all test passed, then you are ready to commit your data to DB.
You need a condition like this:
if ('POST' === $_SERVER['REQUEST_METHOD']) {
// a form was posted
}
Of course, you still need to check whether your post actually contains the right stuff:
isset($_POST['p_length_mm'], $_POST['p_width_mm'], $_POST['p_aperture'])
Even better is to use filter_input_array() to sanitize your incoming data; your current code is open to SQL injection attacks. Using PDO or mysqli and prepared statements is the way to go.

PHP form submission

I've built mini content management system. In my page add form i'm using ckeditor. for text are named content
<textarea id="content" style="width:100%" name="content"></textarea>
Adding all data from form into db table with following php code. (Function filter used for sanitizing data)
<?php
require '../../core/includes/common.php';
$name=filter($_POST['name'], $db);
$title=filter($_POST['title'], $db);
$parentcheck=filter($_POST['parentcheck'],$db);
if(isset ($_POST['parent'])) $parent=filter($_POST['parent'],$db);
else $parent=$parentcheck;
$menu=filter($_POST['menu'], $db);
$content = $db->escape_string($_POST['content']);
if(isset($_POST['submit'])&&$_POST['submit']=='ok'){
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$menu')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', '$title', '$content')") or die($db->error);
header("location:".$wsurl."admin/?page=add");
}
?>
FUNCTION FILTER (data sanitization)
function filter($data, $db)
{
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = $db->escape_string($data);
return $data;
}
I got questions about it. (I'm newbie to ajax.)
Currently i'm submitting data with standart php (page refreshes
every time). How to modify code for ajax submission?
I have only one button for submitting data. I want to create second
button "save" which will update db fields via ajax
How can i create autosave function (which periodically saves form in the background and informss user about it, just like on Stackoverflow) via ajax?
Thx in advance
Let's suppose you want to use jQuery to do the ajax business for you, you need to setup a periodic POST of the data in the textarea (note that in some browsers GET requests have a limit).
On the first POST, you need to tell the PHP script "this is the first POST" so that it knows to INSERT the data, it should then return to you some identifying characteristic. Every other time you POST data, you should also send this identifying characteristic, let's just use the primary key (PK). When you POST data + PK, the PHP script should run an update query on the SQL.
When constructing these, the thing to think about is sending data from the browser using JavaScript to a PHP script. The PHP script gets only whatever packet of data you send, and it can return values by producing, for instance, JSON. Your JavaScript code can then use those return values to decide what to do next. Many beginners often make the mistake of thinking the PHP can make calls to the JS, but in reality it's the other way around, always start, here, with the JS.
In this instance, the PHP is going to save data in the database for you, so you need to ship all the data you need to save to the PHP. In JS, this is like having some magic function you call "saveMyData", in PHP, it's just like processing a form submission.
The JavaScript side of this looks something like this (untested):
<script type="text/javascript">
var postUpdate = function(postKey){
postKey = postKey || -1;
$.post("/myscript.php",
/* note that you need to send some other form stuff
here that I've omitted for brevity */
{ data: $("#content").value(), key: postKey },
function(reply){
if(reply.key){
// if we got a response containing the primary key
// then we can schedule the next update in 1s
setTimeout(function(){postUpdate(reply.key);}, "1000");
}
}
});
};
// first invocation:
postUpdate();
</script>
The PHP side will look something like this (untested):
Aside: your implementation of filter should use mysql_real_escape_string() instead of striptags, mysql_real_escape_string will provide precisely the escaping you need.
<?php
require '../../core/includes/common.php';
$name = filter($_POST['name'], $db);
$title = filter($_POST['title'], $db);
$parentcheck = filter($_POST['parentcheck'],$db);
if(isset($_POST['parent'])){
$parent = filter($_POST['parent'],$db);
}else{
$parent = $parentcheck;
}
$menu = filter($_POST['menu'], $db);
$content = $db->escape_string($_POST['content']);
$pk = intval($_POST['key']);
if($pk == -1 || (isset($_POST['submit']) && $_POST['submit']=='ok')){
$result = $db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$menu')")
or die($db->error);
$new_id = $db->insert_id;
$result2 = $db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', '$title', '$content')")
or die($db->error);
$pk = $db->insert_id;
echo "{\"key\": ${pk}}";
// header("location:".$wsurl."admin/?page=add");
}else if($pk > 0){
$result2 = $db->query("UPDATE pages SET content='$content' WHERE id='$pk')")
or die($db->error);
echo "{\"key\": ${pk}}";
}
For AJAX, you can use jQuery's ajax API. It is very good and is cross-browser.
And for saving and auto-saving: you can use a temporary table to store your data. When the user presses the save button or when your data is auto-saved, you save your data to the table using AJAX and return a key for the newly created row. Upon future auto-save/save button events, you update the temporary table using AJAX.
And one word of advice, use a framework for your PHP and Javascript. I personally use Symfony and Backbone.js. Symfony checks for CSRF and XSS automatically and using Doctrine prevents SQL-injection too. There are other frameworks available (such as CodeIgniter, CakePHP and etc.) but I think Symfony is the best.
Edit: For the auto-save functionality, you can use Javascript SetTimeout to call your AJAX save function, when the page loads for the first time.
With regard to security issues:
Your silver bullet function is fundamentally flawed, it does not work, will never work and can never work.
SQL has different escaping needs than hmtl.
The functions you use counteract each other. escape_string adds \, stripslashes removes them.
Never mind the order of the functions, you need to use a specialized escape function for one and only one purpose.
On top of that you are using depreciated functions.
For MySQL this is mysql_real_escape_string. Note that escape_string (without the real) is depreciated, because it is not thorough enough. Use real_escape_string instead. On mysqli escape_string is an alias for real_escape_string.
See:
How does the SQL injection from the "Bobby Tables" XKCD comic work?
The ultimate clean/secure function

Categories