syntax for MySQL INSERT with an array of columns - php

I'm new to PHP and MySQL query construction. I have a processor for a large form. A few fields are required, most fields are user optional. In my case, the HTML ids and the MySQL column names are identical. I've found tutorials about using arrays to convert $_POST into the fields and values for INSERT INTO, but I can't get them working - after many hours. I've stepped back to make a very simple INSERT using arrays and variables, but I'm still stumped. The following line works and INSERTs 5 items into a database with over 100 columns. The first 4 items are strings, the 5th item, monthlyRental is an integer.
$query = "INSERT INTO `$table` (country, stateProvince, city3, city3Geocode, monthlyRental) VALUES ( '$country', '$stateProvince', '$city3', '$city3Geocode', '$monthlyRental')";
When I make an array for the fields and use it, as follows:
$colsx = array('country,', 'stateProvince,', 'city3,', 'city3Geocode,', 'monthlyRental');
$query = "INSERT INTO `$table` ('$colsx') VALUES ( '$country', '$stateProvince', '$city3', '$city3Geocode', '$monthlyRental')";
I get a MySQL error - check the manual that corresponds to your MySQL server version for the right syntax to use near ''Array') VALUES ( 'US', 'New York', 'Fairport, Monroe County, New York', '(43.09)' at line 1. I get this error whether the array items have commas inside the single quotes or not. I've done a lot of reading and tried many combinations and I can't get it. I want to see the proper syntax on a small scale before I go back to foreach expressions to process $_POST and both the fields and values are arrays. And yes, I know I should use mysql_real_escape_string, but that is an easy later step in the foreach. Lastly, some clues about the syntax for an array of values would be helpful, particularly if it is different from the fields array. I know I need to add a null as the first array item to trigger the MySQL autoincrement id. What else?
I'm pretty new, so please be specific.

$query = "INSERT INTO `$table` ('$colsx') etc...
isn't going to work. $colsx is an array, so what you're going to end up producing is literally
$query = "INSERT INTO `sometable` ('Array')
^^^^^---yes, it'll literally say "Array"
You'll have to preprocess the array into a string before doing this, e.g.
$colsx = array(...);
$col_string = implode(',', $colsx);
$query = "INSERT INTO `$table` ($col_string) etc...";

Related

Error in SQL syntax for INSERT INTO

I am trying to insert data into a MySQL table which contains 19 columns however not all the rows are being stored.
Only a few of the rows are being stored and I'm getting the error message:
There is error in your SQL syntax. Check your syntax for your SQL version.
Although when I echo the variables, they are working fine.
My code is as follows:
$sql="CREATE TABLE tb(tb1 VARCHAR(50),tb2 VARCHAR(50),tb3 VARCHAR(100),tb4 VARCHAR(100),tb5 VARCHAR(100),tb6
VARCHAR(100),tb7 VARCHAR(100),tb8 VARCHAR(100),tb9 VARCHAR(100),tb10 VARCHAR(100),tb11 VARCHAR(100),tb12
VARCHAR(100),tb13 VARCHAR(100),tb14 VARCHAR(100),tb15 VARCHAR(100),tb16 VARCHAR(100),tb17 VARCHAR(100),tb18
VARCHAR(100),tb19 VARCHAR(100))";
foreach ($xml->product as $character)
{
$a1=$character->category->primary;
$b2=$character->category->secondary;
$c3=$character->URl->product;
$d4=$character->URL->productImage;
$e5=$character->URL->buy;
$f6=$character->description->short;
$g7=$character->description->long;
$h8=$character->discount->amount;
$i9=$character->discount->time;
$j10=$character->price->sale;
$k11=$character->price->retail;
$l12=$character->brand;
$m13=$character->shipping->cost->amount;
$n14=$character->shipping->cost->currency;
$o15=$character->shipping->information;
$p16=$character->shipping->availability;
$q17=$character->keywords;
$r18=$character->upc;
$s19=$character->m1;
$sql="INSERT INTO tb
(tb1,tb2,tb3,tb4,tb5,tb6,tb7,tb8,tb9,tb10,tb11,tb12,tb13,tb14,tb15,tb16,tb17,tb18,tb19) VALUES
('$a1','$b2','$c3','$d4','$e5','$f6','$g7','$h8','$i9','$j10','$k11','$l12','$m13','$n14','$o15','$p16','$q17','$r18','$s19')";
mysql_query($sql,$conn);
}
If ANY of your values contains an apostrophe, your query breaks.
Use mysql_real_escape_string() around each of your values as a quick fix.
A more correct and future-proof solution is to stop using mysql_* functions and instead start using PDO, making use of features like prepared statements as these take care of escaping things for you.
This is a formatted comment. A frequent mistake with this type of query is that the number of fields does not match the number of values. That is easier to troubleshoot if you type your query like this:
insert into table (
field1
, field2
, etc
)
values (
value1
, value2
, etc
)
This format makes it easier to count the number of fields and values. Sometimes the problem is with a certain field or value. This format, with the commas at the start of the line, make it easier to comment out blocks of code to isolate the problem.

how to insert radio button values and dropdown values to database postgresql using php

I want to insert the data into postgresql database which includes radio button and dropdwn box. I tried 3 different insert queries.
1)
$query = sprintf("INSERT INTO onf VALUES('%s','%s','%s','%s','%s','%s','%d')",$_REQUEST['title'],$_REQUEST['name'],$_REQUEST['district'],$_REQUEST['rurban'],$_REQUEST['taluk'],$_REQUEST['village'],$_REQUEST['wardno']);
2)
$qry="INSERT INTO onf(title, name, district,rurban,taluk,village,wardno) VALUES ('$tile', '$name', '$district','$rurban','$taluk','$village','$wardno')";
3)
$qy="INSERT INTO onf(title, name, district,rurban,taluk,village,wardno) VALUES (('$_POST[title]','gen','$_POST[gen]),'$_POST[name]','$_POST[district]','$_POST[rurban]','$_POST[taluk]','$_POST[village]','$_POST[wardno]')";
$res = pg_query($db,$qy);
My problem is in 1st query oly name alone gets inserted and in 2nd , 3rd no record gets inserted. Y dropdown nd radio button is not inserting into database?
Tanx in advance..
May just be because neither of those 3 is proper PHP code.
Query 1:
Don't use $_REQUEST. Use $_POST.
Query 2:
Unless you have register_globals turned on, which I SERIOUSLY hope you don't, your vars ($tile, $name, etc.) will not contain the information submitted by the form. Again, you want to use $_POST.
Query 3:
Your variables aren't properly escaped. Generally, I recommend not embedding variables into double-quoted strings if you don't quite have a grasp on string concatenation in PHP. Use single-quoted strings and build them by breaking the string and concatenating with ..
Now, I feel like your second query is the closest to what you want, so try this:
$qry = '
INSERT INTO onf (
title,
name,
district,
rurban,
taluk,
village,
wardno
) VALUES (
"'.$_POST['tile'].'",
"'.$_POST['name'].'",
"'.$_POST['district'].'",
"'.$_POST['rurban'].'",
"'.$_POST['taluk'].'",
"'.$_POST['village'].'",
"'.$_POST['wardno'].'"
);
';

How can I send a PHP variable array to a MySQL database?

So I have a variable array created from scraping a plaintext data string from a webpage (using Simple HTML DOM Parser class). This variable is the formatted to make it more concise and useful.
I now wish to export this data into a MySQL table where the table name is the webpage title (scraped separately) and the data input is an array, where each word extracted from the webpage is a separate data record.
Here is my code (where $trimmed is a formatted variable string of data scraped from a user input webpage):
$trimmed->plaintext=trim($trimmed->plaintext);
$array = (explode(" ", $trimmed->plaintext));
$printarray = print_r ($array);
mysql_select_db("test", $connect) or die ('Could not find database.');
$sql = "CREATE TABLE '$title'";
$myquery = sprintf("INSERT INTO WebPage '%s'
VALUES '%s'",
mysql_real_escape_string($title->plaintext),
mysql_real_escape_string($printarray));
$result = mysql_query($myquery);
if (!$result) {
$message = '<br /><br /><br /> Invalid query: ' . mysql_error() . "\n";
$message .= '<br /><br /> Whole query entered here: ' . $myquery;
die($message);
}
The error is recieve when trying this is:
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Example Domain' VALUES '1'' at line 1
Whole query entered here: INSERT INTO WebPage 'Example Domain' VALUES '1'
I can provide more code if needed, and sorry in advance if I haven't explained this very well; I am quite new to this.
Thanks in advance.
Your SQL:
INSERT INTO WebPage 'Example Domain' VALUES '1'
is not valid. Maybe you meant:
INSERT INTO `WebPage` ('Example Domain') VALUES ('1')
On a side note, if Example Domain is indeed a column name: you should really avoid spaces in field's names.
There are lot's of errors here.
First, The SQL you're generating for the insert looks incorrect:
INSERT INTO tableName (fields) VALUES (values)
Your code says:
INSERT INTO WebPage 'plainText' VALUES (array)
You should remove Webpage if you want to create a table named like the webpage title. Plus, it must be a single word (replace empty spaces with something like '_').
Second, you need to create the table. You need the proper CREATE TABLE structure prior to doing the insert.
Third, your echo print_r won't work for inserting a value per field (column). You need to iterate the array and for each key insert a value. But you should had already done this for creating the table columns.
It looks as if you are trying to incorporate the output from print_r in your query. This isn't possible as print_r is a function that outputs data from an array to the page.
In order to store the contents of an array in the database you can use json_encode to convert the array to a string. Then use json_decode when retrieving it so change it back into a php array.
E.g.
$myquery = sprintf("INSERT INTO `WebPage` ('%s')
VALUES ('%s')",
json_encode($title->plaintext),
json_encode($array)); //not $printarray as that is not an actual array
edit: As others have noted, mysql_real_escape_string is a deprecated function so other methods should be used to escape characters.
edit2: serialize could also be used in place of json_encode although I am not sure of the relative advantages/disadvantages. A more ideal method would be to restructure your database table to accommodate all contents of the array as a separate piece of data although this may sometimes not be practical.

SQL - Inserting multiple row values into a single column

I need help on a method of inserting values into a single column on different rows.
Right now, I have an imploded array that gives me a value such as this:
('12', '13', '14')
Those numbers are the new IDs of which I wish to insert into the DB.
The code I used to implode the array is this:
$combi = "('".implode("', '",$box)."')"; // Where $box is the initial array
The query of which I plan to use gets stuck here:
mysql_query("INSERT INTO studentcoursedetails (studentID) VALUES
One option would be to repeat this, but I cant, because the array will loop; there might be 3 IDs, there might be 20.
A loop doesn't seem right. Any help would be appreciated.
For inserting more than one value into a table you should use (value1), (value2) syntax:
$combi = "('".implode("'), ('",$box)."')";
PS: This feature is called row value constructors and is available since SQL-92
Can you not do something like this:
for($x = 0; $x < count($box); $x++)
{
mysql_query("INSERT INTO studentcoursedetails (studentID) VALUES ($box[$x]);
}
This will work directly on your array, insert a new row for each value in $box and also prevent the need to implode the array to a comma delimited string
Storing ids as a comma delimited string might initially seem like a simple model but in the long term this will cause you no end of trouble when trying to work with a non-normalised database.
Some flavors of sql allow compound inserts:
insert into studentcoursedetails (studentid) values
(1),
(2),
(3),
If you are using MySQL, you can insert multiple values in a single sentence:
sql> insert into studentcoursedetails (studentID)
> values (('12'), ('13'), ('14'));
So, you just need to build that string in PHP and you are done.
You can still create the statement via implode. Just don't use VALUES; use SELECT instead
$combi = " ".implode(" UNION ALL SELECT ",$box)." "; // Where $box is the initial array
mysql_query("INSERT INTO studentcoursedetails (studentID) SELECT " . $combi)
The SELECT .. union is portable across many dbms.
Note on the IDs - if they are numbers, don't quote them.
Check to see if there is a variant of the mysql_query function that will operate on an array parameter.

Is it bad to put a MySQL query in a PHP loop?

I often have large arrays, or large amounts of dynamic data in PHP that I need to run MySQL queries to handle.
Is there a better way to run many processes like INSERT or UPDATE without looping through the information to be INSERT-ed or UPDATE-ed?
Example (I didn't use prepared statement for brevity sake):
$myArray = array('apple','orange','grape');
foreach($myArray as $arrayFruit) {
$query = "INSERT INTO `Fruits` (`FruitName`) VALUES ('" . $arrayFruit . "')";
mysql_query($query, $connection);
}
OPTION 1
You can actually run multiple queries at once.
$queries = '';
foreach(){
$queries .= "INSERT....;"; //notice the semi colon
}
mysql_query($queries, $connection);
This would save on your processing.
OPTION 2
If your insert is that simple for the same table, you can do multiple inserts in ONE query
$fruits = "('".implode("'), ('", $fruitsArray)."')";
mysql_query("INSERT INTO Fruits (Fruit) VALUES $fruits", $connection);
The query ends up looking something like this:
$query = "INSERT INTO Fruits (Fruit)
VALUES
('Apple'),
('Pear'),
('Banana')";
This is probably the way you want to go.
If you have the mysqli class, you can iterate over the values to insert using a prepared statement.
$sth = $dbh->prepare("INSERT INTO Fruits (Fruit) VALUES (?)");
foreach($fruits as $fruit)
{
$sth->reset(); // make sure we are fresh from the previous iteration
$sth->bind_param('s', $fruit); // bind one or more variables to the query
$sth->execute(); // execute the query
}
one thing to note about your original solution over the implosion method of jerebear (which I have used before, and love) is that it is easier to read. The implosion takes more programmer brain cycles to understand, which can be more expensive than processor cycles. premature optimisation, blah, blah, blah... :)
One thing to note about jerebear's answer with multiple VALUE-blocks in one INSERT:
It can be rather dangerous for really large amounts of data, because most DBMS have an upper limit on the size of the commands they can handle. If you exceed that with too many VALUE-blocks, your insert will fail. On MySQL for example the limit is usually 1MB AFAIK.
So you should figure out what the maximum size is (ideally at runtime, might be available from the database metadata), and make sure you don't exceed it by spreading your lists of values over several INSERTs.
I was inspired by jerebear's answer to build something like his second option for one of my current projects. Because of the shear volume of records I couldn't save and do all the data at once. So I built this to do imports. You add your data, and then call a method when each record is done. After a certain, configurable, number of records the data in memory will be saved with a mass insert like jerebear's second option.
// CREATE TABLE example ( Id INT, Field1 INT, Field2 INT, Field3 INT);
$import=new DataImport($dbh, 'example', 'Id, Field1, Field2, Field3');
foreach ($whatever as $row) {
// add data in the order of your column definition
$import->addValue($Id);
$import->addValue($Field1);
$import->addValue($Field2);
$import->addValue($Field3);
$import->nextRow();
}
$import->lastRow();

Categories