简体   繁体   English

如何使用php从mysql数据库中检索所有数据?

[英]How to retrieve all data from mysql database using php?

I have a another php file that has the function to connect to the database (does so successfully) and also a function getEvent that contains the sql statement. 我有另一个php文件,它具有连接数据库的功能(这样做成功),还有一个包含sql语句的函数getEvent。 The code below successfully retrieves one data row from the database but i need it to return all data from the table. 下面的代码成功从数据库中检索一个数据行,但我需要它从表中返回所有数据。

<?php
// include db connect class
require_once 'include/DB_Functions.php';

// connecting to db
$db = new DB_Functions();

 // array for JSON response
$response = array();

// get all events from events table
$event = $db->getEvent();

// check for empty result
if($event !=FALSE){


    $response["error"]=FALSE;
    $response["uuid"] = $event["eventID"];
        $response["eventdetails"]["title"] = $event["title"]; 

echo json_encode($response);

}else{
$response["error"]=TRUE;
$response["error_msg"] = "No events to display";
        echo json_encode($response);
}

?>

the getEvent method getEvent方法

public function getEvent(){ 
    $stmt= $this->conn->prepare("SELECT * from eventdetails"); 
    $stmt->execute(); 
    $event= $stmt->store_result(); 
    if ($stmt->execute()) { 
        $event = $stmt->get_result()->fetch_assoc(); 
        $stmt->close(); 
        return $event; 
    } else { 
        // events dont existed 
        $stmt->close(); 
        return null; 
    }

If youwant to return an array containing all the results from a query then use the fetchAll() method of the PDOStatement Class 如果您想返回包含查询中所有结果的数组,请使用PDOStatement类的fetchAll()方法

public function getEvent(){ 

    $stmt = $this->conn->prepare("SELECT * from eventdetails"); 
    $stmt->execute(); 
    $events = $stmt->fetchAll(); 
    return $events;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM