Ionic搜索页如何通过PHP脚本结合AuthService返回搜索结果?
Hey there! Let's walk through getting your search functionality working smoothly. Since you already have a working AuthService for database connections, we can build right on top of that to implement the search feature. Here's a step-by-step breakdown:
First, we'll extend your existing AuthService with a method that sends search requests to your PHP backend. This method will handle passing the search term and ensuring your user session is validated.
import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; @Injectable() export class AuthService { private apiBaseUrl = 'http://your-domain.com/api/'; // Replace with your PHP API path constructor(private http: Http) {} // Your existing method to fetch session user data (kept for reference) getCurrentUser(): Observable<any> { return this.http.get(`${this.apiBaseUrl}get-user.php`) .map(res => res.json()); } // New search method to fetch results from PHP searchItems(searchTerm: string): Observable<any[]> { // Set up headers to handle form data and pass session credentials const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); const options = new RequestOptions({ headers: headers, withCredentials: true // Ensures session cookies are sent for user validation }); // Encode the search term to avoid URL issues const body = `search_term=${encodeURIComponent(searchTerm)}`; // Send POST request to your PHP search endpoint return this.http.post(`${this.apiBaseUrl}search.php`, body, options) .map(res => res.json()); } }
Note: If you're using Angular's newer HttpClient (Angular 4.3+), adjust the code to use HttpParams instead of manual form encoding—this is cleaner and more secure.
Next, create a PHP script that connects to your database, validates the user session, and returns matching search results as JSON. Make sure to use prepared statements to prevent SQL injection!
<?php session_start(); // First, validate the user is logged in (match your existing AuthService logic) if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['error' => 'Unauthorized access']); exit; } // Database connection details (replace with your own) $servername = 'your-db-host'; $dbUsername = 'your-db-username'; $dbPassword = 'your-db-password'; $dbName = 'your-db-name'; // Connect to database using mysqli (use PDO if that's your preference) $conn = new mysqli($servername, $dbUsername, $dbPassword, $dbName); if ($conn->connect_error) { die(json_encode(['error' => 'Database connection failed: ' . $conn->connect_error])); } // Get the search term from the request $searchTerm = isset($_POST['search_term']) ? trim($_POST['search_term']) : ''; // Prepare and execute a safe search query (replace table/column names with your own) $sql = "SELECT * FROM your_target_table WHERE column_to_search LIKE ?"; $stmt = $conn->prepare($sql); $likeTerm = "%{$searchTerm}%"; // Add wildcards for partial matches $stmt->bind_param("s", $likeTerm); $stmt->execute(); $result = $stmt->get_result(); // Collect results into an array $searchResults = []; while ($row = $result->fetch_assoc()) { $searchResults[] = $row; } // Return results as JSON header('Content-Type: application/json'); echo json_encode($searchResults); // Clean up connections $stmt->close(); $conn->close(); ?>
Now, wire up the SearchPage to handle user input, call the AuthService search method, and render the results.
SearchPage TypeScript (search.ts)
import { Component } from '@angular/core'; import { AuthService } from '../../services/auth.service'; // Adjust path to your AuthService @Component({ selector: 'page-search', templateUrl: 'search.html', }) export class SearchPage { searchTerm: string = ''; dataSet: any[] = []; constructor(private authService: AuthService) {} // Trigger search on input change (real-time search) onSearchInput() { if (this.searchTerm.trim() === '') { this.dataSet = []; return; } this.authService.searchItems(this.searchTerm) .subscribe( (results) => { this.dataSet = results; }, (error) => { console.error('Search failed:', error); // Add user feedback here (e.g., an Ionic toast) } ); } }
SearchPage HTML (search.html)
<ion-header> <ion-navbar> <ion-title>Search</ion-title> </ion-navbar> </ion-header> <ion-content padding> <!-- Search bar --> <ion-searchbar [(ngModel)]="searchTerm" (ionInput)="onSearchInput()" placeholder="Type to search..."> </ion-searchbar> <!-- No results message --> <div *ngIf="dataSet.length === 0 && searchTerm.trim() !== ''" class="no-results"> <p>No matching results found.</p> </div> <!-- Search results (your existing card structure) --> <ion-card *ngFor="let item of dataSet; let msgIndex = index"> <ion-card-header> {{ item.title }} <!-- Replace with your data field --> </ion-card-header> <ion-card-content> {{ item.description }} <!-- Replace with your data field --> </ion-card-content> </ion-card> </ion-content>
- CORS Handling: If your Ionic app and PHP server are on different domains, add CORS headers to your PHP script (or use Ionic's proxy configuration for development):
header("Access-Control-Allow-Origin: http://your-ionic-app-url"); header("Access-Control-Allow-Credentials: true"); - Data Structure: Ensure the PHP script returns a JSON array of objects—this matches how you're iterating over
dataSetin your template. - Security: Always use prepared statements in PHP to prevent SQL injection, and validate user sessions before processing any requests.
内容的提问来源于stack exchange,提问作者user5312962

