Present data extracted from MySQL

Currently, my code retrieves data from a MySQL table and displays it on the page in a single line. However, I want to present this information in separate blocks. Is there a way to split the line and create distinct blocks of information that can be placed anywhere on the webpage?

<?php
while ($row = mysql_fetch_array($query)) {
echo $row['Column A'] . " " . $row['Column B'] . " " . $row['Column C'] . " ";
} ?>

Answer №1

Firstly, it's important to update your mysql_* functions to more modern alternatives like PDO & mysqli.

Now, let's discuss how you can generate HTML from your database data. There are several approaches you can take:

One possible method is as follows:

<?php
while ($row = mysql_fetch_array($query)) {
?>
<h1><?php echo $row['columnA']; ?></h1>
<div class="myclass"><?php echo $row['columnb']; ?></div>
<img src="<?php echo $row['columnC']; ?>">
<?php
} ?>

Another approach could be:

<?php
    while ($row = mysql_fetch_array($query)) {
    $str = ""; 
    $str .= "<h1>".$row['columnA']."</h1>"; 
    $str .= '<div class="myclass">'.$row['columnb'].'</div>'; 
    $str .= '<img src="'.$row['columnC'].'">'; 
    echo $str; 
    <?php
    } ?>

Alternatively, you can simplify the process by using a framework that handles this for you.

If you prefer not to use a framework, you can utilize a templating library which offers the best solution.

I recommend checking out mustache https://github.com/bobthecow/mustache.php for this purpose.

You have the flexibility to modify the HTML structure based on your requirements.

I hope these suggestions prove helpful in resolving your query. Happy coding!

Answer №2

A possible solution for your needs could be a table implementation... (Keep in mind to switch over to mysqli* as suggested by @Sedz)

<table border="1">
    <?php
        while ($row = mysqli_fetch_array($query)) {
            echo '<tr>';
                echo '<td>' . $row['Column A'] . '</td>';
                echo '<td>' . $row['Column B'] . '</td>';
            echo '</tr>';
            echo '<tr>';
                echo '<td></td>';
                echo '<td>' . $row['Column C'] . '</td>';
            echo '</tr>';
        };
    ?>
</table>

Adjust the display layout according to your preferences...

Answer №3

One possible approach is to store the results in an array:

$resultArray = array(); 

while ($row = mysql_fetch_assoc($results)) {
    $resultArray[] = $row;
}

To address the issue you mentioned:

foreach ($resultArray as $item) {
    echo "$item<br>";
}

Answer №4

Hello user2619310!

Here's what you can do to solve your issue:

You need to insert the newline character "\n" into your code.

<?php
while ($row = mysql_fetch_array($query)) {
      echo $row['Column X'] . " " . $row['Column Y'] . " " . $row['Column Z'] . "\n";

} 
?>

Good luck! :-)

Answer №5

There are various ways to format the lines depending on your goals and where you plan to use them. These are some methods for organizing information on separate lines:

  1. Add a line break (br) tag at the end of each field.
  2. Enclose each row in DIVs.
  3. Create a table for each row.

If you need compatibility across different browsers and efficient sizing, using DIVs would be the optimal choice. However, tables can also be easily implemented for specific purposes.

Here is an example of how I would organize the rows using tables:

<table>
    <?php while ($row = mysql_fetch_array($query)): ?>
    <tr>
        <td>Label for Column A</td>
        <td><?php echo $row['ColumnA']; ?></td>
    </tr>
    <tr>
        <td>Label for Column B</td>
        <td><?php echo $row['ColumnB']; ?></td>
    </tr>
    <tr>
        <td>Label for Column C</td>
        <td><?php echo $row['ColumnC']; ?></td>
    </tr>
    <?php endwhile; ?>
</table>

I am not familiar with your specific database table structure, but based on the information provided, I have included an example. Please note that this is untested but should work.

Additionally, take note of the alternative PHP syntax for the while loop.

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

What is the process for updating a collection in MongoDB database with PHP?

After writing a code snippet to gather user input through a form and update a collection based on the entered product ID, I am encountering issues with incorrect results. It seems that I am unable to fetch the correct product ID value, which is causing t ...

saving data from database for future utilization in php

I'm struggling to retrieve data from a table in an MSSQL database and I need to save the information from 2 specific columns for future use. Below is the code snippet that I have written: <?php $conn = sqlsrv_connect( $serverName, $connectionInfo) ...

Enhancing a php SOAP complex datatype by incorporating an XML wrapper

In my nusoap server file, I am currently utilizing the following code snippet: $server->wsdl->addComplexType( 'member', 'complexType', 'struct', 'all', '', array( &apo ...

Ask the controller for information, then send it to the appropriate route before displaying it in

Within my HomeController, there is a method that requires specific arguments to function properly. public function mcQuery($ip, $port){ $Query = new MinecraftQuery(); try { $Query->Connect( $ip, $port ); return ...

Save array in JSON format to a file using PHP

I'm in need of assistance as I am fairly new to working with JSON and PHP. Any guidance or tips would be greatly appreciated. Currently, I have a PHP file with the following code snippet: $data = print_r($_POST, TRUE); file_put_contents('api3. ...

Is there a concept similar to HTTP_GET_RESPONSE out there?

I am intrigued by the idea of fetching the result from this URL () which returns "DE", and storing it in a variable to be used for writing into my database. I have no problem with the latter part, but I would appreciate guidance on how to accomplish the fo ...

Cross-class function retrieval results in failure of database interactivity

In my login session, I have a function within my login class that retrieves user information, specifically the user_id. This is crucial for identifying users in my database. Now, I'm attempting to access this function from another class, my Login cla ...

Tips for showcasing an array in PHP with either JSON or XML structure?

I am currently working on creating an API web service using PHP. My goal is to display all the records from my database table in both JSON and XML formats using arrays. However, I am facing an issue where only one record is being displayed or receiving a r ...

Synchronize the Android database with a remote server database

I am currently developing an Android app that utilizes two databases. My goal is to synchronize these databases with two identical databases on a web server, ensuring they have the same field structure and field names. Before syncing, I need to access info ...

Determine the remaining load time in PHP after submitting a task

Is there a way to incorporate a progress bar that displays the percentage while "preparing the next page" before redirection? I have successfully implemented the progress bar animation, but now I am looking for an approximation of the time it will take be ...

Looking to utilize PHP's foreach loop to generate XML elements and attributes based on information from another XML file

After extracting specific attributes from an XML document (traffic.xml) using PHP, I created a new PHP file (drivetimeFetch.php) to process the data. Now, my goal is to generate another XML document (carousel_Traffic.xml) based on the content of drivetimeF ...

Extracting Data from JSON Objects Using PHP

array(85) { [0]=> object(stdClass)#9 (18) { ["offer_id"]=> string(8) "12345678" ["offer_name"]=> string(39) "Offer Name" ["offer_desc"]=> string(209) "Offer Description" ["call_to_action"]=> string(57) "Of ...

Data from Ajax calls is only available upon refreshing the page

I am working on adding a notification button for inactive articles on my blog. I want to use AJAX so that the admin does not have to reload the page to view newly submitted inactive articles. I am trying to prepend HTML data to: <ul id="menu1" class= ...

Error in PHP class: Wikipedia - index out of bounds

I am new to PHP and encountering an undefined offset issue in my php class. Could someone please assist me with this? The error is currently on line 28, but there might be more errors present. The specific error message I'm seeing is: Notice: Und ...

Combining ID's from two MySQL tables to generate results from one table into the other

Despite attempting various examples and browsing through stackoverflow for answers, I am still struggling to achieve my goal. I am currently developing a PHP/MySQL tool to monitor projects. To improve performance, I decided to store IDs in the Project tab ...

Enter a number into a text box and increase the value in several text boxes created with jQuery in PHP

I need to dynamically populate textboxes with student information from a database after inputting a value, for example 100, and clicking on the 'Add' button. The challenge is to incrementally assign values to each textbox based on the initial num ...

Handling PHP forms: verifying data, submitting entries, and presenting information

Over the past few days, I've been attempting to customize a PHP form that I came across on the web. It seems quite popular based on the numerous posts about it. The form successfully sends me an email upon submission, which is great. However, there ar ...

Using the WordPress function wp_mail along with Ajax and ValidationEngine to perform database insertion through the $wpdb object

Seeking guidance on a complex issue, I present a query regarding a contact form integrated within my home.php file. The code structure is as follows: HTML: <form id="js-calculator" name="calculator" action="" method="post"> <input type="ema ...

Articulate junction table featuring distinct column titles

Data Tables for Users: User ID: 1 User Name: John Doe Visits Table Details: Visit ID: 123 User ID: 1 Viewer ID: 456 In order to retrieve a list of visits with the associated username for user ID 1, I used the following code: $visits = \Visits::wh ...

Verify the presence of the promotion code and redirect accordingly

I have created a special promotion page that I want to restrict access to only users who have received a unique code from me via email. To achieve this, I have designed the following form: <form accept-charset="UTF-8" action="promotion.php" method="po ...