1. 连接数据库:```PHP$servername = "localhost";$username = "username";$p
1. 连接数据库:
```PHP
$servername = "localhost";
$username = "username";
$passWord = "password";
$dbname = "database";
$conn = new Mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
```
2. 查询数据库:
```php
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "字段1: " . $row["column1"]. " - 字段2: " . $row["column2"]. "
";
}
} else {
echo "0 结果";
}
```
3. 插入数据到数据库:
```php
$sql = "INSERT INTO table_name (column1, column2, column3)
VALUES ('value1', 'value2', 'value3')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
```
4. 更新数据库中的数据:
```php
$sql = "UPDATE table_name SET column1='new_value' WHERE condition";
if ($conn->query($sql) === TRUE) {
echo "记录更新成功";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
```
5. 删除数据库中的数据:
```php
$sql = "DELETE FROM table_name WHERE condition";
if ($conn->query($sql) === TRUE) {
echo "记录删除成功";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
```
6. 获取当前日期和时间:
```php
$currentDateTime = date('Y-m-d H:i:s');
echo $currentDateTime;
```
7. 获取客户端IP地址:
```php
$ip = $_SERVER['REMOTE_ADDR'];
echo $ip;
```
8. 文件上传:
```php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "文件上传成功";
} else {
echo "文件上传失败";
}
```
9. 发送电子邮件:
```php
$to = "recipient@example.com";
$subject = "邮件主题";
$message = "邮件内容";
$headers = "From: sender@example.com" . "\r\n" .
"Reply-To: sender@example.com" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
if (mail($to, $subject, $message, $headers)) {
echo "邮件发送成功";
} else {
echo "邮件发送失败";
}
```
--结束END--
本文标题: 推荐9个常用的php代码
本文链接: https://lsjlt.com/news/395007.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0