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.
Related
I've been fighting with a bit of code for a week now, not seeing what the heck is wrong...
I have a gaming site I'm trying to build new character sheets for, the form is all done, the action pointing to another page that is strictly the sql for inserting the information into the database. We have good connection, but it is hanging at the second insert statement. The code was working previously, but we had to delete the database and rebuild it, resulting in a rebuild of the insert sql lines.
The first portion of the insert code is:
if($_POST['Submit']=="Submit")
{
$sql="INSERT INTO accounts (log_name,owner,account_type,date_joined) VALUES (\"$_POST[char_name]\",\"$_SESSION[logname]\",\"$_POST[account_type]\",NOW())";
$result = mysql_query($sql)
or die("<p>Couldn't add character.<br/>".mysql_error()." in accounts.<br/>Please send this exact message to <a href='mailto:savvannis#houston-by-night.com'>Savvannis</a> with your character's name.</p>");
echo $result;
echo $_SESSION['logname'];
$sql="INSERT INTO topdata (log_name,char_venue,sub_venue,species,char_name,create_date,gender,age,appage,nature,demeanor,concept,description,web_site,view_pword,sfa) VALUES (\"$_SESSION[logname]\",\"$_POST[char_venue]\",\"$_POST[sub_venue]\",\"$_POST[species]\",\"$_POST[char_name]\",NOW(),\"$_POST[gender]\",\"$_POST[age]\",\"$_POST[appage]\",\"$_POST[nature]\",\"$_POST[demeanor]\",\"$_POST[concept]\",\"$_POST[description]\",\"$_POST[web_site]\"\"$_POST[viewpw]\",\"$_POST[sfa]\")";
$result=mysql_query($sql)
or die ("<p>Could not create character.<br/>".mysql_error()." in topdata.<br/>Please send this exact message to <a href='mailto:savvannis#houston-by-night.com'>Savvannis</a> with your character's name.</p>");
echo $result;
When the information is entered into the form and submit is hit, I get the following:
1
Could not create character.
Column count doesn't match value count at row 1 in topdata.
Please send this exact message to Savvannis with your character's name.
I look at the database and the information is entered into the accounts table, so that statement is working, but it is hanging up on the topdata table. It's not echoing the $_SESSION['logname'] and looking at the database, it's not saving the owner, which should be $_SESSION['logname'], so I'm wondering if that statement is now somehow incorrect??
I can't figure out what the heck is wrong. Any and all help would be greatly appreciated.
You have missed a comma here: \"$_POST[web_site]\"\"$_POST[viewpw]\" in your second insert SQL.
It should be \"$_POST[web_site]\", \"$_POST[viewpw]\"
First off the error message is telling you that there is an unequal number of columns and values in your SQL
Lets have a look at that
INSERT INTO topdata (
log_name,
char_venue,
sub_venue,
species,
char_name,
create_date,
gender,
age,
appage,
nature,
demeanor,
concept,
description,
web_site,
view_pword,
sfa
) VALUES (
\"$_SESSION[logname]\",
\"$_POST[char_venue]\",
\"$_POST[sub_venue]\",
\"$_POST[species]\",
\"$_POST[char_name]\",
NOW(),
\"$_POST[gender]\",
\"$_POST[age]\",
\"$_POST[appage]\",
\"$_POST[nature]\",
\"$_POST[demeanor]\",
\"$_POST[concept]\",
\"$_POST[description]\",
\"$_POST[web_site]\"\"$_POST[viewpw]\",
\"$_POST[sfa]\"
)";
Now by formatting your SQL (which is vulnerable to sql injection) I've noticed a missing comma between web_site and viewpw values
I am having a very strange problem inserting values into my mysql database, using php, so i was running a test, the simplest of the simple insert; the following doesnt work:
<?php
include("config.php"); // put the *FULL* path to the file.
mysql_query("INSERT INTO 'lms'.'test2' ('trn') VALUES ('17')");
?>
However the following works:(Note the difference in single quotes)
<?php
include("config.php"); // put the *FULL* path to the file.
mysql_query("INSERT INTO `lms`.`test2` (`trn`) VALUES ('17')");
?>
I really can't see what the problem is could I get sum assistance please
You don't need to encapsulate tables within a query unless they have space or they are reserved words.
INSERT INTO 'lms'.'test2' ('trn') VALUES ('17')
// This makes no real sense to the db. It should be:
INSERT INTO lms.test2 (trn) VALUES ('17')
If the column trn accepts numbers, it really should be:
INSERT INTO lms.test2 (trn) VALUES (17)
With MySQL, you can use the tilted quote character to encapsulate names, but not strings. To enter a string in the query you will have to use normal quotes like '.
You can to this:
select `someTable`.`someColumn` from `someTable`
but not this:
select someTable.someColumn from someTable where myName=`Tommy`;
The correct use would be:
select someTable.someColumn from someTable where myName='Tommy';
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...";
Anyone know how to insert bar/pipe delimited array in an array field?
With comma its working but when I change it to bar it produces error "malformed array literal"
example (works):
insert into table (arrayfield) values ('{"var1","var2","var3"}')
example (doesn't work):
insert into table (arrayfield) values ('{"var1"|"var2"|"var3"}')
btw i'm using postgres 8.2 and PHP and i can't use comma as delimiter for various reasons.
If you can use values without quotes because you know that no pipe is in your data, then you can use:
insert into table (arrayfield) select string_to_array('var1|var2|var3','|');
If you need that your values are quoted on your pipe-delimited string then it gets complicated. If that's the case then I think you should format and quote properly your array using ARRAY['val1','val2','val3'] syntax in PHP.
I am pulling back some data from the twitter query API, and parsing it through PHP like so:
$i =0;
foreach ($tweetArray->results as $tweet) {
$timeStamp = strtotime($tweet->created_at);
$tweetDateTime = date('m-d-Y H:m:s', $timeStamp);
if($i > 0){
$SQL .= ',';
}
$SQL .= "(". $tweet->id .",'" . $tweet->from_user ."','". addslashes($tweet->profile_image_url) . "','". addslashes($tweet->text). "','" . $tweetDateTime ."')";
$i++;
}
$SQL .= " ON DUPLICATE KEY UPDATE 1=1";
This leaves me with a SQL statement looking like this:
INSERT
INTO
tblTwitterSubmit (tweetId, twitterAuthor, authorAvatar, tweetText, tweetDateTime)
VALUES
(111,'name','http://url.com','a string of text','03-04-2011 13:03:09'),
(222,'anothername','http://url.com','another tweet','03-04-2011 12:03:51')
ON DUPLICATE KEY UPDATE 1=1;
I am unfortunately getting the following error: 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 '1=1' at line 1.
Edit:
The 1=1 is supposed to not do anything. The tweets don't change, and so if I pull the same one back twice for any reason, nothing will happen, but it also won't throw a duplicate key error.
Re-edit:
The problem appears to have something to do with the key field I was using, which was the id of tweet as assigned by twitter.
I re-factored the code anyway, since it seemed pretty evident that what I had read in articles as a "really-good-idea" wasn't. I now included a PDO submit inside the for loop so I just make a bunch of submissions instead of one long sql string.
Hopefully this is better practice.
Leaving this open for a couple minutes hoping for some feedback if this is the way to do it or not.
The ON DUPLICATE KEY UPDATE requires a column name, something like this, assuming tweetId is the key column that's getting duplicates.
ON DUPLICATE KEY UPDATE tweetId=tweetId+1
Your 1=1 doesn't actually do anything.
Are you sure you're using the right syntax for on duplicate key update ?
Judging from it's manual's page, it seems you have to specify a column name, and not 1=1.
From what I understand, if you want to indicate "use the value from the values() clause when there's a duplicate", you should use something like this :
on duplicate key update your_col=values(your_col)
Quoting the relevant part :
You can use the VALUES(col_name)
function in the UPDATE clause to
refer to column values from the
INSERT portion of the INSERT ... ON
DUPLICATE KEY UPDATE statement.
In other words,
VALUES(col_name) in the ON
DUPLICATE KEY UPDATE clause refers to
the value of col_name that would be
inserted, had no duplicate-key
conflict occurred. This
function is especially useful in
multiple-row inserts.
Then, as a sidenote, you must escape your strings using the function that matches your API -- probably mysql_real_escape_string -- and not the generic addslashes, which doesn't know about the specificities of your database engine.
The problem appears to have something to do with the key field I was using, which was the id of tweet as assigned by twitter.
I re-factored the code anyway, since it seemed pretty evident that what I had read in articles as a "really-good-idea" wasn't. I now included a PDO submit inside the for loop so I just