简体   繁体   中英

how can handle single quote in mysql query

i am working in php. i want to write query like this:-

update user_account set university_name='St. Josed father's institute' 
where userId=5;

but this is creating error due to 's means it creating problem because of single quote ' .

please suggest me how can i handle this. currently i am right this directly St. Josed father's institute but in my php code this is in variable $university_name

so please suggest me how can i check and remove such type of problem.

$location = "St. Josed father's institute";
$location = mysql_real_escape_string($location);
$query = update user_account set university_name='St. Josed father's institute' 
where userId=5;

$query = str_replace("'","''", $query);

It's necessary that you realise this issue centers around SQL and not php. SQL's escape character (according to the standard 92) is '. So what we want to do is change

'St. Josed father's institute' to 'St. Josed father''s institute'

Using the escape character, mysql would not interpret you ' as the end of the string.

you could use php function mysql_real_escape_string

<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    OR die(mysql_error());

// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
            mysql_real_escape_string($user),
            mysql_real_escape_string($password));
?>

document is here: http://php.net/manual/en/function.mysql-real-escape-string.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM