Home >Database >Mysql Tutorial >mysql insert into用法实例

mysql insert into用法实例

WBOY
WBOYOriginal
2016-06-01 09:58:161423browse

先来看一下mysql中insert into的语法:

<code class="language-sql">INSERT INTO table_name VALUES (value1, value2,....)</code>

您还可以规定希望在其中插入数据的列:

<code class="language-sql">INSERT INTO table_name (column1, column2,...)VALUES (value1, value2,....)</code>


注释:SQL 语句对大小写不敏感。INSERT INTO 与 insert into 相同。

实例一:insert语句一次可以插入多组值,每组值用一对圆括号括起来,用逗号分隔,如下:

<code class="language-sql">insert into `news`(title,body,time) values('title 1','body 1',now()),('title 2','body 2',now());</code>

 

实例二.Insert Select 语句,将查询的结果插入到新的表,顾名思义,它由一条insert语句和一条select语句组成

<code class="language-sql">insert into news_one(id,title,body,time) select id,title,body,time from news_two;</code>

在php中使用方法要注意的是,这两个表的结构要完全相同,列名可以不同。

下面是 "insert.php" 页面的代码:

<code class="language-php"><?php $con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con)
?></code>

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn