我使用curl运行SQL查询以在数据库中创建表。这是工作代码:
// defines the post vars
$apikey = $_POST['apikey'];
$username = $_POST['username'];
$tablename = $_POST['tablename'];
//SQL create table statment
$sql = "CREATE TABLE " . (string)$tablename . " (post_id integer, post_title text, post_content text, post_date date, post_type text, permalink_guid text);";
$sql2 = "SELECT cdb_cartodbfytable('" . (string)$tablename . "');";
// initializing curl
$ch = curl_init( "https://".$username.".cartodb.com/api/v2/sql" );
$query = http_build_query(array('q'=>$sql,'api_key'=>$apikey));
$query2 = http_build_query(array('q'=>$sql2,'api_key'=>$apikey));
// configuring curl options
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//result
$result_jsonstring = curl_exec($ch);
$result = json_decode($result_jsonstring);
echo(print_r($result));
使用此代码,我可以获得两个成功的响应。如果表创建成功:
stdClass Object
(
[rows] => Array
(
)
[time] => 0.013
[fields] => stdClass Object
(
)
[total_rows] => 0
)
1
如果数据库中已存在表名,我会得到:
stdClass Object
(
[error] => Array
(
[0] => relation "tablename" already exists
)
)
1
我还可以成功运行第二个查询,将curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
替换为curl_setopt($ch, CURLOPT_POSTFIELDS, $query2);
我遇到的问题是如果第一个查询成功,则运行第二个查询(创建表,但如果表存在则不运行)。以下是我试图完成此操作的代码:
// defines the post vars
$apikey = $_POST['apikey'];
$username = $_POST['username'];
$tablename = $_POST['tablename'];
//SQL create table statment
$sql = "CREATE TABLE " . (string)$tablename . " (post_id integer, post_title text, post_content text, post_date date, post_type text, permalink_guid text);";
// initializing curl
$ch = curl_init( "https://".$username.".cartodb.com/api/v2/sql" );
$query = http_build_query(array('q'=>$sql,'api_key'=>$apikey));
// configuring curl options
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//result
$result_jsonstring = curl_exec($ch);
//close the curl session
curl_close($ch);
if (TRUE === $result_jsonstring)
echo "It was true!";
echo(print_r($result_jsonstring));
ch2 = curl_init( "https://".$username.".cartodb.com/api/v2/sql" );
$sql2 = "SELECT cdb_cartodbfytable('" . (string)$tablename . "');";
$query2 = http_build_query(array('q'=>$sql2,'api_key'=>$apikey));
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query2);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result_jsonstring2 = curl_exec($ch2);
echo(print_r($result_jsonstring2));
curl_close($ch2);
以下是我遇到的问题: 1)第二个卷曲请求不起作用。我收到一条消息说我必须提供一个SQL查询"而且我不确定为什么。我确实得到了#34;这是真的!"但是声明。 2)我在回复结束时继续得到数字1。在最后的案例中,我得到两个(11)。
{"rows":[],"time":0.008,"fields":{},"total_rows":0}It was true!11{"error":["You must indicate a sql query"]}11
如果成功创建表,我怎样才能成功运行第二个curl进程?
答案 0 :(得分:0)
将最后两个curl_setop更改为使用$ ch2而不是$ ch。