Why is my SQL query in PHP failing?

I have a PHP function that should return a database query:

function editprojectform(){
  global $conn;

  if(isset($_POST['project_id'])){
    $project_id = $_POST['project_id']; 
    $sql = "SELECT * FROM projects WHERE Project_ID=".$project_id;
      if ($conn->query($sql) === TRUE) {
        echo "It works";
      } else {
          echo "Error: " . $sql . "<br>" . $conn->error;
      }
  }
}

However it is printing out the error instead of printing out the project name:

Error: SELECT * FROM projects WHERE Project_ID=3

I can copy and paste this exact query into PHPadmin and it returns the expected result. I am trying to work out why it is not working here? I have a very similar function that deletes a record and it works fine.

Thank-you.


I'm assuming you are using mysqli::query. If you read the documentation, particularly the return values section, it states that

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

Therefore, since you are using a SELECT statement, the function will either return FALSE or an object which both are not identical ( === ) to TRUE. So, it will always fail.

Unlike a SELECT statement, if you use a DELETE statement, the function will only return TRUE or FALSE. So depending on what type of statement you have, the function will return different values.

Simply follow the example in the documentation and replace your IF statement with if ($result = $conn->query($sql)) { .


在这种情况下,最好使用PDO。

$db = $pdo->prepare('SELECT FROM projects WHERE Project_ID=:Project_ID');
$db->bindParam(':Project_ID', $project_id);
$db->execute();
$res = $db->fetchAll();

var_dump($res)
链接地址: http://www.djcxy.com/p/58606.html

上一篇: 在php if语句中使用===

下一篇: 为什么我在PHP中的SQL查询失败?