What are the best practices for storing and retrieving strings with varying lengths and spaces in a MySQL database using PHP?

When storing strings with varying lengths and spaces in a MySQL database using PHP, it is important to properly handle the data to prevent any issues with data truncation or unexpected behavior. One best practice is to use the VARCHAR data type for variable-length strings and ensure that the column length is set appropriately to accommodate the maximum expected length of the strings. Additionally, when retrieving the strings, use PHP functions like trim() to remove any leading or trailing spaces.

// Storing a string with varying length and spaces in a MySQL database
$connection = new mysqli("localhost", "username", "password", "database");

// Define the maximum length for the string
$max_length = 100;

// Escape the string and trim any leading or trailing spaces
$string = $connection->real_escape_string(trim($string));

// Insert the string into the database
$query = "INSERT INTO table_name (column_name) VALUES ('$string')";
$connection->query($query);

// Retrieving the string with spaces removed
$query = "SELECT column_name FROM table_name WHERE id = 1";
$result = $connection->query($query);
$row = $result->fetch_assoc();
$retrieved_string = trim($row['column_name']);

// Close the database connection
$connection->close();