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

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();

Related

How to make PHP MYSQL Insert query only with values which are existed for certain columns?

I have 17 columns in my DB
I'm inserting values from different sources. Somewhere I haven't, for example, company/company_info values (I'm setting in PHP FALSE values for relevant variables).
So, I need some kind of PHP INSERT query to insert only not empty variables and columns of certain list.
For example, I could do:
$q = "INSERT INTO `$tname` (`phone`,`location`, `pagelang`, `company`, `company_url`, `phone_no_cc`, `phone_type`, `operator`, `pageviews`, `rating`, `comments_number`, `activity_by_days`, `activity_by_hours`) VALUES (
'$main_number', '$number_advanced_info[location]', '$pagelang', '$company[name]', '$company[site]', '$number_advanced_info[number_no_countrycode]', '$number_advanced_info[phone_type]', '$number_advanced_info[operator]', '$searches_comments[searches]', '$rating', '$searches_comments[comments]', '$history_search', '$daily_history'
);";
With insert of 14 columns and their values.
But sometimes I need to insert less columns/values and let MYSQL set default values for not listed columns. For Example, I want to insert only 5 columns.
$q = "INSERT INTO `$tname` (`phone`,`location`, `pageviews`, `rating`) VALUES (
'$main_number', '$number_advanced_info[location]', '$searches_comments[searches]', '$rating'
);";
Is there some CLASS or any solution like binding values which will automatically build query depending which values are not NULL?
I need some kind of code:
if (!$phone) {
$columns .= "`column_name`," ;
$values .= "value";
}

Updating A Column if a Value Is Changed

I have a database with a column representing line numbers. The line numbes correspond to lines in a text area.
Say if I have 10 lines and I go to line 5 and make a new insert, I will now have 11 lines. This means that all the line number values after the insert statement (I have my insert statement working fine) need to be updated by one. Is there a way PHP can update these multiple line number values? I've tried using the LAST_INSERTID() function and adding 1 but with no success.
My attempts:
INSERT INTO Table(LineNumber, Text) VALUES ('LAST_INSERT_ID() + 1', '' )";
Which didn't really make sense
if($linenumber <= mysqli_insert_id() {
$update = "UPDATE Table SET LineNumber='$linenumber' ";
}
I also tried a for loop in the javascript which calls the function to try to carry out an UPDATE statement for each value of Line Number
You can query the database and do a mass update:
UPDATE TABLE *tablename* SET line_number = line_number + 1 WHERE line_number >= 5
and then:
INSERT INTO *tablename* (line_number, ...othervals) VALUES (5, ...othervals)

insert multiple row in sql database with php

I want to insert multiple row in sql with php, after checking few conditions.
The condition is, if 'cat' and 'preview' is not null then row one will be submitted and if 'cat','preview','cat2','preview2' is not null then two row will submitted with first row's value 'cat' and'preview and 2nd row's value 'cat2' and 'preview2'.
i tried these code, but i see - Undefined variable: sql
whats wrong with my condition?
else if(isset($cat)and ($cat!=="") and isset($preview)and ($preview=="") and
(isset($cat2))and ($cat2!=="") and (isset($preview2))and ($preview2!==""))
{
$sql = "INSERT INTO files (cat, preview, file, art) VALUES
('".$cat."','".$preview."','".$file."','".$art."')
('".$cat2."','".$preview2."','".$file2."','".$art2."')";
}
your code just had query mistake that you wanted to insert two row in just one insert command.use this code that seperates the insert commands :
else if(!empty($cat) and !empty($preview) and
!empty($cat2) and !empty($preview2))
{
$sql = "INSERT INTO files (cat, preview, file, art) VALUES
('".$cat."','".$preview."','".$file."','".$art."');";
$sql .= " INSERT INTO files (cat, preview, file, art) VALUES ('".$cat2."','".$preview2."','".$file2."','".$art2."');";
}
I personally think that the logic you have with your conditions may need rethinking. For instance, if you save your values into arrays, you can automate this process:
// Save first values
$sqlArgs[] = array($cat,$preview,$file,$art);
// Save second values
$sqlArgs[] = array($cat2,$preview2,$file2,$art2);
// Loop through each row.
foreach($sqlArgs as $key => $array) {
// If the `cat` or the `preview` empty, skip
if(!empty(trim($array[0])) && !empty(trim($array[1])))
$sql[] = "'".implode("','",$array)."'";
}
// If the sql has rows continue
if(!empty($sql)) {
// Build the statement rows with implode() of values.
// This assumes these are not user-input values or that you have
// thoroughly sanitized the values.
$statement = "INSERT INTO `files` (`cat`,`preview`,`file`,`art`) VALUES (".implode("),(",$sql).")";
// Preview statement
print_r($statement);
}
This approach will take care of 0,1, or 2 inserts (or more if necessary) based on the two keys cat & preview being filled.
Insert query with ; is not one query...
For example
Insert into mytable (a,b,c) values (1,2,3);
Insert into mytable (a,b,c) values (4,5,6);
Insert into mytable (a,b,c) values (7,8,9);
is not one query, this is 3 insert queries.
That is mean when insert values (4,5,6) have error, values (1,2,3) query is successed....
We want if one row failed, all insert query fail.
Therefore, we don't write insert query with ;
Example query:
Insert into mytable values(1, 2, 3), (4, 5, 6), (7, 8, 9);

cant insert data into postgresDB in 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.

Multiple mysql INSERT statements in one query php [duplicate]

This question already has answers here:
Insert multiple rows with one query MySQL
(5 answers)
Closed 2 years ago.
Is this legal?
$string1= "INSERT INTO....;";
$string1 .= "INSERT INTO....;";
$string1 .= "INSERT INTO....;";
mysql_query($string1) or die(mysql_error());
For what it's worth, and depending on if you're inserting the same data into
the same tables, it's much better to insert multiple values with the one insert
e.g.
INSERT INTO a VALUES (1,23),(2,34),(4,33);
INSERT INTO a VALUES (8,26),(6,29);
No, mysql_query() only allows one query at a time.
You can insert multiple rows like this:
INSERT INTO table (col1, col2)
VALUES (1, 2), (3, 4), (5, 6)
From MySQL dev support MySQL dev forum
INSERT INTO table (artist, album, track, length)
VALUES
("$artist", "$album", "$track1", "$length1"),
("$artist", "$album", "$track2", "$length2"),
("$artist", "$album", "$track3", "$length3"),
("$artist", "$album", "$track4", "$length4"),
("$artist", "$album", "$track5", "$length5");
So insert goes as normal as always:
naming first the table name where we want to insert new row,
followed by naming column names in round brackets (Note: Not needed if you want to insert ALL columns),
followed by VALUES key name and then in round brackets comes the values that you want to insert for new ROW in the above table,
followed by COMMA and then another pair of round brackets with new values for new row in the mentioned table above
and this repeats N-times as long you have the data to insert.
Happy inserting multiple values with ONE insert statement. :)
Copy/paste example within a function and a loop (suppose $ids is an array)
public function duplicateItem($ids)
{
if (isset($ids[0])){ //at least one item
$sqlQuery = "INSERT INTO items (item_id, content) VALUES ";
for($i=0; $i<count($ids); $i++) {
if ($i == count($ids)-1){
$sqlQuery .= "(".$ids[$i][0].", '".$ids[$i][1]."');";
}else{
$sqlQuery .= "(".$ids[$i][0].", '".$ids[$i][1]."'),";
}
}
mysql_query($sqlQuery) or die('Error, insert query failed: '.mysql_error());
}
}
In general, that's valid SQL since each statement ends with a semicolon, but PHP doesn't allow you to send more than one query at a time, in order to protect against SQL injection attacks that might exploit a poorly written script.
You can still use a syntax like:
INSERT INTO foo VALUES ('a1', 'b1'), ('a2', 'b2');
INSERT INTO table (a,b) VALUES (1,2), (2,3), (3,4);
No. They are separate queries, and must be called as such.
// if $data is an array
$sqlQuery ="INSERT INTO tableName(col1, col2) VALUES ";
for($i=0; $i<count($data); $i++) {
$sqlQuery .="(".$data[$i][0].", '".$data[$i][1]."'),";
}
$sqlQuery = rtrim($sqlQuery, ','); // Remove last comma
mysql_query($sqlQuery) or die('Error, insert query failed: '.mysql_error());

Categories