SELECT INSERT UPDATE DELETE GET POST FETCH JSON API PHP MYSQL JS

 

Fetch API post json api insert data mysql pdo php form

Certainly, here's an example of how you can use JavaScript's Fetch API to send a POST JSON API insert request to a PHP script, which then inserts data into a MySQL database using PDO:

 

First, create an HTML form with input fields for the data to be inserted and a submit button:

 

html

Copy code

<form id="insert-form">

  <label for="name-input">Name:</label>

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

 

  <label for="email-input">Email:</label>

  <input type="email" id="email-input" name="email-input">

 

  <label for="phone-input">Phone:</label>

  <input type="tel" id="phone-input" name="phone-input">

 

  <button type="submit">Insert</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 insert form and input elements

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

const nameInput = document.querySelector('#name-input');

const emailInput = document.querySelector('#email-input');

const phoneInput = document.querySelector('#phone-input');

 

// Add a submit event listener to the form

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

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

 

  // Get the form data

  const formData = {

    name: nameInput.value.trim(),

    email: emailInput.value.trim(),

    phone: phoneInput.value.trim()

  };

 

  // Send a POST request to the PHP script

  fetch('insert.php', {

    method: 'POST',

    headers: {

      'Content-Type': 'application/json'

    },

    body: JSON.stringify(formData)

  })

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

  .then(result => {

    console.log(result);

    // Optionally, display a success message or redirect to another page

  })

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

});

The above code sends a POST request to a PHP script called insert.php with a JSON object containing the form data. The response is expected to be a success message, which is logged to the console.

 

Next, create the insert.php script to insert the form data into the MySQL database:

 

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 form data from the POST request

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

 

// 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 insert the data into the database

$stmt = $pdo->prepare('INSERT INTO your_table_name (name, email, phone) VALUES (:name, :email, :phone)');

$stmt->bindValue(':name', $formData['name'], PDO::PARAM_STR);

$stmt->bindValue(':email', $formData['email'], PDO::PARAM_STR);

$stmt->bindValue(':phone', $formData['phone'], PDO::PARAM_STR);

 

// Execute the statement and check for errors

try {

    $stmt->execute();

    echo 'Data inserted successfully';

} catch(PDOException $e) {

    echo 'Error inserting data: ' . $e->getMessage();

    exit;

}

Note: You'll need to replace the

Fetch API post json api update data mysql pdo php form

 

4 / 4

 

Sure, here's an example of how you can use JavaScript's Fetch API to send a POST JSON API update request to a PHP script, which then updates data in a MySQL database using PDO:

 

First, create an HTML form with input fields for the data to be updated and a submit button:

 

html

Copy code

<form id="update-form">

  <label for="id-input">ID:</label>

  <input type="number" id="id-input" name="id-input">

 

  <label for="name-input">Name:</label>

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

 

  <label for="email-input">Email:</label>

  <input type="email" id="email-input" name="email-input">

 

  <label for="phone-input">Phone:</label>

  <input type="tel" id="phone-input" name="phone-input">

 

  <button type="submit">Update</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 update form and input elements

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

const idInput = document.querySelector('#id-input');

const nameInput = document.querySelector('#name-input');

const emailInput = document.querySelector('#email-input');

const phoneInput = document.querySelector('#phone-input');

 

// Add a submit event listener to the form

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

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

 

  // Get the form data

  const formData = {

    id: idInput.value.trim(),

    name: nameInput.value.trim(),

    email: emailInput.value.trim(),

    phone: phoneInput.value.trim()

  };

 

  // Send a POST request to the PHP script

  fetch('update.php', {

    method: 'POST',

    headers: {

      'Content-Type': 'application/json'

    },

    body: JSON.stringify(formData)

  })

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

  .then(result => {

    console.log(result);

    // Optionally, display a success message or redirect to another page

  })

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

});

The above code sends a POST request to a PHP script called update.php with a JSON object containing the form data. The response is expected to be a success message, which is logged to the console.

 

Next, create the update.php script to update the data in the MySQL database:

 

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 form data from the POST request

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

 

// 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 update the data in the database

$stmt = $pdo->prepare('UPDATE your_table_name SET name = :name, email = :email, phone = :phone WHERE id = :id');

$stmt->bindValue(':name', $formData['name'], PDO::PARAM_STR);

$stmt->bindValue(':email', $formData['email'], PDO::PARAM_STR);

$stmt->bindValue(':phone', $formData['phone'], PDO::PARAM_STR);

$stmt->bindValue(':id', $formData['id'],

 

 

.then(response => response.json()) Fetch API post json api insert data mysql pdo php form

 

Sure, here's an updated example that uses .json() instead of .text() to parse the response as JSON:

 

javascript

Copy code

// Get the form and input elements

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

const nameInput = document.querySelector('#name-input');

const emailInput = document.querySelector('#email-input');

const phoneInput = document.querySelector('#phone-input');

 

// Add a submit event listener to the form

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

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

 

  // Get the form data

  const formData = {

    name: nameInput.value.trim(),

    email: emailInput.value.trim(),

    phone: phoneInput.value.trim()

  };

 

  // Send a POST request to the PHP script

  fetch('insert.php', {

    method: 'POST',

    headers: {

      'Content-Type': 'application/json'

    },

    body: JSON.stringify(formData)

  })

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

  .then(data => {

    console.log(data);

    // Optionally, display a success message or redirect to another page

  })

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

});

The above code sends a POST request to a PHP script called insert.php with a JSON object containing the form data. The response is expected to be a JSON object, which is parsed using the .json() method.

 

Next, create the insert.php script to insert the data into the MySQL database:

 

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 form data from the POST request

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

 

// 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 insert the data into the database

$stmt = $pdo->prepare('INSERT INTO your_table_name (name, email, phone) VALUES (:name, :email, :phone)');

$stmt->bindValue(':name', $formData['name'], PDO::PARAM_STR);

$stmt->bindValue(':email', $formData['email'], PDO::PARAM_STR);

$stmt->bindValue(':phone', $formData['phone'], PDO::PARAM_STR);

$stmt->execute();

 

// Send a success message back to the client

$response = array('message' => 'Data inserted successfully.');

echo json_encode($response);

The above code inserts the data into a MySQL table called your_table_name and sends a success message back to the client as a JSON object. You should replace the database credentials and table name with your own.

 

.then(response => response.json()) Fetch API post json api update data mysql pdo php form

 

Sure, here's an updated example that uses .json() instead of .text() to parse the response as JSON:

 

javascript

Copy code

// Get the form and input elements

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

const idInput = document.querySelector('#id-input');

const nameInput = document.querySelector('#name-input');

const emailInput = document.querySelector('#email-input');

const phoneInput = document.querySelector('#phone-input');

 

// Add a submit event listener to the form

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

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

 

  // Get the form data

  const formData = {

    id: idInput.value.trim(),

    name: nameInput.value.trim(),

    email: emailInput.value.trim(),

    phone: phoneInput.value.trim()

  };

 

  // Send a POST request to the PHP script

  fetch('update.php', {

    method: 'POST',

    headers: {

      'Content-Type': 'application/json'

    },

    body: JSON.stringify(formData)

  })

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

  .then(data => {

    console.log(data);

    // Optionally, display a success message or redirect to another page

  })

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

});

The above code sends a POST request to a PHP script called update.php with a JSON object containing the form data. The response is expected to be a JSON object, which is parsed using the .json() method.

 

Next, create the update.php script to update the data in the MySQL database:

 

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 form data from the POST request

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

 

// 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 update the data in the database

$stmt = $pdo->prepare('UPDATE your_table_name SET name = :name, email = :email, phone = :phone WHERE id = :id');

$stmt->bindValue(':name', $formData['name'], PDO::PARAM_STR);

$stmt->bindValue(':email', $formData['email'], PDO::PARAM_STR);

$stmt->bindValue(':phone', $formData['phone'], PDO::PARAM_STR);

$stmt->bindValue(':id', $formData['id'], PDO::PARAM_INT);

$stmt->execute();

 

// Send a success message back to the client

$response = array('message' => 'Data updated successfully.');

echo json_encode($response);

The above code updates the data in a MySQL table called your_table_name based on the id value and sends a success message back to the client as a JSON object. You should replace the database credentials and table name with your own.

.then(response => response.json()) Fetch API post json api delete data mysql pdo php form

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 deletes data from a MySQL database:

 

javascript

Copy code

// Get the form and input elements

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

const idInput = document.querySelector('#id-input');

 

// Add a submit event listener to the form

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

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

 

  // Get the form data

  const formData = {

    id: idInput.value.trim()

  };

 

  // Send a POST request to the PHP script

  fetch('delete.php', {

    method: 'POST',

    headers: {

      'Content-Type': 'application/json'

    },

    body: JSON.stringify(formData)

  })

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

  .then(data => {

    console.log(data);

    // Optionally, display a success message or redirect to another page

  })

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

});

The above code sends a POST request to a PHP script called delete.php with a JSON object containing the form data. The response is expected to be a JSON object, which is parsed using the .json() method.

 

Next, create the delete.php script to delete data from the MySQL database:

 

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 form data from the POST request

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

 

// 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 delete the data from the database

$stmt = $pdo->prepare('DELETE FROM your_table_name WHERE id = :id');

$stmt->bindValue(':id', $formData['id'], PDO::PARAM_INT);

$stmt->execute();

 

// Send a success message back to the client

$response = array('message' => 'Data deleted successfully.');

echo json_encode($response);

The above code deletes the data from a MySQL table called your_table_name based on the id value and sends a success message back to the client as a JSON object. You should replace the database credentials and table name with your own

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