Home > headlines > php adds data to data table

php adds data to data table

无忌哥哥
Release: 2018-06-28 11:30:13
Original
2542 people have browsed it

* Add new data to the data table

* Functions used:

* 1.mysqli_query(),

* 2.mysqli_errno(),mysqli_error (),

* 3.mysqli_affected_rows(),mysqli_insert_id(),

* 4.mysqli_close()

//1. Connect to the database

define ('DB_HOST', 'localhost');
define ('DB_USER', 'root');
define ('DB_PASS', 'root');
define ('DB_NAME', 'php');
define ('DB_CHAR', 'utf8');
$db = @mysqli_connect(DB_HOST, DB_USER, DB_PASS);
if (mysqli_connect_errno($db)) {
    exit('连接失败'.mysqli_connect_error($db));
}
mysqli_select_db($db, DB_NAME);
mysqli_set_charset($db, DB_CHAR);
Copy after login

//2. Prepare sql statement

$sql = "INSERT INTO staff (staff_id,name,sex,age,salary) VALUES (null,'赵敏',1,30,4000)";
Copy after login

//INSERT is a standard SQL syntax. Not only can one be inserted, but also multiple records can be inserted. New records are separated by commas. Auto-incrementing the primary key id can be omitted

$sql = "INSERT  staff (name,sex,age,salary) VALUES ('小昭',1,20,2400),('宋青书',0,40,1800),('成昆',0,70,9000)";
Copy after login

//For MySQL database, there is a more efficient way to insert data, but only one record can be inserted at a time

$sql = "INSERT staff SET name='灭绝师太',sex=1, age=58, salary=9999";
Copy after login

//3. Execute query: return true on success, return on failure false

$res = mysqli_query($db, $sql);
var_dump($res);exit;
if (mysqli_query($db, $sql)) {
    if (mysqli_affected_rows($db) > 0) {
        //返回受影响的记录数与新增主键id
        echo &#39;成功的新增了&#39;.mysqli_affected_rows($db).&#39;条记录,<br>新记录的主键id是:&#39;.mysqli_insert_id($db);
    } else {
        echo &#39;没有记录被新增&#39;;
    }
} else { //项目上线后,不应该将出错信息显示出来,否则会暴露数据库的相关信息
    exit(mysqli_errno($db).&#39;:&#39;.mysqli_error($db));
}
Copy after login

//4. Close the connection

mysqli_close($db);
Copy after login
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template