dounie5475 2017-04-15 23:56
浏览 17
已采纳

为什么PHP中的SQL查询失败?

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.

  • 写回答

2条回答 默认 最新

  • dtbrd80422 2017-04-16 02:08
    关注

    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)) {.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了