简体   繁体   中英

Using PHP/PDO To Store/Select Rows From Multiple Tables

I know how to select rows from a single table and store in an array:

<?php
    include "db.php";
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "SELECT * from chars";
    $stmt = $conn->prepare($sql);
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $bows = array();
    if ($stmt) {
        try {
            $stmt->execute();
            while ($row = $stmt->fetch()) {
                $chars[] = $row;
            }
        }
        catch (PDOException $e) {
            var_dump($e);
        }
    }
?>

But how do I do this if I have multiple tables, ie. chars , items , bases , etc. and I want to use different select queries for each and store in different arrays?

Edit: the tables have no related fields.

If you are just looking to store the results of multiple queries in different arrays, do the same thing you are doing now with different queries and arrays. If you are grabbing data across tables, depending on what you need, you may be able to modify your query to use joins.

If the tables are completely unrelated, and you want to fetch all the data from all of them into three separate arrays, you will need three separate select statements.

If the tables are related, you can use JOIN.

For example, if table items has column id , and table bases has column *item_id* , which refers to id column in items, you can get combined data with:

 SELECT * from items
 INNER JOIN bases ON items.id=bases.item_id;

Is this what you are looking for? If not, please provide more info, and I will revise my answer.

Just use the same approach you are using, at the moment, but without all that useless code:

<?php
include "db.php";

$stmt = $conn->prepare("SELECT * from chars");
$stmt->execute();
$chars = $stmt->fetchAll();

$stmt = $conn->prepare("SELECT * from items WHERE id=?");
$stmt->execute(array($id));
$item = $stmt->fetch();

$stmt = $conn->prepare("SELECT name FROM bases WHERE id=?");
$stmt->execute(array($id));
$base = $stmt->fetchColumn();

and so on

You can write a function

<?php
include "db.php";
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

function getArr($vartable) {
  global $conn;
  $sql = "SELECT * from ".$vartable;
  $stmt = $conn->prepare($sql);
  $stmt->setFetchMode(PDO::FETCH_ASSOC);
  $ars = array();
  if ($stmt) {
    try {
        $stmt->execute();
        while ($ars[] = $stmt->fetch());
    }
    catch (PDOException $e) {
        var_dump($e);
    }
  }
return $ars;
}

$chars = getArr("chars");
$items = getArr("items");
$bases = getArr("bases");

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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