Home > Article > Backend Development > How to add data to database in PHP
1. Connect to the database
The prerequisite for operating the database is to connect to the database first. Before connecting to the database, we need to know the host name of the database. , user name, password, and also need to know which database we are going to choose to insert data into.
Examples are as follows:
$username="root"; $password=""; $servernmae="localhost"; $dbname="ceshi"; $connect=new mysqli($servernmae,$username,$password,$dbname);
Related recommendations: "php tutorial"
2. Statements for inserting data
The format of the statement to insert data:
insert into data table name (field name 1, field name 2,...) values (value of field 1, value of field 2);
Examples are as follows:
$sql="insert into test1 (username,age,register_time) values ('liming',20,'{$time1}') ";
Note: Field names and field values must correspond one to one and cannot be messed up!
3. Execute the statement
The next step is to execute our insert statement.
$query=$connect->query($sql); if($query){ echo "成功插入数据!"; } else{ echo $connect->error; }
Execute the insert statement and give corresponding prompts.
4. Test
Test locally. Before testing, you must first enable the local apache and mysql services, otherwise you will not be able to access them.
The above is the detailed content of How to add data to database in PHP. For more information, please follow other related articles on the PHP Chinese website!