Escaping Single Quotes in PHP for MySQL Insertion
When inserting data into a MySQL database from PHP, special characters like single quotes can cause errors. To prevent this, it's crucial to escape these characters before inserting them into the query.
The issue described in the question arises because data is gathered and inserted differently, depending on the origin. Query 1 directly gathers data from a submitted form, which potentially introduces unescaped single quotes. In Query 2, however, the data is first extracted from the database, where single quotes might have already been escaped if magic_quotes_gpc was enabled.
The solution is to escape single quotes consistently in both queries using mysql_real_escape_string(). This function escapes special characters and ensures proper handling of single quotes, even when they appear in the data.
Example:
<code class="php">$escaped_name = mysql_real_escape_string($name); $query = mysql_query("INSERT INTO message_log (order_id, timestamp, message_type, email_from, supplier_id, primary_contact, secondary_contact, subject, message_content, status) VALUES ('$order_id', '" . date('Y-m-d H:i:s', time()) . "', '$email', '$from', '$row->supplier_id', '$row->primary_email' ,' $row->secondary_email', '$subject', '$escaped_name', '1')");</code>
By escaping single quotes consistently in PHP before inserting data into MySQL, you can prevent potential errors and ensure accurate data handling.
The above is the detailed content of How to Properly Escape Single Quotes for MySQL Insertion in PHP?. For more information, please follow other related articles on the PHP Chinese website!