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.");
Related
I am trying to insert data into 2 tables which are in different database. But I'm not able to connect to the second database.
$con1 = mysqli_connect("localhost","root","","db1");
$sql_1 = "insert into enquiry(name,email,phone,subject,message,service_category) values('aa','aa#gg.com','12344','xxx','ddd','ddd')";
$res_1 = mysqli_query($con1,$sql_1);
$con = mysqli_connect("localhost","root","","db2");
$sql = "insert into customers(cname,cphone,cemail) values('$name','$phone','$email')";
$res = mysqli_query($con,$sql);
You can do this with a single connection
$db = new mysqli($host,$user,$pass);
When selecting the DB use this
mysqli_select_db('DB_NAME', $db);
You Code
$con1 = mysqli_connect("localhost","username","password");
/* For the DB1 */
mysqli_select_db('DB_NAME1', $con1);
$sql_1 = "insert into
enquiry(name,email,phone,subject,message,service_category)
values('aa','aa#gg.com','12344','xxx','ddd','ddd')";
$res_1 = mysqli_query($con1,$sql_1);
/* For the DB2 */
mysqli_select_db('DB_NAME2', $con1);
$sql = "insert into customers(cname,cphone,cemail)
values('$name','$phone','$email')";
$res = mysqli_query($con1,$sql);
i really dont know why this code isnt working.. database connection works, the timestamp is written to the database.
But i cant figure out why i get a blank page with this code here (i should see the timestamp as echo).
Anyone an idea about this ?
Thank you!
<?php
$user = "daycounter";
$password = "1234";
$database = "daycounter";
$host = "localhost";
$date = time();
// Create connection
$conn = new mysqli($host, $user, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Error: " . $conn->connect_error);
}
//Insert timestamp in database
$sql = "INSERT INTO datum (datum)
VALUES ('".$date."')";
//check if that worked
if ($conn->query($sql) === TRUE) {
echo "That worked!";
}
//get timestamp from db and display it as echo
$select = "SELECT 'datum' FROM 'daycounter'";
$result = mysql_query($select);
while($row = mysql_fetch_object($result))
{
echo "$row->datum";
}
?>
You're using a mysqli DB connection, but calling mysql to do your select. You cannot mix/match the database libraries like that. If you'd had even minimal error checking, you'd have been told that there's no connection to the db:
$result = mysql_query($select) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^
Plus, your select query has syntax errors. 'daycounter' is a string literal - you cannot select FROM a string. 'datum' would be syntactically correct, you can select a string literal from a table, but most like you want:
SELECT datum FROM daycounter
or
SELECT `datum` FROM `daycounter`
Neither of those words are a reserved word, so there's NO need to quote them, but if you're one of those people who insist on quoting ALL identifiers, then they must be quoted with backticks, not single-quotes.
$select = "SELECT 'datum' FROM 'daycounter'";
$result = mysqli_query($conn, $select);
while($row = mysqli_fetch_object($result)) {
echo "$row->datum";
}
So I have form1 that contains information from multiple tables in a database. I've got listboxes and textboxes within this form that have that information. So all I'm trying to do is insert whatever information the user submits back into the database and have it outputted on form2. I've got my INSERT INTOs on my output page. I know you can't use one INSERT INTO query, so I was wondering how to use multiple INSERTS and submit that information back into the database.
The variables created below come from the previous page and all of the values are there.
if (isset($_POST['n_submit'])){
$oid = $_POST['oid'];
$odate = $_POST['odate'];
$ostatus = $_POST['ostatus'];
$cfname = $_POST['cfname'];
$cname = $_POST['clname'];
$efname = $_POST['efname'];
$elname = $_POST['elname'];
echo "New record created successfully";
$db = mysqli_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password') or die ("I cannot connect to the database because: ".mysqli_connect_error());
$query = "select status_id from ostatus where status_type = '$ostatus'";
$result = mysqli_query($db, $query) or die("Error in SQL statement:" .mysqli_error());
$row = mysqli_fetch_array($result);
$statusid = $row[0];
$query1 = "insert into cust ('c_fname', 'c_lname') values ('$cfname', $clname)";
$result1 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query2 = "insert into employed ('e_fname', e_lname) values ('$efname', '$elname')";
$result2 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query3 ="INSERT INTO sorder (o_id, o_date, s_id) VALUES ('{$oid}', '{$odate}', '{$statusid}')";
$result3 = mysqli_query($db, $query3);
}
First of all your query is vulnerable to SQL injection. I am not going to fix that.
Second, you should Google how to handle forms properly. And you should consider starting SQL transaction if you really care about the data to go into all the tables for sure.
Third, you should be able to use multiple inserts like you are doing in your code. but you need to correct your syntax errors.
Try this code (I also removed the select code are based on your question it is not needed)
if (isset($_POST['n_submit'])){
$oid = $_POST['oid'];
$odate = $_POST['odate'];
$ostatus = $_POST['ostatus'];
$cfname = $_POST['cfname'];
$cname = $_POST['clname'];
$efname = $_POST['efname'];
$elname = $_POST['elname'];
$db = mysqli_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password') or die ("I cannot connect to the database because: ".mysqli_connect_error());
$query1 = "insert into cust (c_fname, c_lname) values ('".$cfname."', '".$clname."')";
$result1 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query2 = "insert into employed (e_fname, e_lname) values ('".$efname."', '".$elname."')";
$result2 = mysqli_query($db, $query2) or die("Error in SQL statement:" .mysqli_error());
$query3 ="INSERT INTO sorder (o_id, o_date, s_id) VALUES ('".$oid."', '".$odate."', '".$statusid."')";
$result3 = mysqli_query($db, $query3);
if($result1 && $result2 && $result3)
echo 'New record created successfully';
else
echo 'something did not work';
}
This question already has answers here:
php/mysql with multiple queries
(3 answers)
Closed 3 years ago.
I've a doubt with mysqli_query..
this is a part of my code:
$con = db_connect();
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
$result = mysqli_query($con, $sql);
return $result;
I can't do the query...
If I try to do a query like this:
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
It works.
What's the problem?? I can't use SET with mysqli_query?
Thanks
You can not execute multiple queries at once using mysqli_query but you might want to use mysqli_multi_query as you can find out in the official documentation:
http://www.php.net/manual/en/mysqli.multi-query.php
Lets start with creating a working php script.
<?php
// replace for you own.
$host ="";
$user = "";
$password = "";
$database = "";
$con= mysqli_connect($host, $user, $password, $database);
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
// Begin SQL query
$sql = "SELECT * FROM users";
$result = mysqli_query($con,$sql) OR Die('SQL Query not possible!');
var_dump($result);
return $result;
var_dump($result);
// End SQL query
mysqli_close($con);
};
?>
INSERT query:
$sql= "INSERT INTO categorias(name) VALUES ('ssss')";
mysqli_query ($con,$sql) OR Die('SQL Query not possible!');
UPDATE and DELETE query:
$sql= "DELETE FROM users WHERE username = 'Hola';";
$sql.= "UPDATE users SET foreign_key_checks = 0 WHERE username = 'Hola'"; /* I made a guess here*/
mysqli_multi_query ($con,$sql) OR Die('SQL Query not possible!');
Check the SET query. I think something is missing. I have changed it to what I think was your aim.
The connection should be established like this:
$Hostname = "Your host name mostly it is ("localhost")";
$User = "Your Database user name default is (root)"//check this in configuration files
$Password = "Your database password default is ("")"//if you change it put the same other again check in config file
$DBName = "this your dataabse name"//that you use while making database
$con = new mysqli($Hostname, $User , $PasswordP , $DBName);
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
In this query:
put categorias in magic quotes(`) and column names also
For your next query do this:
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
Change to:
$sql= "SET foreign_key_checks = 0; DELETE FROM `users` WHERE `username` = 'Hola'";
I'm kinda new to PHP and only using it for the backend of my Android App.
I've got three strings that I'm sending to the PHP from my Android App. I want to query a table called 'users' and find the userid of the username that was sent from my Android App and then inset the data into a seperate table called 'msg'.
I've tried for my life and I cannot get it to work, plus I haven't even finished.
thanks and helping me would be pretty amazing, as I'm new to PHP and can't finish off the rest of the code.
PHP:
<?php
$username = $_POST['username'];
$msg = $_POST['msg'];
$frienduser = $_POST ['frienduser'];
/*mysql data below */
$dbc = mysql_connect('localhost', 'removemypasswords', 'again');
if(!dbc) {
die("Something went wrong! Try again...");
}
/* select database */
$db_select = mysql_select_db("andagain, $dbc");
if (!db_select){
die("Can't connect :" .mysql_error);
}
$query = mysql_query("SELECT FROM users WHERE usernames ='$usernames'");
$query1 = mysql_query(INSERT INTO `gtanews1_zips54`.`msg` (
`id` ,
`friendid` ,
`msg`
)
VALUES (
'$query', '$frienduser', 'msg'
);
echo ($msg);
?>
how about putting quotes around $query1 like
$query1 = mysql_query("INSERT INTO gtanews1_zips54.msg (`id` ,`friendid` ,`msg`)
VALUES ('$query', '$frienduser', 'msg')");
Should be
$query = mysql_query("SELECT * FROM users WHERE usernames ='$username'");
$result = mysql_fetch_array($query);
$query1 = mysql_query("INSERT INTO gtanews1_zips54.msg (id,friendid,msg) VALUES ('" . $result['yourField'] . "', '$frienduser','$msg')");
your mysql select db code is wrong. you need to have the quotes before the comma
mysql_select_db("andagain", $dbc);
also place quotes at the end of your query
$query = mysql_query("SELECT FROM users WHERE usernames ='$usernames'"); $query1 = mysql_query(INSERT INTO `gtanews1_zips54`.`msg` ( `id` , `friendid` , `msg` ) VALUES ( '$query', '$frienduser', 'msg' )");
There's a lot going wrong here:
<?php
$username = $_POST['username'];
$msg = $_POST['msg'];
$frienduser = $_POST ['frienduser'];
/*mysql data below */
$dbc = mysql_connect('localhost', 'removemypasswords', 'again');
if(!$dbc) { //- You forgot the dollar $ sign on $dbc
die("Something went wrong! Try again...");
}
/* select database */
$db_select = mysql_select_db("andagain", $dbc); //- You had the entire thing quoted, quotes are just around "andagain"
if (!db_select){
die("Can't connect :" .mysql_error()); //- You forgot the parentheses after mysql_error
}
$query = mysql_query("SELECT FROM users WHERE usernames ='$usernames'");
//- You need to actually get the results out of the query object
$row = mysql_fetch_assoc($query);
if (!$row) {
die('User not found');
}
$user_id = $row['id']; //- Or whatever the column is called
$query1 = mysql_query("INSERT INTO `gtanews1_zips54`.`msg` (
`id` ,
`friendid` ,
`msg`
)
VALUES (
'$user_id', '$frienduser', 'msg'
"); //- You forgot to put quotes around this query
echo ($msg);
?>
And that's just to start, there may be other problems depending on your database schema / data transfer format.
Also, you're wide open to SQL injection.
your code have many errors .
$db_select = mysql_select_db (andagain, $dbc);
$query = mysql_query('SELECT FROM users WHERE usernames ="$usernames"');
since Stackoverflow is not a community for fixing codes bugs ..so i am leaving this job for you .
below are some points which can help you to fix all errors ?
Variable-substitution cann't be dont with single quotes (') . double quotes allow variable substitution .
to escape quotes inside quotes , we use \
parameter cannot be encapsulated with double quotes .