Home  >  Article  >  php adds data to data table

php adds data to data table

无忌哥哥
无忌哥哥Original
2018-06-28 11:30:132379browse

* 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);

//2. Prepare sql statement

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

//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)";

//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";

//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 '成功的新增了'.mysqli_affected_rows($db).'条记录,
新记录的主键id是:'.mysqli_insert_id($db); } else { echo '没有记录被新增'; } } else { //项目上线后,不应该将出错信息显示出来,否则会暴露数据库的相关信息 exit(mysqli_errno($db).':'.mysqli_error($db)); }

//4. Close the connection

mysqli_close($db);
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