Reputation: 452
I'm new to php form insertion and can't seem to find an answer to my specific issue. I'm able to send the name/email to a database, however I need to specify the input table in order to keep it more organized. With my current setup, I only know how to create new databases for each product giveaway, but I'm sure there is a better way than that.
Here is my current php code, please keep in mind I'm two weeks into php! If you could specify where I need to enter anything that would help a lot.
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
mysql_connect("localhost","username","password");//database connection
mysql_select_db("myusername_mytable");
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
// Get values from form
$name = $_POST['name'];
$email = $_POST['email'];
//inserting data order
$order = "INSERT INTO user_info
(name, email)
VALUES
('$name','$email')";
//declare in the order variable
$result = mysql_query($order);
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Registration Complete!';
}
*********UPDATE***********
Turns out I was using deprecated language, so I switched to PDO. Thank you all for the help!
IF any other newbies were wondering with the previous form, I was missing an incredibly easy fix where it says $order = "INSERT INTO user_info
which was the table name!
Upvotes: 0
Views: 137
Reputation: 448
Firstly, you need to be using the MySQLi or PDO libraries, which are more secure than the now deprecated mysql_
library.
Assuming you want to store information on the giveaway and the entrants, you can create a single database with two tables, entrants
and giveaways
.
Give giveaways
the structure of
id int primary key auto_increment
name varchar(100),
start_date datetime
end_date datetime
and entrants
the structure of
id int primary key auto_increment
giveaway_id int //this is a foreign key linking the entrant to the relevant giveaway
email varchar(100),
name varchar(150)
With that in mind, let's have a look at your code:
//setting your arrays for later
$data = array();
$errors = array();
//checking your posted data values
if(empty($_POST['name'])) $errors['name'] = "Name is required.";
if(empty($_POST['email'])) $errors['email'] = "Email is required.";
//find out if we had any errors
if(!empty($errors)) {
//if we did, then we return them
$data['success'] = false;
$data['errors'] = $errors;
} else {
//and if we didn't, continue
$sql = new MySQLi(/*your host, username, password and database name here */);
if($sql->connect_error) {
//if we can't get a connection to the database, kill the script and print out a handy message
die("Connection error: ".$sql->connect_error." ".$sql->connect_errorno);
}
}
//get your securimage script
include_once($_SERVER['DOCUMENT_ROOT'].'/securimage/securimage.php');
if ($securimage->check($_POST['captcha_code']) == false) {
//do some error handling for the captcha checking
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
//did all that work? Awesome, let's continue
//ALWAYS escape your form data. It's not a sure win against SQL injection but it's the best place to start
$email = $sql->real_escape_string($_POST['email']);
$name = $sql->real_escape_string($_POST['name']);
//assuming that there can only be one giveaway running at any one time...
//get the id of the active giveaway, where it's end date is more than the current time
$query = "SELECT id FROM giveaways WHERE end_date > NOW()";
//query the database or kill the script and print an error (further down the line, don't print the error for security reasons
$result = $sql->query($query) or die($sql->error);
if($result->num_rows > 0) {
//if there's an active giveaway, fetch that result
$row = mysqli_fetch_assoc($result);
//and set a variable to the id we want
$id = $row['id'];
//insert into your entrants the now linked entrant details and giveaway key
$query = "INSERT INTO entrants (giveaway_id, name, email) VALUES ('$id', '$name', '$email')";
//again, query or error handling
$result = $sql->query($query) or die($sql->error);
//if that query worked, do your success message, if it didn't tell the entrant that something went wrong
if($result) {
$data['success'] = true;
$data['message'] = "Registration complete!";
} else {
$data['success'] = false;
$data['message'] = "There was an error registering you, please try again soon.";
}
}
Now, when you need to return all entrants to a specific giveaway you simply do:
SELECT name, email FROM entrants WHERE giveaway_id = //the id of the giveaway
Upvotes: 1
Reputation: 583
If you change the structure of your table, you can save the giveaway name.
SQL
ALTER TABLE user_info ADD COLUMN giveaway VARCHAR(64) NOT NULL;
PHP
$giveaway = $_POST['giveaway'];
$order = "INSERT INTO user_info
(name, email, giveaway)
VALUES
('$name','$email','$giveaway')";
I'd recommend using bound parameters in your query and sanitizing your data input from $_POST, too. Check out PDO.
Upvotes: 0