0

I am trying to fetch values from a mysql query using PDO...it works with one column but I need to return 2 columns from the query. Below is the piece of code I have made...

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; 

It returns me some array values...which I really can't figure out. Can anyone please help me with this.

3
  • You want get 2 columns or 2nd column ? Commented Jan 27, 2016 at 17:57
  • @AniruddhaChakraborty...2 columns Commented Jan 27, 2016 at 17:58
  • You should add the array result also , that would help us to solve quickly Commented Jan 27, 2016 at 18:01

3 Answers 3

1

If you use fetch() with the PDO::FETCH_ASSOC style it is easy to get both columns:

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

By placing the fetch in a loop all of the rows will be returned which you can then limit as you see fit.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Add LIMIT 2 in the query , to get two sets of result :)

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); 

1 Comment

If you do not loop through the results the two rows will not be returned. Besides, the OP wanted "2 columns", not 2 rows according to their clarifying comments.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.