You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP PDO查询返回bool(false),疑因输入误操作或Ubuntu系统导致

Troubleshooting bool(false) from PDO fetch() and Fixing Your Code

First off, that bool(false) result from $sql->fetch() almost always means one of two things: either your query didn't match any records in the customers table, or there was an error executing the query that you didn't catch. Let's walk through fixing your code and ruling out issues.

Key Issues in Your Current Code

Let's break down the problems that are likely causing this:

  • SQL Injection Risk & Wrong Prepared Statement Usage: You're using prepare() but still concatenating $custID directly into the SQL string. This defeats the purpose of prepared statements and exposes you to SQL injection. You need to use parameter binding instead.
  • Uninitialized Variables: When the page loads without a POST request (like the first time), $custID and $result aren't defined. This will throw PHP warnings when you try to echo them in the form.
  • Case Sensitivity Mismatch: In your query you select CustZip, but later you try to access $result['Custzip'] (lowercase 'z'). Depending on your database's collation, this might return null or break your output.
  • Lack of Error Handling: PDO doesn't throw exceptions by default, so if your query fails (e.g., typos in column names), you won't see an error message to debug what's wrong.

Fixed Code with Explanations

Here's the revised code that addresses all these issues:

<?php
// Enable full error reporting during development to catch hidden issues
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include your validation file if needed
// include ('includes/validation.php');
include ('includes/validationmysql.php');

// Initialize variables to avoid undefined variable warnings
$custID = '';
$result = [];

try {
    // Initialize PDO with exception-based error handling
    $dbh = new PDO('mysql:host=localhost;dbname=sales', $dbuser, $dbpass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Opened database successfully<br>";
} catch(PDOException $e) {
    die("Error : Unable to open database: " . $e->getMessage());
}

if(isset($_POST["custID"])){
    $custID = trim($_POST["custID"]); // Trim whitespace to avoid accidental no-matches
    
    // Proper prepared statement with parameter binding
    $sql = $dbh->prepare("SELECT CustFirstName, CustLastName, CustAddress, CustCity, CustState, CustZip, CustCellPhone FROM customers WHERE custID = :custID");
    $sql->bindParam(':custID', $custID, PDO::PARAM_INT); // Bind as integer if custID is numeric
    $sql->execute();
    
    $result = $sql->fetch(PDO::FETCH_ASSOC);
    
    // Debug outputs (remove these in production)
    var_dump($custID);
    var_dump($result);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Figure It Out</h1>
<form action="" method="post">
<p>CustomerID <input type="text" name="custID" value="<?php echo htmlspecialchars($custID); ?>" size="5"><input type="submit" name="submit" value="submit"></p>
<textarea>
<?php
// Only echo content if we have a valid result to avoid errors
if(!empty($result)) {
    echo $result['CustFirstName']. ' ' . $result['CustLastName']. "\n";
    echo $result['CustAddress']. "\n";
    echo $result['CustCity']. ' ' . $result['CustState']. ' ' . $result['CustZip']. "\n"; // Fixed case for CustZip
    echo $result['CustCellPhone'];
}
?>
</textarea>
</form>
</body>
</html>

What Changed:

  1. Error Reporting: Enabled full error reporting to catch warnings and errors you might have missed during testing.
  2. Variable Initialization: Set default values for $custID and $result to avoid undefined variable warnings when the page first loads.
  3. PDO Error Mode: Configured PDO to throw exceptions, so you'll get clear error messages if there's a connection or query problem.
  4. Safe Prepared Statement: Used a placeholder :custID and bindParam() to safely pass the customer ID, eliminating SQL injection risk.
  5. Trimmed Input: Added trim() to clean up accidental spaces in the input that might cause no matching records.
  6. Case Correction: Fixed the typo in $result['Custzip'] to match the column name CustZip from your query.
  7. Conditional Output: Wrapped the textarea content in a check to avoid trying to access array keys when no result exists.

Is Ubuntu 18.10 the Problem?

Almost certainly not. Your earlier issue with the accidental http://sales/form2.php input was just a temporary user error—once you corrected the input, the code worked, which confirms the system itself isn't the root cause. The bool(false) result you're seeing is due to the code issues we fixed above, not your OS.

Next Steps to Debug:

  • If you still get bool(false) after using the fixed code, double-check that the custID you're entering actually exists in the customers table.
  • Verify your database collation settings to ensure column names are matched correctly (though we fixed the case issue already).
  • Check the debug var_dump($custID) to make sure the value being passed is exactly what you expect (no extra spaces, correct data type).

内容的提问来源于stack exchange,提问作者user4727065

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:49:46