SELECT DATOS FETCH API GET JSON API MYSQL PDO PHP TABLE HTML

 

.then(response => response.json()) Fetch API get json api select data mysql pdo php table html

Sure, here's an example of how to use .json() to parse the response from a Fetch API GET request to a PHP script that selects data from a MySQL database and generates an HTML table:

 

javascript

Copy code

// Get the table element

const table = document.querySelector('#my-table');

 

// Send a GET request to the PHP script

fetch('select.php')

  .then(response => response.json())

  .then(data => {

    console.log(data);

    // Generate an HTML table from the retrieved data

    const rows = data.map(item => `<tr><td>${item.id}</td><td>${item.name}</td><td>${item.email}</td></tr>`);

    const html = `<table><thead><tr><th>ID</th><th>Name</th><th>Email</th></tr></thead><tbody>${rows.join('')}</tbody></table>`;

    table.innerHTML = html;

  })

  .catch(error => console.error(error));

The above code sends a GET request to a PHP script called select.php, which is expected to return a JSON array of objects containing the selected data. The response is then parsed using the .json() method.

 

Next, create the select.php script to select data from the MySQL database and send it back to the client as a JSON array:

 

php

Copy code

// Replace the variables with your MySQL database credentials

$host = 'localhost';

$dbname = 'your_database_name';

$username = 'your_mysql_username';

$password = 'your_mysql_password';

 

// Create a PDO instance and set the error mode to exception

try {

    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch(PDOException $e) {

    echo "Connection failed: " . $e->getMessage();

    exit;

}

 

// Prepare a statement to select data from the database

$stmt = $pdo->prepare('SELECT id, name, email FROM your_table_name');

$stmt->execute();

 

// Fetch the rows and send them back to the client as a JSON array

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($rows);

The above code selects all rows of data from a MySQL table called your_table_name and sends them back to the client as a JSON array of objects. You should replace the database credentials and table name with your own. The client-side JavaScript code generates an HTML table from the retrieved data and inserts it into the table element.


.then(response => response.json()) Fetch API post json api select data mysql pdo php include the table edit button and delete button

Sure, I can provide an example of using the Fetch API to POST JSON data to an API endpoint, selecting data from a MySQL database using PDO in PHP, and including an edit button and delete button in a table.

 

First, let's start with the PHP code to select data from the MySQL database using PDO:

 

php

Copy code

<?php

 

// Establish a connection to the database

$dbh = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

 

// Select all rows from the "mytable" table

$stmt = $dbh->query('SELECT * FROM mytable');

 

// Loop through the rows and store them in an array

$rows = array();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

    $rows[] = $row;

}

 

// Encode the array as JSON and output it

echo json_encode($rows);

 

?>

Next, let's create a table in HTML to display the data and include edit and delete buttons for each row:

 

php

Copy code

<table>

    <thead>

        <tr>

            <th>Column 1</th>

            <th>Column 2</th>

            <th>Actions</th>

        </tr>

    </thead>

    <tbody id="table-body">

        <!-- Data rows will be dynamically added here using JavaScript -->

    </tbody>

</table>

Then, we can use the Fetch API to retrieve the data from the API endpoint and dynamically add it to the table in the HTML document:

 

php

Copy code

<script>

 

// Retrieve the data from the API endpoint

fetch('/api/myendpoint')

    .then(response => response.json())

    .then(data => {

        // Loop through the data and add each row to the table

        const tableBody = document.getElementById('table-body');

        data.forEach(row => {

            // Create a new table row

            const tr = document.createElement('tr');

 

            // Add the data for each column to the row

            const td1 = document.createElement('td');

            td1.textContent = row.column1;

            tr.appendChild(td1);

 

            const td2 = document.createElement('td');

            td2.textContent = row.column2;

            tr.appendChild(td2);

 

            // Add edit and delete buttons to the row

            const td3 = document.createElement('td');

            const editButton = document.createElement('button');

            editButton.textContent = 'Edit';

            td3.appendChild(editButton);

 

            const deleteButton = document.createElement('button');

            deleteButton.textContent = 'Delete';

            td3.appendChild(deleteButton);

 

            tr.appendChild(td3);

 

            // Add the row to the table body

            tableBody.appendChild(tr);

        });

    });

 

</script>

This code will retrieve the data from the API endpoint, loop through each row, create a new table row, add the data for each column and the edit and delete buttons, and then append the row to the table body.


Comentarios

Entradas populares de este blog

INSERTAR Y UPDATE FECHA CON PHP MYSQL EN FORMULARIO METODO POST CON JQUERY ETIQUETA DATE

Copia de Seguridad de Archivo MS Access (.mdb) a Pendrive con VB6

CONVERTIR IMÁGEN JPG O PNG A WEBP CON PHP DE FORMA SIMPLE