PHP表单插入到Db中的特定表中

时间:2014-05-22 15:21:51

标签: php mysql forms

我是php表单插入的新手,似乎无法找到我特定问题的答案。我可以将名称/电子邮件发送到数据库,但是我需要指定输入表以使其更有条理。根据我目前的设置,我只知道如何为每个产品赠品创建新数据库,但我确信有更好的方法。

这是我目前的PHP代码,请记住我已经进入php两周了!如果你可以指定我需要输入任何可以帮助很多的东西。

<?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 ***********

原来我使用的是弃用的语言,所以我切换到了PDO。谢谢大家的帮助!

如果其他任何新手都对之前的表单感到疑惑,我错过了一个非常简单的解决方案,其中显示$order = "INSERT INTO user_info这是表名!

2 个答案:

答案 0 :(得分:1)

首先,您需要使用MySQLiPDO库,这些库比现已弃用的mysql_库更安全。

假设您要在赠品和参赛者上存储信息,您可以使用两个表格entrantsgiveaways创建一个数据库。

giveaways结构

id int primary key auto_increment
name varchar(100),
start_date datetime
end_date datetime

entrants

的结构
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)

考虑到这一点,让我们看看你的代码:

//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.";
    }
}

现在,当您需要将所有参赛者退回特定赠品时,您只需:

SELECT name, email FROM entrants WHERE giveaway_id = //the id of the giveaway

答案 1 :(得分:0)

如果您更改了表格的结构,则可以保存赠品名称。

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')";

我建议您在查询中使用bound parameters并清理$ _POST中的数据输入。查看PDO