I have two php variables, one integer and other json, which I convert into string variable and then inserting them inside a postgresql database.
Converting integer into string variable:
$string1 = (string)$integer;
Coneverting json from facebook api into string variable:
$string2 = json_encode($json);
Now, I have to insert these two string variables into postgres database:
$query = "INSERT INTO interests VALUES(". $string1 ." ," . $string2 .")";
pg_query($con, $query) or die("Cannot execute query: $query\n");
This is not working. I have tried a lot of solutions but still not working.
I changed my function to insert into database
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);
}
Output is: cannot execute statement1 I have created database as below:
$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");
Because strings need to be surrounded with simple quotes. I would strongly advise you use prepared statements to ignore these kind of problems and ensure correct variable escaping to prevent your application from beeing hacked trough SQL injection.
$sql = "INSERT INTO interests VALUES ($1, $2)";
$result = pg_prepare($con, 'my_insert', $sql);
$result = pg_execute($con, 'my_insert', array($string1, $string2));
See http://php.net/manual/en/function.pg-prepare.php
Edit: Here is the actual code I've tested:
<?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.");
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.