简体   繁体   中英

How can I fix single quote error in SQL query?

I have an SQL query, in which I am converting inches to feet.

<?php  
$query ="
SELECT *
,replace (replace('<feet>'' <inches>"',
                   '<feet>', height / 12),
           '<inches>', height % 12) AS playerHeight
,abbrName
FROM leagueRosters
INNER JOIN leagueTeams AS teamInfo
ON leagueRosters.teamId=teamInfo.teamId

WHERE abbrName LIKE '".$_GET['team']."'
ORDER BY rosterId DESC
";  
$resultRoster = mysqli_query($connect, $query);  
?>

From what I understand I'm supposed to double the single quotes, which I have done

,replace (replace("<feet>"" <inches>"",
                   "<feet>", height / 12),
           "<inches>", height % 12) AS playerHeight

And I've also tried this

,replace (replace("'<feet>'" "'<inches>'",
                       "'<feet>'", height / 12),
               "'<inches>'", height % 12) AS playerHeight

Neither one works. I've tried a few other combinations, but always end up with an error on at least one line.

I followed the answer in this question - How do I escape a single quote in SQL Server? But I"m still unsure what I'm doing wrong.

You need to escape the double quote so it doesn't end the PHP string.

$query ="
SELECT *
,replace (replace('<feet>'' <inches>\"',
                   '<feet>', height / 12),
           '<inches>', height % 12) AS playerHeight
,abbrName
FROM leagueRosters
INNER JOIN leagueTeams AS teamInfo
ON leagueRosters.teamId=teamInfo.teamId

WHERE abbrName LIKE '".$_GET['team']."'
ORDER BY rosterId DESC
";

But there's no need to use replace in the first place, just use string concatenation.

$query ="
SELECT *
,CONCAT(FLOOR(height/12), ''' ', height % 12, '\"') AS playerheight
,abbrName
FROM leagueRosters
INNER JOIN leagueTeams AS teamInfo
ON leagueRosters.teamId=teamInfo.teamId

WHERE abbrName LIKE '".$_GET['team']."'
ORDER BY rosterId DESC
";  

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