2

[I am using phpmyadmin]

I want to insert the long texts which are a large description of a city or region. It contains apostrophe and comma, but when inserted, comma is not a problem but the apostrophe are.

For eg.

' Taunggyi's the administrative capital for the whole of Shan State. Perched on top of a mountain, it's also a busy trading post, and the...',

It will an input from the user (type-in) to the text area on my website. So it cannot define statically like other examples I found.

Current one
//php $name=$_REQUEST["name"]; // //in insert query => '.$name.',

Have tried like below too, but not working.

'".$name."',

Any good ideas, please! Your help is most appreciated. Thank you!

Nai
  • 430
  • 5
  • 15

2 Answers2

3

Escape the quote with a backslash. Like 'sumit\'s'.

Here is an example function, using mysqli_real_escape_string:

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?> 

Reference: http://www.w3schools.com/php/func_mysqli_real_escape_string.asp

In your case, it should be mysql_real_escape_string($name)

jarvo69
  • 7,908
  • 2
  • 18
  • 28
1

Have you tried escaping special characters? Below should be helpful:

$name=mysqli_real_escape_string($connection, $name);

I created a function called post() and each time I need something from $_POST I simple call post('item_name'); the function than perform escaping and returns safe string ... There are numerous questions and answers to your question including this one: Properly Escaping with MySQLI | query over prepared statements

Community
  • 1
  • 1
salih0vicX
  • 1,363
  • 1
  • 8
  • 9
  • 1
    In the procedural way, [`mysqli_real_escape_string()`](http://php.net/manual/en/mysqli.real-escape-string.php) function takes two arguments, first is the connection handler and second is the string to escape. – Rajdeep Paul Sep 28 '16 at 12:52
  • @RajdeepPaul Good catch - I've updated my answer + upvoted. Thanks. – salih0vicX Sep 28 '16 at 12:54
  • It's worth mentioning that [even escaping string won't prevent SQL injection](http://stackoverflow.com/questions/37218691/mysql-real-escape-string-solve-sql-injection-definitely). +1 for the link btw. – Rajdeep Paul Sep 28 '16 at 12:59