安卓APP图片上传服务器成功,MySQL插入记录无报错却失败求助
Hey there! Let's break down why your database insert isn't working even though the image upload succeeds—there are a few key issues in your PHP script that are causing this silence and failure:
1. Variable Scope Problem
Your $name, $phone, $type and other variables are defined outside the upload() function, but you're trying to use them inside it. PHP functions have their own isolated scope, so those variables are undefined inside upload()—meaning your SQL query is either inserting empty values or throwing a silent error (if error reporting is turned off).
2. You Never Actually Run the SQL Query
You've written the $sql string, but you never execute it with a database call like mysqli_query() or prepared statements. The database never receives your insert request at all!
3. Mismatched Column and Value Order
Looking at your INSERT statement:
- Column order:
name, donor_phone, donor_type, donor_desc, address, donor_img, token - Value order:
'$name', '$type', '$phone', '$desc', '$address', '$path', '$token'
You swapped donor_phone and donor_type—$type is being inserted into the phone column and vice versa. This could trigger validation errors (if donor_phone expects numeric values) or just store wrong data.
4. No Error Checking
You don't verify if the database connection succeeded, and you don't check if the SQL query ran correctly. Without error feedback, you can't debug what's breaking behind the scenes.
5. Critical SQL Injection Risk
Directly inserting user input into your SQL query is a massive security hole. Anyone could delete your entire database or steal sensitive data. Always use prepared statements!
Here's the fixed version of your script with all these issues resolved:
<?php $hostname = "localhost"; $username = "username"; $password = "password"; $dbname = "dbname"; // Enable error reporting for debugging (disable in production) error_reporting(E_ALL); ini_set('display_errors', 1); // Check database connection first $con = mysqli_connect($hostname, $username, $password, $dbname); if (!$con) { die(json_encode(["error" => "Connection failed: " . mysqli_connect_error()])); } if (isset($_POST['image'])) { $image = $_POST['image']; $name = $_POST['name']; $type = $_POST['type']; $desc = $_POST['desc']; $phone = $_POST['phone']; $token = $_POST['token']; $address = $_POST['address']; // Pass all required variables (including DB connection) to the upload function upload($image, $name, $type, $desc, $phone, $token, $address, $con); exit; } else { echo json_encode(["error" => "image_not_in"]); exit; } function upload($image, $name, $type, $desc, $phone, $token, $address, $con) { // Create unique image file name $now = DateTime::createFromFormat('U.u', microtime(true)); $id = $now->format('YmdHisu'); $upload_folder = "Uploads"; $path = "$upload_folder/$id.jpeg"; if (file_put_contents($path, base64_decode($image)) !== false) { // Use prepared statement to avoid SQL injection $sql = "INSERT INTO donor(name, donor_phone, donor_type, donor_desc, address, donor_img, token) VALUES(?, ?, ?, ?, ?, ?, ?)"; $stmt = mysqli_prepare($con, $sql); // Bind parameters (s = string; adjust types if needed, e.g., i for integer phone numbers) mysqli_stmt_bind_param($stmt, "sssssss", $name, $phone, $type, $desc, $address, $path, $token); if (mysqli_stmt_execute($stmt)) { echo json_encode(["success" => 1]); } else { // Return specific SQL error for debugging echo json_encode(["error" => "Database insert failed: " . mysqli_stmt_error($stmt)]); } mysqli_stmt_close($stmt); } else { echo json_encode(["error" => 2]); } } mysqli_close($con); ?>
Key Fixes Explained:
- Fixed variable scope: We now pass all required data (including the database connection) to the
upload()function so it can access them. - Executed the query: Used prepared statements (
mysqli_prepare()+mysqli_stmt_execute()) to safely run the insert request. - Corrected column-value order: Matched
donor_phonewith$phoneanddonor_typewith$typeto ensure data goes to the right columns. - Added error checking: Enabled error reporting, verified the database connection, and returned specific SQL errors if the insert fails.
- Eliminated SQL injection: Prepared statements keep user input separate from the query, removing the risk of malicious attacks.
Quick Additional Checks:
- Ensure your
donortable has all the columns you're inserting into, and their data types match your input (e.g.,donor_phoneshould accept string/phone number values). - In production, turn off
display_errorsand log errors to a file instead of showing them to users. - Double-check that your web server has write permissions for the
Uploadsfolder (you already have this working, but it's good to confirm).
内容的提问来源于stack exchange,提问作者Mona ibrahim

