How to save json array in mysql using php?

by haylee.mertz , in category: PHP General , 4 months ago

How to save json array in mysql using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , 4 months ago

@haylee.mertz 

To save a JSON array in a MySQL database table using PHP, you can follow these steps:

  1. Connect to the MySQL database:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}


  1. Create a JSON array:
1
$jsonArray = json_encode($your_array); // Convert your array to JSON


  1. Prepare and execute an SQL query to save the JSON array in the database:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$sql = "INSERT INTO your_table_name (json_column) VALUES (?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $jsonArray);
$stmt->execute();

// Check if the query was successful
if ($stmt->affected_rows > 0) {
    echo "JSON array saved successfully.";
} else {
    echo "Error saving the JSON array.";
}


  1. Close the database connection:
1
2
$stmt->close();
$conn->close();


Note: Replace your_username, your_password, your_database_name, your_table_name, and $your_array with your actual values. Make sure you have a column in your table capable of storing JSON data, usually with a datatype like JSON or VARCHAR.