SEARCH NOMBRE FECHAS CON FETCH POST JSON API MYSQL PDO PHP TABLE HTML

 FETCH post json api search mysql pdo php display table html

Sure, here's an example of how you can use PHP PDO to retrieve data from a MySQL database, and then display it in an HTML table using data obtained from a POST JSON API search request:

 

First, you'll need to create a connection to your MySQL database using PDO:

 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;

}

Next, you can retrieve data from the database using a prepared statement. In this example, we'll assume that the search query is passed as a JSON object in the POST request body:

 

php

Copy code

// Get the search query from the POST request

$search_query = json_decode(file_get_contents('php://input'), true);

 

// Prepare a statement to retrieve data from the database based on the search query

$stmt = $pdo->prepare('SELECT * FROM your_table_name WHERE column_name LIKE :search_query');

$stmt->bindValue(':search_query', '%' . $search_query['query'] . '%', PDO::PARAM_STR);

 

// Execute the statement and fetch the results

$stmt->execute();

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

Once you have the results, you can display them in an HTML table:

 

php

Copy code

// Output the results in an HTML table

echo '<table>';

echo '<thead><tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr></thead>';

echo '<tbody>';

foreach ($results as $row) {

    echo '<tr>';

    echo '<td>' . $row['column1'] . '</td>';

    echo '<td>' . $row['column2'] . '</td>';

    echo '<td>' . $row['column3'] . '</td>';

    echo '</tr>';

}

echo '</tbody>';

echo '</table>';

Note: You'll need to replace the table column names in the above code with the actual column names from your database table.

 

//////////////////////////////

Fetch API post json api search mysql pdo php display table html

 

Sure, here's an example of how you can use JavaScript's Fetch API to send a POST JSON API search request to a PHP script, which then retrieves data from a MySQL database using PDO and displays it in an HTML table:

 

First, create an HTML form with a search input field and a submit button:

 

html

Copy code

<form id="search-form">

  <label for="search-input">Search:</label>

  <input type="text" id="search-input" name="search-input">

  <button type="submit">Search</button>

</form>

Next, add JavaScript code to handle the form submission and send a POST request to a PHP script:

 

javascript

Copy code

// Get the search form and input elements

const searchForm = document.querySelector('#search-form');

const searchInput = document.querySelector('#search-input');

 

// Add a submit event listener to the form

searchForm.addEventListener('submit', (event) => {

  event.preventDefault(); // Prevent the form from submitting normally

 

  // Get the search query from the input element

  const searchQuery = searchInput.value.trim();

 

  // Send a POST request to the PHP script

  fetch('search.php', {

    method: 'POST',

    headers: {

      'Content-Type': 'application/json'

    },

    body: JSON.stringify({ query: searchQuery })

  })

  .then(response => response.text())

  .then(html => {

    // Insert the HTML table into the page

    document.querySelector('#search-results').innerHTML = html;

  })

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

});

The above code sends a POST request to a PHP script called search.php with a JSON object containing the search query. The response is expected to be an HTML table, which is inserted into a container element with the ID search-results.

 

Next, create the search.php script to retrieve data from the MySQL database and display it in an HTML table:

 

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

 

// Get the search query from the POST request

$searchQuery = json_decode(file_get_contents('php://input'), true)['query'];

 

// 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 retrieve data from the database based on the search query

$stmt = $pdo->prepare('SELECT * FROM your_table_name WHERE column_name LIKE :search_query');

$stmt->bindValue(':search_query', '%' . $searchQuery . '%', PDO::PARAM_STR);

 

// Execute the statement and fetch the results

$stmt->execute();

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

 

// Output the results in an HTML table

echo '<table>';

echo '<thead><tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr></thead>';

echo '<tbody>';

foreach ($results as $row) {

    echo '<tr>';

    echo '<td>' . $row['column1'] . '</td>';

    echo '<td>' . $row['column2'] . '</td>';

    echo '<td>' . $row['column3'] . '</td>';

    echo '</tr>';

}

echo '</tbody>';

echo '</table>';

Note: You'll need to replace the table column names in the above code


------------------------

.then(response => response.json()) Fetch API get json api search input data mysql pdo php display 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 searches for data in a MySQL database and generates an HTML table based on the search query:

 

javascript

Copy code

// Get the search input and table elements

const searchInput = document.querySelector('#search-input');

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

 

// Send a GET request to the PHP script with the search query as a parameter

searchInput.addEventListener('input', () => {

  const query = searchInput.value.trim();

  if (query.length > 0) {

    fetch(`search.php?query=${encodeURIComponent(query)}`)

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

  } else {

    table.innerHTML = '';

  }

});

The above code sends a GET request to a PHP script called search.php, passing the search query as a URL parameter. The response is then parsed using the .json() method.

 

Next, create the search.php script to search for data in the MySQL database based on the query parameter 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;

}

 

// Get the search query from the URL parameter

$query = $_GET['query'] ?? '';

 

// Prepare a statement to search for data in the database

$stmt = $pdo->prepare('SELECT id, name, email FROM your_table_name WHERE name LIKE :query OR email LIKE :query');

$stmt->bindValue(':query', '%' . $query . '%', PDO::PARAM_STR);

$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 searches for data in a MySQL table called your_table_name based on the search query parameter passed in the URL. The query searches for matches in both the name and email columns using the LIKE operator. The retrieved rows are sent back to the client as a JSON array of objects. 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 search input data mysql pdo php display table html

Sure, here's an example of how to use .json() to parse the response from a Fetch API POST request to a PHP script that searches for data in a MySQL database and generates an HTML table based on the search query:

 

javascript

Copy code

// Get the search input, form, and table elements

const searchInput = document.querySelector('#search-input');

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

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

 

// Send a POST request to the PHP script with the search query as a parameter

form.addEventListener('submit', (event) => {

  event.preventDefault();

  const formData = new FormData(form);

  fetch('search.php', {

    method: 'POST',

    body: formData

  })

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

});

 

// Send a GET request to the PHP script to retrieve all data

fetch('search.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 POST request to a PHP script called search.php, passing the search query as form data. The response is then parsed using the .json() method. Additionally, a GET request is sent to retrieve all data from the PHP script when the page loads.

 

Next, create the search.php script to search for data in the MySQL database based on the form data 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;

}

 

// Get the search query from the form data

$query = $_POST['query'] ?? '';

 

// Prepare a statement to search for data in the database

$stmt = $pdo->prepare('SELECT id, name, email FROM your_table_name WHERE name LIKE :query OR email LIKE :query');

$stmt->bindValue(':query', '%' . $query . '%', PDO::PARAM_STR);

$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 searches for data in a MySQL table called your_table_name based on the search query passed in the form data

.then(response => response.json()) Fetch API post json api search 2 date data mysql pdo php display table html

 

6 / 6

 

Sure, here's an example of how to use .json() to parse the response from a Fetch API POST request to a PHP script that searches for data in a MySQL database between two dates and generates an HTML table based on the search query:

 

javascript

Copy code

// Get the date inputs, form, and table elements

const fromDateInput = document.querySelector('#from-date-input');

const toDateInput = document.querySelector('#to-date-input');

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

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

 

// Send a POST request to the PHP script with the date range as parameters

form.addEventListener('submit', (event) => {

  event.preventDefault();

  const formData = new FormData(form);

  fetch('search.php', {

    method: 'POST',

    body: formData

  })

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

});

 

// Send a GET request to the PHP script to retrieve all data

fetch('search.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 POST request to a PHP script called search.php, passing the date range as form data. The response is then parsed using the .json() method. Additionally, a GET request is sent to retrieve all data from the PHP script when the page loads.

 

Next, create the search.php script to search for data in the MySQL database between two dates 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;

}

 

// Get the date range from the form data

$fromDate = $_POST['from_date'] ?? '';

$toDate = $_POST['to_date'] ?? '';

 

// Prepare a statement to search for data in the database between the two dates

$stmt = $pdo->prepare('SELECT id, name, email FROM your_table_name WHERE created_at BETWEEN :fromDate AND :toDate');

$stmt->bindValue(':fromDate', $fromDate, PDO::PARAM_STR);

$stmt->bindValue(':toDate', $toDate, PDO::PARAM_STR);

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

 

Comentarios

Entradas populares de este blog

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

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

DETECTAR DIRECCION IP CON PHP Y JS