1. Connect MySQL database with PHP
<?php $host ="localhost";//服务器地址 $root ="root";//用户名 $password ="admin";//密码 $database ="beyondweb_test";//数据库名 $conn = mysql_connect($host,$root,$password);//连接数据库 if(!$conn){ die("数据库连接失败!".mysql_error()); }else{ echo"数据库连接成功"; } mysql_select_db($database,$conn);//选择数据库 mysql_query("set names utf-8");//设置编码为utf-8 ?>
2. Add data to the database
First of all, I created such a user table in the beyondweb_test database for demonstration
SQL statement:
CREATE TABLE user( id INT(20) PRIMARY KEY AUTO_INCREMENT, nikename VARCHAR(30), email VARCHAR(40) );
Then add data to the database:
<?php $query ="INSERT INTO user(nikename,email) VALUES(#张三#,#beyondwebdotcn@xxx.com#);";//#号代表单引号,使用单引号才是正确的 $result = mysql_query($query); if(!$result){ echo"Error!"; }else{ echo"Success!"; mysql_close($conn);//关闭数据库连接 } ?>
3. Modify the data in the database
We also operate based on the user table, for example "Zhang San" is changed to "Li Si", the php code is as follows:
<?php $query ="UPDATE user SET nikename=#李四# WHERE id=#1#;"; //#号代表单引号,使用单引号才是正确的 $result = mysql_query($query); if(!$result){ echo"Error!"; }else{ echo"Success!"; mysql_close($conn);//关闭数据库连接 } ?>
In fact, the SQL statement has changed, and the others are exactly the same.
4. Query the database
Just change the SQL statement. For example, query all the data in the table and output it in table form:
<?php $query ="SELECT * FROM user;"; $result = mysql_query($query); if(!$result){ echo"Error!"; }else{ echo"Success!"; } ?> <br/> <table border="1px"> <tr> <th>id</th> <th>nikename</th> <th>email</th> </tr> <?php while($row = mysql_fetch_row($result)){ echo"<tr>"; echo"<td>".$row[0]."</td>"; echo"<td>".$row[1]."</td>"; echo"<td>".$row[2]."</td>"; echo"</tr>"; } ?> </table> <?php mysql_close($conn); ?>
5. Delete data
The solutions to adding data, modifying data, and deleting data have been given before, so the only "delete" left in "add, delete, modify, and check" is. Let's take a look at how to delete data. In fact, it is the same as the above. It’s almost like a sentence, just change the SQL statement
<?php $query ="DELETE FROM user WHERE nikename=#张三#;"; //#号代表单引号,使用单引号才是正确的 $result = mysql_query($query); if(!$result){ echo"Error!"; }else{ echo"Success!"; mysql_close($conn);//关闭数据库连接 } ?>
The above is (advanced part) PHP connects to the database to implement the most basic addition, deletion, modification and query (process-oriented), and more related content Please pay attention to the PHP Chinese website (www.php.cn)!