简体   繁体   中英

Insert data into two table from a web form

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

将表单值读入变量,安全地插入MySQL数据库: http : //www.php.net/manual/zh/function.mysql-query.php

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM