php向mysql数据库中插入数据(单条和多条)

版权声明:转载请注明出处,谢谢! https://blog.csdn.net/dreamstone_xiaoqw/article/details/78024954

原始代码来自于:http://www.runoob.com/php/php-mysql-insert.html

<?php

//mysql
$servername = "localhost";
$username = "root";
$password = "******";
$dbname = "yixzm";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
        die("Connect Failed: " . $conn->connect_error);
}

echo "Connected Success!";

// use sql create database table
// table name: guests
$sql = "insert into guests (name, email)
        values ('Luffy', 'luffy@onepiece.com')";

if ($conn->query($sql) === true) {
        echo "Table guests insert Successfully";
} else {
        echo "Create Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

?>

运行结果如下:
这里写图片描述

与创建数据库的代码相比,此时在调用mysqli函数时,多传入一个参数:$dbname。这与创建数据表的情况相同。

mysqli($servername, $username, $password, $dbname);

向mysql数据库中插入数据的关键代码是:

$sql = "insert into guests (name, email)
        values ('Luffy', 'luffy@onepiece.com')";

重点:

insert into 数据表名(变量名列表)
values(变量值列表)

插入多条数据

连接数据库代码相同,区别在于插入的代码。插入代码如下:

$sql = "insert into guests (name, email)
        values ('Luffy', 'luffy@onepiece.com')";
$sql .= "insert into guests (name, email)
        values ('Zero', 'zero@onepiece.com')";
$sql .= "insert into guests (name, email)
        values ('Nami', 'nami@onepiece.com')";

第一条数据插入代码相同,区别在于后续数据追加时,赋值符号为.=
这一点和Makefile变量追加赋值相似,区别在于Makefile中是用+=符号来追加赋值。

展开阅读全文

没有更多推荐了,返回首页