Transforming the output from fetchAll() into a well-

Currently, I'm utilizing fetchAll(PDO::FETCH_ASSOC) to query my self-made database using an SQL statement. In order to visualize the retrieved data, I am employing print_r(). The values returned by print_r() look like this:

Array ( [0] => Array ( [Type] => Poison, Invicibility, Heals [First_Name] => Acton [Last_Name] => Mooney ) 
        [1] => Array ( [Type] => Telepathy, Mind-Control [First_Name] => Adam [Last_Name] => Warlock )

To present this information in a well-organized table format, I aim to use a loop. For instance, I desire the following output:

         Type                          First_Name    Last_Name
Poison, Invincibility, Heals              Acton         Mooney
Telepathy, Mind-Control                  Adam          Warlock

However, I'm currently facing a challenge in implementing this. Although I understand that it involves some form of loop, the query is dynamic and can contain more than three rows of data, which complicates matters.

Answer №1

When reading the results, it is recommended to use a while loop instead of fetchAll();

$stmnt = $db->prepare($sql);
$stmnt->execute($aParams);
while($row = $stmnt->fetch()) {
    // Custom code goes here....
}
$stmnt = null;

Edit : To address the issue regarding column number and name retrieval, especially when the query can be applied to any table:

// Retrieve all results using fetchAll method
$aResults = $stmnt->fetchAll(PDO::FETCH_ASSOC)

// Check if there are any results
$numResults = count($aResults);
if (count($numResults) > 0) {
    // Output the table header
    echo '<table><tr>';
    foreach ($aResults[0] as $fieldName=>$value) {
        echo '<th>' . htmlspecialchars($fieldName) . '</th>';
    }
    echo '</tr>';

    // Output all the results
    foreach($aResults as $row) {
        echo '<tr>';
        foreach ($row as $fieldName=>$value) {
            echo '<td>' . htmlspecialchars($value) . '</td>';
        }
        echo '</tr>';
    }

    // Close the table
    echo '</table>';
} else {
    echo 'No results';
}

Answer №2

In a similar manner,

<?php 

$data = array ( 0 => array ( 'Ability' => 'Poison, Invincibility, Healing', 'First_Name' => 'Anderson', 'Last_Name' => 'Moon' ) ,
        1 => array ( 'Ability' => 'Telepathy, Mind Control', 'First_Name' => 'Adrian', 'Last_Name' => 'Willow' )) ;

echo "<table><tr><th>Ability</th><th>Ability</th><th>Ability</th></tr>";

foreach ($data as $k=>$v) {
    echo "<tr>";
    echo "<td>".$v['Ability']."</td>";
    echo "<td>".$v['First_Name']."</td>";
    echo "<td>".$v['Last_Name']."</td>";
    echo "</tr>";
}        
echo "</table>";      

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to decode JSON string, returning null

I am having trouble passing this JSON string to my query xxxxxx=createVenue&clientId=2&jsonString={"veneue":{"clientId":"b","name":"d","tagline":"f","phone":"b","address":"d","city":"f","state":"b","zip":"d","twitter":"f","license":"d","imagePath" ...

Mastering Regular Expressions with PHP

Hello, I am currently working on creating a Regular Expression that will replace any word enclosed in pound signs (#) with a URL. I want it to function similar to Twitter hashtags, but my current expression only works for English words. If a post is made ...

How can a variable be passed to route.php from middleware in Laravel 5.2?

I have created a middleware and I need it to pass the variable $role to the route.php file. public function handle($request, Closure $next) { if ($this->auth->check()) { $role= "normal"; $user_roles = AssignedRoles::join(&ap ...

Can PHP be utilized to convert an XML file to UTF-8 encoding?

I have encountered an XML document that is encoded in ITF-16 LE, making it unreadable in wp all import. Upon investigating the version section, I found this: <?xml version="1.0" encoding="Unicode" ?> Additionally, in my visual studio code, I notice ...

Minor login form mishap

I am currently working on creating a compact login form where users need to input their username and password. If the entered credentials match those stored in the database, they will be directed to the home page. Here's my progress so far: <html ...

The comparison between AJAX and JSON passing and PHP generating HTML versus returning it

Currently, my code looks like this: <li onclick = " function CBAppData( callerObj, data ) { var string = ''; for( a in data ) { debug.push( data[ ...

The AJAX request to send data to PHP is not functioning correctly

I have an issue where I am trying to send data to my server using AJAX in PHP. Even though I have set the method as POST, it seems to be executing as a GET request instead. Here is the code snippet: $.ajax({ type: 'POST', data: { user: us ...

Unlocking the Potential of MySQL SELECT: Step-by-Step Guide to Crafting

Suppose I perform a SELECT query using the column alias "b" that does not exist in the table. Will the query create a virtual column? In reality, what I actually want is to include a virtual column within the query itself and manipulate certain data in or ...

Can the .htaccess files be merged together?

Currently, I am facing the challenge of overhauling an existing website that is riddled with spaghetti code and relies on rewrite rules to create friendly URLs. Unfortunately, there are critical issues within the architecture and database structure that c ...

Switch between selecting every group of 3 items and every group of 4 items

Having an array with more than 14 items, I need to group them into 2 different groups in this specific way: The first 3 (#1,2,3) will be in array A, the next 4 (#4,5,6,7) will be in array B, the following 3 (#8,9,10) will be in array A, the subsequent 4 (# ...

Implementing Ajax image upload functionality in Symfony2 framework

I am trying to implement a functionality where clicking on an image opens a window to select a new image and update the screen. However, when attempting to change the picture in the database, I encountered the following error: Catchable Fatal Error: Arg ...

PHP Function - rounding numbers to two decimal places

Do you have a moment for a question? Here is the function in question: function clean_num($num){ return trim(trim($num, '0'), '.'); } The current functionality removes .00 from numbers like 85.00 and 55.00, and returns 85 and 55. ...

unable to access submitted data

I am working with some PHP code where I am retrieving post values from a form- <?php $file="data.xml"; $test= new SimpleXMLElement($file, null, true); echo $_POST['question1']; echo $test->easy->question[0]->key; echo $test->easy- ...

Indentation differences between PHP and JavaScript

It's interesting to observe the different indentation conventions in various programming languages. Recently, I came across a code snippet from the PHP manual that caught my attention: switch ($i) { case "apple": echo "i is apple"; ...

A search form utilizing prepared statements in mysqli

Well met again, everyone. I recently reached out for help on improving some messy code I had put together, and the response was swift. Thank you for that! You can find the original question thread here: PHP - Search database and return results on the sam ...

Display a message after serializing JSON in my cakePHP application

Is there a way to append something at the conclusion of the cakePHP json/xml output? This is necessary for incorporating JSONP capability (Since I must insert the callback at the start and ');' at the end) This is how the controller is set up: ...

Setting up Opencart version 1.5.x using PHP 7

After recently starting to use OpenCart for the first time, I encountered a strange issue while attempting to install version 1.5.4 on my computer. Although I searched for a solution in various forums, I found that the community support for OpenCart is not ...

Issue with adding to lightbox feature when loading content dynamically using AJAX PHP is not functioning as expected

Hey there! I've encountered an interesting issue with my code that adds models to a lightbox. It's functioning perfectly on static pages like this one. $scope.add = function(permalink, post_id) { if (typeof(Storage) !== "undefined") { ...

Kartik's gridview in yii2 has a unique feature where the floating header in the thead and tbody are

I'm looking to create a table gridview with a floating header, where the tbody and thead are not the same. The image appears after refreshing the page, before the modal is refreshed. After refreshing the modal, this modal is inside pjax and it sets t ...

PHP is unable to detect the query string when using RewriteRule

Here is how my .htaccess file is set up: RewriteEngine On RewriteRule ^api/([^/]*)$ /api.php?method=$1 [L,QSA] This is the contents of my api.php: class API { public function __construct() { require_once('helpers.php'); } ...