Nai Nai - 2 months ago 13
MySQL Question

PHP|MySql - cannot insert text contains apostrophe

[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!

Answer

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)