在PHP中编写SQL语句可以使用原生的SQL语句,也可以使用ORM(对象关系映射)工具来简化操作。下面分别介绍这两种方式:
使用原生的SQL语句:
<?php
// 连接数据库
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
// 查询数据
$query = "SELECT * FROM users";
$result = mysqli_query($conn, $query);
// 处理查询结果
while ($row = mysqli_fetch_assoc($result)) {
echo $row['name'];
}
// 插入数据
$query = "INSERT INTO users (name, age) VALUES ('John Doe', 25)";
mysqli_query($conn, $query);
// 更新数据
$query = "UPDATE users SET age = 30 WHERE id = 1";
mysqli_query($conn, $query);
// 删除数据
$query = "DELETE FROM users WHERE id = 1";
mysqli_query($conn, $query);
// 关闭数据库连接
mysqli_close($conn);
?>
使用ORM工具(例如Laravel的Eloquent):
<?php
// 使用Eloquent模型
use Illuminate\Database\Eloquent\Model;
// 定义User模型
class User extends Model
{
protected $table = 'users'; // 表名
protected $fillable = ['name', 'age']; // 可填充字段
}
// 查询数据
$users = User::all();
foreach ($users as $user) {
echo $user->name;
}
// 插入数据
$user = new User;
$user->name = 'John Doe';
$user->age = 25;
$user->save();
// 更新数据
$user = User::find(1);
$user->age = 30;
$user->save();
// 删除数据
$user = User::find(1);
$user->delete();
?>
使用ORM工具可以更加方便地进行数据库操作,同时也提供了更高级的功能,如关联查询、数据验证等。
上一篇:php怎么查看运行结果
下一篇:php7数据连接
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站