PHP报错:Array to string conversion,返回消息数组失败求助
Hey, let's figure out this Array to string conversion issue you're hitting. That warning points straight at your SQL line because either $user or $mdp is an array instead of a string—PHP can't automatically turn an array into a string to plug into your query, hence the notice.
1. First, fix the root cause: Check your input parameters
The problem starts when you call getHistoriqueNotification()—you're probably passing an array instead of a single string for $user or $mdp. Maybe your form uses a name like user[] (which makes $_POST['user'] an array), or you accidentally converted the variable to an array somewhere before calling this function.
Debug this quickly by adding a check at the start of your function:
var_dump($user, $mdp); exit;
If either outputs array(...), adjust how you're passing the value. For example, if it's coming from a form array, use $user = $_POST['user'][0] (or whatever index makes sense for your use case) to get the string value.
2. Critical: Fix the SQL injection vulnerability
Right now your code is wide open to SQL injection attacks—never directly interpolate user input into SQL queries. Switch to prepared statements instead, which also avoids type-related issues like this one.
Here's a revised version of your function with fixes for both the warning and security:
function getHistoriqueNotification($user, $mdp){ $com = new DbConnect(); $db = $com->getDb(); // Handle array inputs (adjust this logic based on your actual data source) if (is_array($user)) { $user = reset($user); // Grab the first element of the array } if (is_array($mdp)) { $mdp = reset($mdp); } // Use prepared statement to avoid SQL injection $sql = "SELECT UTLR_UID FROM adm_utilisateurs WHERE UTLR_LOGIN = ? AND UTLR_MDP = ?"; $stmt = mysqli_prepare($db, $sql); // "ss" tells MySQL both parameters are strings mysqli_stmt_bind_param($stmt, "ss", $user, $mdp); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); $getID = mysqli_fetch_assoc($result); if ($getID) { $userID = $getID['UTLR_UID']; // Continue with your subsequent $sqli query here... } else { // Handle case where user doesn't exist or password is wrong return []; } }
3. Bonus: Fix password storage (huge security issue!)
Storing plain-text passwords in your database is a massive no-no. You should always hash passwords using PHP's built-in password_hash() function when creating a user, and verify them with password_verify() instead of comparing plain strings. For example:
When creating a user:
$hashedPassword = password_hash($userInputPassword, PASSWORD_DEFAULT); // Store $hashedPassword in UTLR_MDP column
When verifying:
// Fetch the hashed password from the database first $hashedPassword = $getID['UTLR_MDP']; if (password_verify($mdp, $hashedPassword)) { // Password is correct, proceed }
内容的提问来源于stack exchange,提问作者k.groom

