我使用php通过ajax获取歌曲请求,并将其保存到postgres db。
一切都在heroku中,我可以使用pgadmin
连接到db我收到以下错误 - 从GET请求获取字符串并写入db的正确方法是什么?
2014-08-24T01:43:32.062128 + 00:00 app [web.1]:[Sun Aug 24 01:43:31.864706 2014] [proxy_fcgi:错误] [pid 64:tid 139700481152768] [客户端10.53.42.218:51189] AH01071:收到错误'PHP消息:PHP 警告:pg_query():查询失败:错误:语法错误在或附近 “\”\ nLINE 1:INSERT INTO歌曲(请求)VALUES(\'song \')\ n
^在第21行的/app/songs.php \ n',referer: http://sep21.herokuapp.com/2014-08-24T01:43:32.062130 + 00:00 app [web.1]:[2014年8月24日01:43:31] 警告:[pool www] child 61对stderr说:“注意:PHP消息: PHP警告:pg_query():查询失败:错误:语法错误在或 靠近“\”“
2014-08-24T01:43:32.062132 + 00:00 app [web.1]:[2014年8月24日01:43:31] 警告:[pool www] child 61对stderr说:“第1行:INSERT INTO 歌曲(请求)VALUES(\'song \')“
2014-08-24T01:43:32.062134 + 00:00 app [web.1]:[2014年8月24日01:43:31] 警告:[池www]孩子61对stderr说:“
^在第21行的/app/songs.php中“
代码如下:
CREATE TABLE songs
(
request character varying[] NOT NULL,
created bigint,
id bigserial NOT NULL,
CONSTRAINT "Pk" PRIMARY KEY (id)
)
$.ajax({
type: "GET",
url: "songs.php",
data: q,
success: function(resp){
// console.log(q)
// console.log(resp)
try{var song_resp = JSON.parse(resp)}
catch(err){var song_resp = err}
// console.log(song_resp)
// console.log(target)
if (song_resp.pass == true){
$("#nice_choice").slideDown(250)
// $("#nice_choice").css("-webkit-animation-play-state","running")
// $("#nice_choice").css("-animation-play-state","running")
}
else {
$("#something_wrong").slideDown(250)
// $("#something_wrong").css("-webkit-animation-play-state","running")
// $("#something_wrong").css("-animation-play-state","running")
}
},
error: function (jqXHR, exception){
$("#something_wrong").slideDown(300)
// $("#something_wrong").css("-webkit-animation-play-state","running")
// $("#something_wrong").css("-animation-play-state","running")
}
}); // Ajax Call
<?php
if ($_GET['q']){
$song = $_GET["q"];
$dbconn = pg_connect("host=ec2-54-247-111-1.eu-west-1.compute.amazonaws.com
dbname=dbname
user=user
password=pw")
or die('Could not connect: ' . pg_last_error());
$result = pg_query($dbconn, "INSERT INTO songs (request) VALUES(\'song\')");
//dump the result object
if ($result == false) {
echo false;
}
else{
echo true;
}
// Closing connection
pg_close($dbconn);
}
?>
答案 0 :(得分:1)
使用pg_query_params
或最好使用PDO。不要滚动你自己的报价。永远。 It's just plain wrong和the issues are well documented in the PHP manual。
您最好使用PDO。
(当前的问题是你的引用是错误的。你已经使用\'
来转义不需要转义的单引号,因此反斜杠会保留在最终的查询字符串中。你可以在错误信息)。