如何在CodeIgniter中存储JSON格式数据?含指定结构存储实现疑问
Hey there! Let's get your JSON storage sorted out. You want to save something like [{"delete": 30}] (where 30 is your selected option value) into the spam_management column of the pm1cti_details table. Your current model code is creating a different JSON structure than what you need, so let's fix that—and use safer practices while we're at it.
First, Let's Fix the Model Code
The main issue is your manual JSON string construction is generating the wrong format. Instead of building the string by hand (which can lead to syntax errors if you're not careful), use PHP's built-in json_encode() function—it's reliable and handles all the JSON syntax rules for you automatically.
Here's the corrected model code:
public function update_selectedspmlds($value) { // Create the exact data structure you want: an array containing one object with "delete" key $jsonStructure = [ ['delete' => (int)$value] // Cast to integer to ensure it's stored as a number, not a string ]; // Convert the structure to valid JSON $validJson = json_encode($jsonStructure); // Insert into the database $this->db->insert('pm1cti_details', ['spam_management' => $validJson]); }
What This Does:
- The
$jsonStructurearray matches the format you need. When encoded to JSON, it becomes exactly[{"delete": 30}](assuming your$valueis 30). - Using
json_encode()ensures that even if your value has special characters (like quotes), it's properly escaped to keep the JSON valid. - Casting
$valueto(int)makes sure the number is stored as a numeric type in the JSON—remove this if you need it as a string instead.
Optional: Improve the Controller
Your controller is mostly okay, but adding a quick validation check can help catch invalid inputs before they reach the model:
public function update_selectedspmlds() { $value = $this->input->post("value"); // Make sure we received a valid numeric value if (is_numeric($value)) { $this->approval_model->update_selectedspmlds($value); // Optional: Send a success response back to the frontend echo json_encode(['status' => 'success']); } else { // Handle invalid input echo json_encode(['status' => 'error', 'message' => 'Please select a valid value']); } }
If You Really Want to Build the JSON String Manually (Not Recommended):
If for some reason you prefer to construct the string by hand (though json_encode() is always safer), you can do this:
$validJson = '[{"delete": ' . (int)$value . '}]';
But again, using json_encode() is better practice—it's less error-prone, especially if your value ever changes to include strings or special characters.
内容的提问来源于stack exchange,提问作者Shwetha Shetty

