1

我有两个 php 变量,一个整数和另一个 json,我将它们转换为字符串变量,然后将它们插入到 postgresql 数据库中。

将整数转换为字符串变量:

$string1 = (string)$integer;

将 json 从 facebook api 转换为字符串变量:

$string2 = json_encode($json);

现在,我必须将这两个字符串变量插入到 postgres 数据库中:

$query = "INSERT INTO interests VALUES(". $string1 ." ," . $string2 .")"; 
pg_query($con, $query) or die("Cannot execute query: $query\n");

这是行不通的。我已经尝试了很多解决方案,但仍然无法正常工作。

我将函数更改为插入数据库

function push_interests(){
$id = $facebook->getUser();
$int = $facebook->api('/me/interests');     
$host = "hostname"; 
$user = "user"; 
$pass = "password"; 
$db = "database"; 

$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
    or die ("Could not connect to server\n"); 


$id = (string)$id;
$int = json_encode($int);

$sql = "INSERT INTO interests VALUES($1,$2)"; 
pg_prepare($con,'my_insert', $sql) or die ("Cannot prepare statement1\n") ;
pg_execute($con,'my_insert', array($id,$int)) or die ("Cannot execute statement1\n");

pg_close($con); 

}

输出是:无法执行语句 1 我创建了如下数据库:

$query = "DROP TABLE IF EXISTS interests"; 
pg_query($con, $query) or die("Cannot execute query: $query\n");

$query = "CREATE TABLE interests(id VARCHAR(25) PRIMARY KEY, interests VARCHAR(500))";  
pg_query($con, $query) or die("Cannot execute query: $query\n"); 
4

1 回答 1

4

因为字符串需要用简单的引号括起来。我强烈建议您使用准备好的语句来忽略此类问题并确保正确的变量转义以防止您的应用程序通过 SQL 注入被黑客入侵。

$sql = "INSERT INTO interests VALUES ($1, $2)";
$result = pg_prepare($con, 'my_insert', $sql);
$result = pg_execute($con, 'my_insert', array($string1, $string2));

http://php.net/manual/en/function.pg-prepare.php

编辑:这是我测试过的实际代码:

<?php

$con = pg_connect('')
    or die ("Could not connect to server\n"); 

$id = (string) 5;
$int = json_encode(array('pika' => 'chu', 'plop' => array(1, 2, 3)));

$query = "CREATE TABLE interests(id VARCHAR(25) PRIMARY KEY, interests VARCHAR(500))";
pg_query($query) or die('creating table failed.');

$sql = "INSERT INTO interests (id, interests) VALUES ($1, $2)";
pg_prepare('my_query', $sql);
pg_execute('my_query', array($id, $int)) or die("Error while inserting.");
于 2012-11-08T10:09:53.130 回答