Home > Backend Development > PHP Problem > How to add data to database in PHP

How to add data to database in PHP

爱喝马黛茶的安东尼
Release: 2023-02-25 08:40:01
Original
8406 people have browsed it

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);
Copy after login

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}') ";
Copy after login

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;
}
Copy after login

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!

Related labels:
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