简体   繁体   English

PDO查询显示无结果

[英]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. 我通常使用mysql,但最近已通过godaddy更改为预配置的vps。 Last night I was trying to connect to my server via PDO, which is showing the connection is being made. 昨晚我试图通过PDO连接到服务器,这表明正在建立连接。

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". 它不显示任何数组信息或任何内容,仅显示单词“ 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. 之所以得到Array是因为您正在回显数组。 Fetch returns an array, Fetch返回一个数组,

PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set PDO :: FETCH_BOTH(默认值):返回一个在结果集中返回的同时由列名和0索引的列号索引的数组

Since you are querying a full table you probably want all the results so you should loop the fetch and return that array. 由于查询的是完整表,因此可能需要所有结果,因此应循环进行fetch并返回该数组。

$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, 或者,您可以使用PDO fetchAll函数,

$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'];
}

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

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