Hướng dẫn mysql escape single quote

This is how my data as API response looks like, which I want to store in the MYSQL database. It contains Quotes, HTML Code , etc.

Example:-

{

rewardName: "Cabela's eGiftCard $25.00",

shortDescription: '

adidas gift cards can be redeemed in over 150 adidas Sport Performance, adidas Originals, or adidas Outlet stores in the US, as well as online at adidas.com.

terms: '

adidas Gift Cards may be redeemed for merchandise on adidas.com and in adidas Sport Performance, adidas Originals, and adidas Outlet stores in the United States.' }

SOLUTION

CREATE TABLE `brand` (
`reward_name` varchar(2048),
`short_description` varchar(2048),
`terms` varchar(2048),  
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;

While inserting , In followed JSON.stringify()

    let brandDetails= {
    rewardName: JSON.stringify(obj.rewardName),  
    shortDescription: JSON.stringify(obj.shortDescription),
    term: JSON.stringify(obj.term),
     }

Above is the JSON object and below is the SQL Query that insert data into MySQL.

let query = `INSERT INTO brand (reward_name, short_description, terms) 
VALUES (${brandDetails.rewardName}, 
(${brandDetails.shortDescription}, ${brandDetails.terms})`;

Its worked....

Hướng dẫn mysql escape single quote

If nothing works try this :

var res = str.replace(/'/g, "\\'");
var res = res.replace(/"/g, "\\\"");

It adds the \ escape character to all(every) occurrences of ' and "

Not sure if its the correct/professional way to fix the issue

I'm guessing it will work but in actual content, every single and double quotes will be replaced with \ character

I have a perplexing issue that I can't seem to comprehend...

Nội dung chính

  • Example 1: Using Object Oriented style
  • Example 2: Using Procedural Method
  • How it Works
  • Definition and Usage
  • How escape single quotes PHP?
  • How do I escape a quote in MySQL?
  • What is use of Mysqli_real_escape_string in PHP?
  • How do I remove a single quote from a MySQL query?

I have two SQL statements:

  • The first enters information from a form into the database.
  • The second takes data from the database entered above, sends an email, and then logs the details of the transaction

The problem is that it appears that a single quote is triggering a MySQL error on the second entry only! The first instance works without issue, but the second instance triggers the mysql_error().

Does the data from a form get handled differently from the data captured in a form?

Query 1 - This works without issue (and without escaping the single quote)

$result = mysql_query("INSERT INTO job_log
(order_id, supplier_id, category_id, service_id, qty_ordered, customer_id, user_id, salesperson_ref, booking_ref, booking_name, address, suburb, postcode, state_id, region_id, email, phone, phone2, mobile, delivery_date, stock_taken, special_instructions, cost_price, cost_price_gst, sell_price, sell_price_gst, ext_sell_price, retail_customer, created, modified, log_status_id)
VALUES
('$order_id', '$supplier_id', '$category_id', '{$value['id']}', '{$value['qty']}', '$customer_id', '$user_id', '$salesperson_ref', '$booking_ref', '$booking_name', '$address', '$suburb', '$postcode', '$state_id', '$region_id', '$email', '$phone', '$phone2', '$mobile', STR_TO_DATE('$delivery_date', '%d/%m/%Y'), '$stock_taken', '$special_instructions', '$cost_price', '$cost_price_gst', '$sell_price', '$sell_price_gst', '$ext_sell_price', '$retail_customer', '".date('Y-m-d H:i:s', time())."', '".date('Y-m-d H:i:s', time())."', '1')");

Query 2 - This fails when entering a name with a single quote (for example, O'Brien)

$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', '$message_content', '1')");

As a PHP/MySQL developer, you have certain practices worth noting and making use of every other time. One of the is how to escape single quote in PHP while working with MySQL database. In this article, I will illustrate how to escape Single Quote in PHP/MySQL

Escaping refers to the process of encoding data containing characters so that MySQL interprets it correctly. To do this, you MUST escape strings with a PHP function known as mysql_real_escape_string. This means that you have to run this function in PHP before passing your query to the database. Normal good practice is to escape any data that comes into your database from an eternal source so as to avoid potential SQL injection.

You have to escape your data before you build your query. Also, you can build your query programmatically using PHP’s looping constructs and range:

Example 1: Using Object Oriented style

While using Object Oriented method, you escape characters in strings as shown below:

 connect_errno) {
  echo "Failed to connect to MySQL: " . $conn -> connect_error;
  exit();
}

// Escape special characters, if any
$fname = $conn -> real_escape_string($_POST['studentname']);
$lname = $conn -> real_escape_string($_POST['lastname']);
$grade = $conn -> real_escape_string($_POST['grade']);

$quest="INSERT INTO students (fName, LName, grade) VALUES ('$fname', '$lname', '$grade')";
 $stmt = $conn->prepare('SELECT * FROM items WHERE category = ?');
 $stmt->bind_param('s', $categ); 

 $stmt->execute();

if (!$conn -> query($quest)) {
  printf("%d Row inserted Successfully!\n", $conn->affected_rows);
}

$conn -> close();
?>



Advertisement

Example 2: Using Procedural Method


Advertisement

How it Works

Definition and Usage

The real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in an SQL query, taking into account the current character set of the connection. For example, while working with strings that use single quotes, like people’s names e.g. O’Neil, you need to handle this by the use of the real_escape_string() / mysqli_real_escape_string() function.

This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to produce an escaped SQL string, taking into account the current character set of the connection.

How escape single quotes PHP?

In PHP, an escape sequence starts with a backslash \ . Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.

How do I escape a quote in MySQL?

To insert binary data into a string column (such as a BLOB column), you should represent certain characters by escape sequences. Backslash ( \ ) and the quote character used to quote the string must be escaped.

What is use of Mysqli_real_escape_string in PHP?

The real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in an SQL query, taking into account the current character set of the connection. This function is used to create a legal SQL string that can be used in an SQL statement.

How do I remove a single quote from a MySQL query?

You can easily escape single quotes, double quotes, apostrophe, backticks and other special characters by adding a backslash (\) before that character.