[php] How to insert special characters into a database?

Can anyone tell me how to insert special characters into a MySQL database? I've made a PHP script which is meant to insert some words into a database, although if the word contains a ' then it wont be inserted.

I can insert the special characters fine when using PHPmyAdmin, but it just doesn't work when inserting them via PHP. Could it be that PHP is changing the special characters into something else? If so, is there a way to make them insert properly?

This question is related to php mysql database insert special-characters

The answer is


I put it here for future reference. After wasting 20 minutes i got a solution to put special characters to database. we do not have to use mysql_real_escape_string($holdvalue) like that. we have to do this in this way. $db->real_escape_string($holdvalue). Where $db is the databse connection details. $db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);.


Probably "mysql_real_escape_string()" will work for u


Are you escaping? Try the mysql_real_escape_string() function and it will handle the special characters.


For Example:
$parent_category_name = Men's Clothing
Consider here the SQL query

$sql_category_name = "SELECT c.*, cd.name, cd.category_id  as iid FROM ". DB_PREFIX . "category c LEFT JOIN " . DB_PREFIX . "category_description cd ON (c.category_id = cd.category_id) WHERE cd.name = '" .  $this->db->escape($parent_category_name) . "' AND c.parent_id =0 "; 

Error:

Static analysis:

1 errors were found during analysis.

Ending quote ' was expected. (near "" at position 198)
SQL query: Documentation

SELECT c.*, cd.name, cd.category_id as iid FROM oc_category c LEFT JOIN oc_category_description cd ON (c.category_id = cd.category_id) WHERE cd.name = 'Men's Clothing' AND c.parent_id =0 LIMIT 0, 25

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Clothing' AND c.parent_id =0 LIMIT 0, 25' at line 1

Try to implement:

$this->db->escape($parent_category_name)

The above method works on OpenCart framework. Find your framework & implement OR mysql_real_escape_string() in Core PHP

This will become Men\'s Clothing i.e, In my case

$sql_category_name = "SELECT c.*, cd.name, cd.category_id  as iid FROM ". DB_PREFIX . "category c LEFT JOIN " . DB_PREFIX . "category_description cd ON (c.category_id = cd.category_id) WHERE cd.name = '" .  $this->db->escape($parent_category_name) . "' AND c.parent_id =0 "; 

So you'll get the clear picture of the query by implementing escape() as

SELECT c.*, cd.name, cd.category_id as iid FROM oc_category c LEFT JOIN oc_category_description cd ON (c.category_id = cd.category_id) WHERE cd.name = 'Men\'s Clothing' AND c.parent_id =0

You are most likely escaping the SQL string, similar to:

SELECT * FROM `table` WHERE `column` = 'Here's a syntax error!'

You need to escape quotes, like follows:

SELECT * FROM `table` WHERE `column` = 'Here\'s a syntax error!'

mysql_real_escape_string() handles this for you.


Use this: htmlentities($_POST['field']);

Enough only. This for special character:

Use for CI htmlentities($this->input->post('control_name'));


use mysql_real_escape_string

So what does mysql_real_escape_string do?

This PHP library function prepends backslashes to the following characters: \n, \r, \, \x00, \x1a, ‘ and “. The important part is that the single and double quotes are escaped, because these are the characters most likely to open up vulnerabilities.

Please inform yourself about sql_injection. You can use this link as a start


You are propably pasting them directly into a query. Istead you should "escape" them, using appriopriate function - mysql_real_escape_string, mysqli_real_escape_string or PDO::quote depending on extension you are using.


htmlspecialchars function is the best solution fellows. Today I was searching for how to insert strings with special characters and the google thrown so many Stackoverflow listings.None of them provided me solution. I found it in w3schools page. Yes I could solve my problem by using this function like this:

$abc = $POST['xyz'];

$abc = htmlspecialchars($abc);

Note that as others have pointed out mysql_real_escape_string() will solve the problem (as will addslashes), however you should always use mysql_real_escape_string() for security reasons - consider:

SELECT * FROM valid_users WHERE username='$user' AND password='$password'

What if the browser sends

user="admin' OR (user=''"
password="') AND ''='"

The query becomes:

SELECT * FROM valid_users 
WHERE username='admin' OR (user='' AND password='') AND ''=''

i.e. the security checks are completely bypassed.

C.


$var = mysql_real_escape_string("data & the base");
$result = mysql_query('SELECT * FROM php_bugs WHERE php_bugs_category like  "%' .$var.'%"');

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to database

Implement specialization in ER diagram phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' cannot be loaded Room - Schema export directory is not provided to the annotation processor so we cannot export the schema SQL Query Where Date = Today Minus 7 Days MySQL Error: : 'Access denied for user 'root'@'localhost' SQL Server date format yyyymmdd How to create a foreign key in phpmyadmin WooCommerce: Finding the products in database TypeError: tuple indices must be integers, not str

Examples related to insert

How to insert current datetime in postgresql insert query How to add element in Python to the end of list using list.insert? Python pandas insert list into a cell Field 'id' doesn't have a default value? Insert a row to pandas dataframe Insert at first position of a list in Python How can INSERT INTO a table 300 times within a loop in SQL? How to refresh or show immediately in datagridview after inserting? Insert node at a certain position in a linked list C++ select from one table, insert into another table oracle sql query

Examples related to special-characters

How to use tick / checkmark symbol (?) instead of bullets in unordered list? HTML for the Pause symbol in audio and video control How to run mysql command on bash? Which characters need to be escaped when using Bash? Matching special characters and letters in regex jQuery: Check if special characters exists in string Checking if a character is a special character in Java How to display special characters in PHP How should I escape commas and speech marks in CSV files so they work in Excel? grep for special characters in Unix