New to learning PHP form validation on same page. Please advise as to why my data might not be posting to the database. After filling out the form, it redirects to thank you page without sending data. Thanks!
http://pastebin.com/3T1W9Krx
Edit: Now that I know where my problem was, I have updated the Pastebin file to show the working code, which validates in the same page and checks the database for duplicate email addresses.
I was able to use Rick Kuipers suggestion below to find this error. I was trying to include a column for the primary key under VALUES, however I only needed the values for the INSERT keys, not ID or timestamp, as ID is set to auto-increment.
$sql = "INSERT INTO table (last_name, first_name, age)
VALUES (".
PrepSQL($last_name) . ", " .
PrepSQL($first_name) . ", " .
PrepSQL($age) . ")";
mysql_query($sql);
header("Location: volthankyou.php");
exit();
}
}
This could be because of a problem with your query.
Try doing the following:
echo mysql_error($db);
//header("Location: volthankyou.php");
This should display the error if there is any.
Check if mysql_query is true or false for your insert. Otherwise, it will ALWAYS try and then, redirect to thankyou. And as spencercw points out, mysql_select_db could also be failing. Always check the result of such methods.
P.S.: always check server logs
Related
I have an HTML survey. I am handling it with PHP and passing it with PHP into a MySQl database. Before this section of code, I post every input, and echo it out as a summary. Every input is reading correctly in the summary, so the form seems to be working fine. I manually input 1 dataset to test the database columns, and then 1 set of data went straight from the form to the database without issue. Now, however, I tried to insert another set of data and it isn't uploading.
I have each field outlined because I have another field that is an autoincrement for when a row is inserted. On a previous form handle I did, I also had an autoincrement field that worked perfectly without including it in the insertion process, so I'm fairly certain I don't need to include it here.
Is there something in the insert code that I've overlooked? I can manually input results just fine that match exactly what I put into the survey fields, but the digital upload from survey submission to database is not being completed. I AM connected to the database, because I have an error for failed connection set up that isn't popping up (it is paired with $dbcon. $dbcon stands for database connection).
//Data Insertion
$res_ins = "INSERT INTO Survey (name, zip,
gender, income, savings, disaster, work,
res_road, work_road, evacuation, lodging,
injury, children, num_child, educ, city_prep,
PrepComments, emer_res, info, prep, fut_prep)
VALUES ('$name', '$zip', '$gender', '$income',
'$savings', '$disaster', '$work', '$res_road',
'$work_road', '$evacuation', '$lodging',
'$injury', '$children', '$num_child', '$educ',
'$city_prep', '$PrepComments', '$emer_res',
'$info', '$prep', '$fut_prep')";
$insert = $dbcon->query($res_ins);
//Terminate connection to database and end
insertion
mysqli_close($dbcon);
I can't comment because of reputation, so I have to give you a hint in the answer: did you try to use this query directly on your database, using some interface?
However, you could try to add some rows to see what is the error, before to close the connection:
if ($dbcon->query($res_ins) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $res_ins. "<br>" . $dbcon->error;
}
before executing, print the query. it will help you to find out the root cause. most common reason of this type of issue is special character. You can check is there any special character in your query.
I have a voting system, which users can use to vote on posts. Thing is, they can't vote twice on the same post. Which is good. I did that like this:
$query = "INSERT IGNORE INTO vote_id (vote, postid, userid)
VALUES ('1', '{$postid}', '{$userid}')";
$result = mysqli_query($db, $query);
header('Location: index.php');
(The $db is my variable that connects to the database.)
They can still click on the vote, even if it doesn't insert into the table. The problem is, when it is IGNORE they shouldn't be able to click.
How do I separate the INSERT and IGNORE, so I can use the IGNORE in an if statement? Or in any other way, that can change the layout of the page?
Without code showing "vote" it's hard to say, but if it's button, then you can simply query a SELECT for a user_id and post_id, and if it finds at least one row, then add disabled to button. Like that:
<button name="vote" value="1" disabled>Vote</button>
Or just don't display anything "to vote" at all when query returns rows.
Other way is to check session, but it'd let the same user to vote again after relogging.
Thing is, they can't vote twice on the same post. Which is good. I did that like this:
What you've shown us here doesn't prevent people from voting twice (a unique index on postid and userid will - but that's not in your post). I do hope you are cleaning those parameters before splicing them into a an SQL statement like that.
But that is a comment.
How do I separate the INSERT and IGNORE, so I can use the IGNORE in an if statement
While I'm not 100% certain, I would expect mysqli_affected_rows() to return 0 if no rows were inserted. A more robust solution would be to omit the 'IGNORE' from the SQL statement and handle the duplicate key error:
$result = mysqli_query($db, $query);
$error=mysqli_errno($db);
switch ($error) {
case 0:
// all good
header('Location: index.php');
break;
case 1062:
print "Please don't vote twice\n";
exit;
default:
trigger_error("Query failed " . $query . " // " . mysqli_error($db));
print "whoops";
exit;
}
I am having some problem with the mysql. Well this is my code
class store_info{
function store_info(&$bean, $event, $arguments){
$id = $bean->id;
$name = $bean->user_name . ' ' .$bean->last_name;
$user_hash = $bean->user_hash;
$query1 = "INSERT INTO sohan_password_management (id_user, name, user_password, register_date, prompt_date, deadline) VALUES('$id', '$name', '$user_hash', NOW(), NOW() + INTERVAL default_prompt_date DAY, NOW() + INTERVAL default_deadline DAY)";
$result1 = $bean->db->query($query1, true);
$bean->save();
}
}
?>
whenever i run this code, data get store in database but it stores for 11 times. I mean same data get stored for more than one time in database. May I know what is wrong here? Till yesterday it was working fine. I don't know what happened to this now.
Try to comment/ remove $bean->save();
I think it is a after_save logic hook and it is executing multiple times.
Also, check this post as well.
http://support.sugarcrm.com/02_Documentation/04_Sugar_Developer/Sugar_Developer_Guide_6.5/03_Module_Framework/Logic_Hooks/Examples/Preventing_Infinite_Loops_with_Logic_Hooks/
I've had a similar issue before. It was due to a slow network connection and reloading the same page which kept submitting my input to the table. To fix this, I created a if statement to check the values of each item being submitted and if a certain number were the same values as a current column in the table, I told it not to input the data.
After including this if statement, it worked perfectly for me.
Not sure if you can apply the same solution to your data set, but I hope this helps.
You are calling bean save in the logic hook which is why bean is saving records multiple times.
You do not need to call the save function within a hook.
i'm trying to set up a simple multipage form, with the use of sessions to be later stored in a database in multiple tables.
however, i seem to have run into a problem. while the values of the last page get posted to the database, the session variables do not.
please, keep in mind.. me and my project partner are complete newbies to php/sql and might not have payed as much attention in class as we should have. most of the code is pretty much thrown together randomly. and identifying problems does not seem to be our strong suit.
first page / b_tickets.php
(simple html form with the values 'ticket_a', 'ticket_k' and 'ticket_vip')
second page / b_rooms.php
<?php
session_start();
$_SESSION['ticket_a'] = $_POST['ticket_a'];
$_SESSION['ticket_k'] = $_POST['ticket_k'];
$_SESSION['ticket_vip'] = $_POST['ticket_vip'];
?>
third page / b_ucp.php
<?php
session_start();
$_SESSION['room_s'] = $_POST['room_s'];
$_SESSION['room_s_extra'] = $_POST['room_s_extra'];
$_SESSION['room_d'] = $_POST['room_d'];
$_SESSION['room_d_extra'] = $_POST['room_d_extra'];
$_SESSION['room_3'] = $_POST['room_3'];
$_SESSION['room_3_extra'] = $_POST['room_3_extra'];
$_SESSION['room_10'] = $_POST['room_10'];
$_SESSION['room_10_extra'] = $_POST['room_10_extra'];
$_SESSION['pension'] = $_POST['pension'];
?>
which leads to
insert_ucp.php
(at this point an echo ยง_SESSION of the previous variables reveals that they are in fact still stored.)
<?php
session_start();
$con = mysql_connect("localhost","XX","XX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("fatcity", $con);
$sql="INSERT INTO tickets (ticket_a, ticket_k, ticket_vip)
VALUES
('$_SESSION[ticket_a]','$_SESSION[ticket_k]','$_SESSION[ticket_vip]')";
$sql="INSERT INTO rooms (room_s, room_s_extra, room_d, room_d_extra, room_3, room_3_extra, room_10, room_10_extra, pension)
VALUES
('$_SESSION[room_s]','$_SESSION[room_s_extra]','$_SESSION[room_d]','$_SESSION[room_d_extra]','$_SESSION[room_3]','$_SESSION[room_3_extra]','$_SESSION[room_10]','$_SESSION[room_10_extra]','$_SESSION[pension]')";
$sql="INSERT INTO ucp (title, name, n_family, adress, a_housenumber, continent, country, province, region, city, telephone, email, password, payment, client, comment)
VALUES
('$_POST[title]','$_POST[name]','$_POST[n_family]','$_POST[adress]','$_POST[a_housenumber]','$_POST[continent]','$_POST[country]','$_POST[province]','$_POST[region]','$_POST[city]','$_POST[telephone]','$_POST[email]','$_POST[password]','$_POST[payment]','$_POST[client]','$_POST[comment]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
at this point the question is not in fact about how terrible we are when it comes to php/sql- thank you.. we already figured that out. with only pretty much three days to our deadline..
but why exactly the session variables aren't saved to the database. what exactly are we overlooking?
thank you very much in advance..
RUN query every time!!!
You create variable, then overwrite it 2 times than execute it
should be:
$sql = 'smth';
mysql_query($sql);
$sql = 'smth';
mysql_query($sql);
$sql = 'smth';
mysql_query($sql);
you have
$sql = 'smth';
$sql = 'smth';
$sql = 'smth';
mysql_query($sql);
And as I've said do not use mysql_*. And your code allows sql injection
First problem I see, is that $sql variable gets overriden 2 times in the last piece of code. So, only the last query gets executed.
Second, you should use this syntax to inject non-tribial vars into strings: "INSERT ... ${someArray[someKey]} ..." - note curly braces. This is not required here, but it will save you from troubles in the future.
Third, sanitize all the input data! You will have SQL injection in the last code example.
Last, no need to session_start() in each file - just place it once in bootstrapping file and require_once it.
I agree with E_p in that only one of your queries is ever going to be executed. doing what he suggested will allow all your queries to execute.
You may also want to take a look at your tables, just from looking at your query structure I see nothing wrong with them, but you may end up having a hard time getting the info you want back out. I could be wrong since you didn't post your table structures nor was your question really regarding this, but its just something I noticed and figured I would share. Your tables do not look like they are connected to each other by any foreign keys. This may not be needed for your project, but if you needed to pull all the form data related to all ticket_a entries then you would only get a list of sessionIDs corresponding to the ticket_a column, without any info from your 'rooms' or 'upc' tables. If that is what you are going for then its fine, otherwise you may want to look into it.
I was wondering if you can maybe help me out here... I created a link sharing website and managed to create a comment on a shared link.
I want to give you a scenario of what I would like to achieve. Every comment made by user_1 for instance, can only be deleted by user_1 and admin.
I understand that when "deleting" it from the php page it must also be dropped from the database. How can you do this?
//I pressume where I INSERTED my post's 'vales' I must DELETE them again from there??
//It is very much alike from reply.php's code where you INSERT the data into the database. Now I just want to delete it.
//I don't know if this code below is correct??
$sql = "DELETE FROM
posts(post_content,
post_date,
post_topic,
post_by)
WHERE ('" . $_POST['reply-content'] . "',
NOW(),
" . mysql_real_escape_string($_GET['id']) . ",
" . $_SESSION['user_id'] . ")";
$result = mysql_query($sql);
if(!$result)
{
echo 'Your reply has not been saved, please try again later.';
}
else
{
echo 'Your comment has been deleted!';
}
Your Delete query has major syntax errors. You don't delete individual fields from a table - you CAN'T. you can only delete entire records. The proper syntax is:
DELETE FROM sometable WHERE (...)
Your where clause also has errors. You're not doing any comparison operations, just listing some values. Again, a syntax error. Most like you'd want this (guessing at your post's table primary key field name):
DELETE FROM posts WHERE (post_id = $id);
You should give your comments ID's, and simply perform delete from posts where ID = $id.
The SQL statement you currently have won't even execute. Look at the manual for how the syntax works.
What would really be helpful is some separation of presentation logic from db logic from bus. logic. Try a MVC pattern, which makes it a lot easier to parse through the code and to only look at DB or presentation or bus. logic code. Then, we could focus on the answer to the question posted.