0

This is the structure in the database:

items    |itemLink
----------------------
Kill Bill|Kill Bill link
Preman   |Preman link

This is the code:

$db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);

            $items = 'SELECT items FROM menus';
            $itemLink = 'SELECT itemLink FROM menus';

            $itemQuery = $db->query($items);
            $linkQuery = $db->query($itemLink);

            $fetchItem = $itemQuery->fetchAll(PDO::FETCH_ASSOC);
            $fetchLink = $linkQuery->fetchAll(PDO::FETCH_ASSOC);

            $merged = array_merge($fetchItem,$fetchLink);

            foreach($merged as $entry) {
            foreach( $entry as $key => $value ) {

          }
        }

From the above code, how do I output only the items' datas?

4
  • Why do you run two separate queries?
    – kapa
    Mar 8, 2012 at 10:30
  • Just for experimental purposes... Mar 8, 2012 at 10:31
  • I would replace foreach( $entry as $key => $value ) {} with $entry['items'] otherwise you will need to do a if($key=='items') in that inner loop.
    – ghbarratt
    Mar 8, 2012 at 10:35
  • Do some var_dumps how the array or variable looks like, eg. $value['Items']['items']. The first one is the db the second one is the column.
    – craphunter
    Mar 8, 2012 at 10:41

2 Answers 2

1

Using the example above you could then do something like this to answer you question

        $result = mysql_query('Select * from names');
        while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
           echo $row["FirstName"] . " " . $row["LastName"] . "<br>";
        }

        mysql_close($conn);
        ?>
0

I would use something like this, not two arrays for something that could be one query. I have shown three methods, using var_dump or print_r will show how each works.

$conn = mysql_connect($hostname, $username, $password);
        if (!$conn) {
            die('Could not connect to MySQL: ' . mysqli_connect_error());
        }
        $db_selected = mysql_select_db('sample', $conn);
        if (!$db_selected) {
            die("Can\t use db : '  . mysql_error()");
        }
        $result = mysql_query('Select * from names');
        while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
            print_r($row);
        }
        $result = mysql_query('Select * from names');
        while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
            print_r($row);
        }
        $result = mysql_query('Select * from names ');
        while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
            print_r($row);
        }
        mysql_close($conn);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.