pdo语句在php中返回超过1列

时间:2016-01-27 17:54:55

标签: php pdo

我正在尝试使用PDO从mysql查询中获取值...它适用于一列,但我需要从查询中返回2列。以下是我所制作的一段代码......

try {
      $conn = new PDO('mysql:host=localhost;dbname=****', 'root', '****'>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
      echo 'ERROR: ' . $e->getMessage();
    }
    $sth = $conn->prepare("select  distinct prod_url,ean from tab_nl where ean in (select ean1 from test_sku where sku='$sku') and prod_url like '%prijzen%'");
$sth->execute();

$urlsku = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
$urlean = $sth->fetchAll(PDO::FETCH_COLUMN, 1);
echo $sku;
echo $urlsku;
echo $urlean;

它返回了一些数组值...我真的无法弄清楚。任何人都可以帮助我。

3 个答案:

答案 0 :(得分:3)

如果您使用fetch()样式PDO::FETCH_ASSOC,则很容易获得两列:

while($row = $sth->fetch(PDO::FETCH_ASSOC) {
    echo $row['prod_url'];
    echo $row['ean'];
}

通过将获取放在一个循环中,将返回所有行,然后您可以根据需要进行限制。

答案 1 :(得分:0)

$data = $sth->fetchAll(PDO::FETCH_ASSOC);
echo $data[0]['prod_url'];
echo $data[0]['ean'];

答案 2 :(得分:0)

在查询中添加LIMIT 2,以获得两组结果:)

try {
        $conn = new PDO('mysql:host=localhost;dbname=****', 'root', '****'>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    $sth = $conn->prepare("select  distinct prod_url,ean from tab_nl where ean in (select ean1 from test_sku where sku='$sku') and prod_url like '%prijzen%' LIMIT 2");
$sth->execute();

$urlsku = $sth->fetchAll(PDO::FETCH_ASSOC, 0);
$urlean = $sth->fetchAll(PDO::FETCH_ASSOC, 1);
print_r($urlsku);
print_r($urlean);