cant insert data into postgresDB in php - php

im having trouble inserting my data's from textbox into postgresdb.
my insert into tbl_ingredients is working fine but my insert into tbl_item is having a troubles can't figure it out how and where?
Connect();
$sql="INSERT INTO tbl_item VALUES('$itemname', '$highthreshold', '$lowthreshold', '$Qpunit', '$description', '$date');";
$iteminfo = pg_query($sql);
$sql1="SELECT MAX(itemid) as newid FROM tbl_item;";
$iden_new = pg_query($sql1);
$fetched_row = pg_fetch_row($iden_new,NULL,PGSQL_BOTH);
$newid=$fetched_row['newid'];
$sql2="INSERT INTO tbl_ingredient VALUES('$newid', '$Brandname');";
$ingredients = pg_query($sql2);
CloseDB();
if(!$sql)
{
$sucmsg = "Successfully added new Item, ".ucfirst($itemname)."!";
echo $sucmsg;
}
else
{
echo "error in saving data";
}
table structure:
tbl_item
itemid>itemname>highquantitythreshold>lowquantitythreshold>qntyperunit>Itemtype>description>dateadded
tbl_ingredient
itemid>brandname
im getting wamp "Warning: pg_query(): Query failed: ERROR: invalid input syntax for integer: "Strawberry" LINE 1: INSERT INTO tbl_item VALUES('Strawberry', '6', '3', '1300gra... ^ in D:\Wamp\wamp\www\Php\CTea\AddItem.php on line 247"
can someone lend me a helping hand thanks!.

You either need to use NULL ->
$sql="INSERT INTO tbl_item VALUES(NULL, '$itemname', '$highthreshold', '$lowthreshold', '$Qpunit', '$description', '$date');";
OR
You need to specify the columns you are inserting into ->
$sql="INSERT INTO tbl_item (itemname, highquantitythreshold, lowquantitythreshold, qntyperunit, description, dateadded) VALUES('$itemname', '$highthreshold', '$lowthreshold', '$Qpunit', '$description', '$date');";
Without the NULL or column name, the database does not know that you are skipping the first column - itemid - so it will try to insert the 1st value into that column.
from the manual - http://www.postgresql.org/docs/9.1/static/sql-insert.html
The target column names can be listed in any order. If no list of
column names is given at all, the default is all the columns of the
table in their declared order; or the first N column names, if there
are only N columns supplied by the VALUES clause or query. The values
supplied by the VALUES clause or query are associated with the
explicit or implicit column list left-to-right.
Each column not present in the explicit or implicit column list will
be filled with a default value, either its declared default value or
null if there is none.

Related

MYSQL - append or insert value into a column depending on whether it's empty or not

As title says, im trying to append a string to a VARCHAR column in my table.
The string is something like " //string ", forward slashes will be used later to explode the string to an array in PHP.
I was wondering if there's a way in MYSQL to perform a CONCAT(columnname, "//string") if the column is empty, otherwise perform a normal UPDATE ... SET ... WHERE . In this way, i will avoid the first value of my future exploded string to be a "//string" with forward slahes.
also, above I 've used bold characters for "in MYSQL" because I know i could first query the DB (to check if the column is empty) with something like:
$q = $conn->dbh->prepare('SELECT columnname FROM tablename WHERE username=:user');
$q->bindParam(':user', $username);
$q->execute();
$check = $q->fetchColumn();
and then leave PHP decide which operation perform:
if ($check != '') { // PERFORM A CONCAT }
else { // PERFORM AN UPDATE }
but this would mean a waste of time/resources due to 2x database calls and more PHP code.
thanks.
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
That means in your case:
INSERT INTO tablename (id,columnname) VALUES (1,'//string')
ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');
http://sqlfiddle.com/#!9/bd0f4/1
UPDATE Just to show you your options:
http://sqlfiddle.com/#!9/8e61c/1
INSERT INTO tablename (id, columnname) VALUES (1, '//string')
ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');
INSERT INTO tablename (id, columnname) VALUES (1, '//string')
ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');
INSERT INTO tablename (id, columnname) VALUES ((SELECT id FROM tablename t WHERE columnname='blahblah'), '//string')
ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');
INSERT INTO tablename (id, columnname) VALUES ((SELECT id FROM tablename t WHERE id=2), '//string')
ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');
INSERT INTO tablename (id, columnname) VALUES ((SELECT id FROM tablename t WHERE columnname='newone'), '//newone')
ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//newone');
If what you want is this:
first string: column will contain 'firststring'
second string: column will contain 'firststring//secondstring'
then do the update like this:
UPDATE tablename SET columnname = CONCAT( IF(IFNULL(columnname,'')='','',CONCAT(columnname,'//')), :string) WHERE username=:user

Warning: SQLite3::query() [sqlite3.query]: 1 values for 2 columns

I am using an sqlite3 db in php wich i want to fill, i need to fill in a foreign key and the name of the subcategory, here's the code that i use.
var_dump('"'.$categoryRow.','.$subcategory.'"');
$db->query('INSERT INTO Subcategories (fk_cat, subcat) VALUES ("'.$categoryRow.','.$subcategory.'")');
$subCategoryRow = $db->lastInsertRowID();
die();
But when i run this code, it returns:
string(11) ""1,subcategory""
Warning: SQLite3::query() [sqlite3.query]: 1 values for 2 columns in /mysite/product.php on line 94
but when i log them i get 1 and ''subcategory' back.
Does anyone know what i am doing wrong?
your variables should be both surrounded by double quotes
sql should be insert into (field1, field2) values ("value1","value2")
var_dump('"'.$categoryRow.','.$subcategory.'"');
$db->query('INSERT INTO Subcategories (fk_cat, subcat) VALUES ("'.$categoryRow.'","'.$subcategory.'")');
$subCategoryRow = $db->lastInsertRowID();
die();

mysql insert query inserts zeros with some values

I am a beginner in php and mysql and am trying to write code to insert values into a table. The problem is some variables like $upval and $aday are inserted correctly but $course and $chour are inserted as zeros, notice that I echo the ($course and $chour) before the insert query and the echo prints the correct values(not zero).
$res1=mysql_fetch_object($result1);
$course =$res1->cid;
$result2= mysql_query("select thoure from $tbl_name3 where cid='$course'");
$res2=mysql_fetch_object($result2);
$chour =$res2->thoure;
$sql ="insert into $tbl_name2 (SID,Cid,Tid,Adate,Ahoure) values ('$upval','$course','2','$aday','$chour')";
$result = mysql_query($sql);
also I try another way to write query but the same problem
$sql ="insert into $tbl_name2 (SID,Cid,Tid,Adate,Ahoure) values ('$upval','".$res1->cid."','2','$aday','".$res2->thoure."')";
This is your SQL statement:
$sql=insert into absent (SID, Cid, Tid, Adate, Ahoure)
values ('65','','2','2014-05-06','')
If Cid is being inserted as 0, that is because Cid is a numeric type (probably integer of some sort) and strings are converted to numbers. So, '' is inserted as to 0 into a number. Why the value is set to an empty string, I do not know.

Inserting data in one table which has two foreign keys (php)

I'm new to this site, and I need some help with my record system. I need to insert the grades of the students into the grades table, which has the columns: gradeid (PK, auto_increment), studentid (FK), courseid (FK), midterm, endterm, final, remark.
The studentid (FK) gets the number from the studentid (PK) of addrec table.
The courseid (FK) gets the number from the courseid (PK) of course table.
Here are the codes that I have experimented (for the umpteenth time) but still got no results:
<?php
$host="localhost";
$username="root";
$password="";
$db_name="studentrec";
$studentid = $_GET['id'];
$sql1="SELECT studentid FROM addrec WHERE studentid='$studentid'";
if(mysql_query($sql1))
{
$courseid = $_GET['courseid'];
$sql2 = "SELECT courseid FROM course WHERE courseid='$courseid'";
if (mysql_query ($sql2))
{
$sql3="INSERT INTO grades(`studentid`, `courseid`, `midterm`, `endterm`, `final`, remark`) VALUES ('$studentid','$courseid','$_POST[midterm]','$_POST[endterm]','$_POST[final]','$_POST[remark]' )";
}
if (mysql_query($sql3))
{
// Success
}
else
{
die('Error on query 2: ' . mysql_error($con));
}
}
?>
There are no errors whenever I hit the Submit button, but the data I put in the text boxes won't insert into the grades table. Help, please? Or suggestions? I'm still studying stuff about PHP. Thank you. :)
youre not connecting to the mySQL : http://www.php.net/manual/en/function.mysql-connect.php
also you might notice the big red box on php.net, you should move to PDO or MySQLi.
Query contains error. Try this
INSERT INTO grades(studentid,courseid,midterm,endterm,final,remark) VALUES ('$studentid','$courseid','$_POST[midterm]','$_POST[endterm]','$_POST[final]','$_POST[remark]' );
do your db connection first than select db and than
try to replace
$sql3="INSERT INTO grades(`studentid`, `courseid`, `midterm`, `endterm`, `final`, remark`) VALUES ('$studentid','$courseid','$_POST[midterm]','$_POST[endterm]','$_POST[final]','$_POST[remark]' )";
with
$sql3="INSERT INTO grades(`studentid`, `courseid`, `midterm`, `endterm`, `final`, remark`) VALUES('$studentid','$courseid','".$_POST['midterm']."','".$_POST['endterm']."','".$_POST['final']."','".$_POST['remark']."' )";
You actual query is like
INSERT INTO grades(`studentid`, `courseid`, `midterm`, `endterm`, `final`,remark`)
VALUES
('$studentid','$courseid','$_POST[midterm]','$_POST[endterm]','$_POST[final]','$_POST[remark]' );
You need to put opening ` (tild) before column remark, so your query will looks like
INSERT INTO grades(`studentid`, `courseid`, `midterm`, `endterm`, `final`,`remark`)
VALUES
('$studentid','$courseid','$_POST[midterm]','$_POST[endterm]','$_POST[final]','$_POST[remark]');

PHP Assosiative array Insert into if data doesnt exist in table

I have an assosiative array in PHP which is inserting data into a table
foreach($array as $key => $value){
$query = "INSERT INTO live_list (file_id, date) SELECT ('$key', '$value') FROM dual WHERE NOT EXISTS (SELECT * FROM live_list WHERE file_id = '$key')";
mysqli_query($link, $query) or die('Query failed: ' . mysqli_error($link));
}
However as I have moved from an indexed array to an assosiative array, I can't figure out how to insert this data ONLY if the data in my array does not exist in my table.
Query failed: Operand should contain 1 column(s)
Now I am recieving this error
Any help will be great!
Why the use of a sub-query?
Assuming file_id is a unique field (i.e. no duplicates in the whole table), make it a unique index on the table if it isn't already:
ALTER TABLE live_list
ADD UNIQUE (file_id)
and change your query to
INSERT INTO live_list (file_id, date)
VALUES ('$key', '$value')
ON DUPLICATE KEY UPDATE date = date;
This means that it will simple "update" the value of date to what it already is if it encounters a duplicate key.
Although you should look to bind your parameters to protect against sql injection.
You could do this:
INSERT INTO live_list (file_id, date)
SELECT '$key', '$value'
FROM dual
WHERE NOT EXISTS (SELECT * FROM live_list WHERE file_id = '$key')
DUAL is a dummy table. The logic is that if the sub query does not exist, the dummy table returns one row with the desiered input.

Categories