douxuan4556 2014-05-22 15:21
浏览 30
已采纳

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

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!

  • 写回答

2条回答 默认 最新

  • dongqing344716 2014-05-22 15:55
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来