php mysql insert into 结合详解及实例代码

php mysql insert into 结合详解及实例代码,第1张

php

mysql

insert

into

结合详解

ySQL

INSERT

INTO语句在实际应用中是经常使用到的语句,所以对其相关的内容还是多多掌握为好。

数据库表插入数据

INSERT

INTO

语句用于向数据库表添加新记录。

语法

INSERT

INTO

table_name

VALUES

(value1,

value2,....)

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

INSERT

INTO

table_name

(column1,

column2,...)

VALUES

(value1,

value2,....)

注释:SQL

语句对大小写不敏感。INSERT

INTO

insert

into

相同。

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

insert

into

`news`(title,body,time)

values('title

1','body

1',now()),('title

2','body

2',now())

2.Insert

Select

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

insert

into

news_one(id,title,body,time)

select

id,title,body,time

from

news_two

要注意的是,这两个表的结构要完全相同,列名可以不同。

在php中使用方法

下面是

"insert.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)

?>

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

insert into是mysql中最常用的插入语句,它有6种写法。

如果插入的记录是数字的话要在数字的逗号后面加n:

通过以上实例我们可以看到insert into语句只能向原表中插入于其字段对应的数据,那么能不能通过insert into语句来把其他表的数据插入到原表中呢:

在MySQL中set方法:

ModifyStatement.Set Method修改语句 set方法

Sets key and value. 设置键和值。

由于insert into语句是一个插入性的语句,所以它的功能要么向指定的表插入数据

也许你看到这个SQL语句是正确的,就觉得这样应该也可以:

mysql>mysql>insert into 4a set sname=4ainall.sname

ERROR 1064 (42000): You have an error in your SQL syntaxcheck the manual that corresponds to your MySQL server version for the right syntax to use near 'mysql>insert into 4a set sname=4ainall.sname' at line 1

或者这样也可以:

mysql>mysql>insert into 4a set sname="赵六"

ERROR 1064 (42000): You have an error in your SQL syntaxcheck the manual that corresponds to your MySQL server version for the right syntax to use near 'mysql>insert into 4a set sname="赵六"' at line 1

然后这样也是不可用:

mysql>insert into 4a select * from 4ainall set sname=4ainall.sname

ERROR 1064 (42000): You have an error in your SQL syntaxcheck the manual that corresponds to your MySQL server version for the right syntax to use near 'from 4ainall set sname=4ainall.sname' at line 1

可以看出由于select是作用于4inall这个表的,而set方法也只能在select语句中,这就直接导致set方法只能作用于4inall这个表,而无法作用于4a这个表。

但是如果我们不用select语句的话编译器又怎么会知道4inall表中的数据在哪里?

显然select是用于查的而set则是一个用于改的方法,两者无法结合在一起——insert into set语句当然也不能用于将其他表的数据插入到原表中了。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/8611150.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-18
下一篇 2023-04-18

发表评论

登录后才能评论

评论列表(0条)

保存