PHP、Java、C++大神教你建站基础代码
在当今这个信息化时代,网站已经成为了企业和个人展示自己的窗口,掌握一门或多门编程语言,可以帮助我们快速搭建网站,本文将分别介绍PHP、Java和C++三种编程语言在建站过程中的基本代码。
一、PHP基础代码
1. 连接数据库
```php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
?>
```
2. 获取用户输入数据并插入数据库
```php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$sql = "INSERT INTO messages (name, email, message) VALUES ('$name', '$email', '$message')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "" . $conn->error;
}
?>
```
3. 从数据库中读取数据并显示在网页上
```php
$sql = "SELECT id, name, email FROM messages";
$result = $conn->query($sql);
?>
Messages
num_rows > 0): ?>ID | Name | |
---|---|---|
```
二、Java基础代码(以JSP为例)
1. 建立数据库连接(这里以MySQL为例)
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.apache.commons.dbcp2.BasicDataSource;
import com.mysql.cj.jdbc.MysqlDataSource; // 需要添加MySQL Connector/J依赖包
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
```
还没有评论,来说两句吧...