PHP和UniApp實作資料的增刪改查的基本操作
$servername = "localhost"; $username = "root"; $password = "your_password"; $dbname = "your_database"; $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接是否成功 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); }
// 在UniApp中发送请求 uni.request({ url: 'http://your_domain.com/insert.php', method: 'POST', data: { name: 'John', age: 25 }, success: function(res) { console.log('插入成功', res.data); }, fail: function(err) { console.log('插入失败', err); } });
// 在insert.php中处理请求 $name = $_POST['name']; $age = $_POST['age']; $sql = "INSERT INTO users (name, age) VALUES ('$name', '$age')"; if ($conn->query($sql) === TRUE) { echo "插入成功"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close();
// 在UniApp中发送请求 uni.request({ url: 'http://your_domain.com/select.php', method: 'GET', success: function(res) { console.log('查询成功', res.data); }, fail: function(err) { console.log('查询失败', err); } });
// 在select.php中处理请求 $sql = "SELECT * FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { $rows = array(); while($row = $result->fetch_assoc()) { $rows[] = $row; } echo json_encode($rows); } else { echo "0 结果"; } $conn->close();
// 在UniApp中发送请求 uni.request({ url: 'http://your_domain.com/update.php', method: 'POST', data: { id: 1, name: 'John', age: 30 }, success: function(res) { console.log('更新成功', res.data); }, fail: function(err) { console.log('更新失败', err); } });
// 在update.php中处理请求 $id = $_POST['id']; $name = $_POST['name']; $age = $_POST['age']; $sql = "UPDATE users SET name='$name', age='$age' WHERE id=$id"; if ($conn->query($sql) === TRUE) { echo "更新成功"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close();
// 在UniApp中发送请求 uni.request({ url: 'http://your_domain.com/delete.php', method: 'POST', data: { id: 1 }, success: function(res) { console.log('删除成功', res.data); }, fail: function(err) { console.log('删除失败', err); } });
// 在delete.php中处理请求 $id = $_POST['id']; $sql = "DELETE FROM users WHERE id=$id"; if ($conn->query($sql) === TRUE) { echo "删除成功"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close();
以上是PHP與UniApp實作資料的增刪改查的基本操作的詳細內容。更多資訊請關注PHP中文網其他相關文章!