简体   繁体   中英

PDO Query Showing No Results

So previously my queries were working fine. I usually use mysql but have recently changed to a pre-configured vps through godaddy. Last night I was trying to connect to my server via PDO, which is showing the connection is being made.

Next I was trying to select the data from a table using:

global $conn;
$sql = "SELECT name FROM suppliers";
$stm = $conn->prepare($sql);
$stm->execute();
return $stm->fetch();

All this shows on my website is Connection Successful, Array

It doesn't show any array information or anything, just the word "Array". The table has information in it, so it should be displaying the results. Any idea of what I am doing wrong?

You get Array because you are echoing an array. Fetch returns an array,

PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

Since you are querying a full table you probably want all the results so you should loop the fetch and return that array.

$sql = "SELECT name FROM suppliers";
$stm = $conn->prepare($sql);
$stm->execute();
while($row = $stm->fetch()) {
    $returned_array[] = $row['name'];
}
return $returned_array;

Then iterate over this where ever you are using it for all the supplier names.

foreach(function_call_for_names() as $name) {
     echo $name;
} 

Alternately, you could use the PDO fetchAll function,

$sql = "SELECT name FROM suppliers";
$stm = $conn->prepare($sql);
$stm->execute();
return $stm->fetchAll();

then

foreach(function_call_for_names() as $row) {
         echo $row['name'];
}

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