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';
Related
Answer found (syntax): The column name of my string had to be encased in backticks " ` " as they contained spaces. Note that this means that the majority of this post has no relevance to the issue. The code has been corrected in case someone wants to do something similar.
So, I am doing a foreach loop to assign a value (1/0) to non-static columns in my database (it needs to support addition/deletion/editing of columns). I am using $connectionvar->query($queryvar); to do my queries which worked fine up until now when I'm trying to use a custom built string as $queryvar in order to change the column name to a variable within the loop. I've been outputting this string through echo and it looks exactly like my functional queries but somehow doesn't run. I've attempted to use eval() to solve this but to no avail (I feel safe using eval() as the user input is radio buttons).
Here's the loop as well as my thought processes behind the code. If something seems incoherent or just plain stupid, refer to my username.
foreach($rdb as $x) { //$rdb is a variable retrieved from $_POST earlier in the code.
$pieces = explode("qqqppp", $x); //Splits the string in two (column name and value) (this is a workaround to radio buttons only sending 1 value)
$qualname = $pieces[0]; //Column name from exploded string
$qualbool = $pieces[1]; //desired row value from exploded string
$sql = 'UPDATE users SET '; //building the query string
$sql .= '`$qualname`';
$sql .= '=\'$qualbool\' WHERE username=\'$profilename\''; //$profilename is retrieved earlier to keep track of the profile I am editing.
eval("\$sql = \"$sql\";"); //This fills out the variables in the above string.
$conn->query($sql); //Runs the query (works)
echo ' '.$sql.' <br>'; //echoes the query strings on my page, they have the exact same output format as my regular queries have.
}
}}
Here's an example of what the echo of the string looks like:
UPDATE users SET Example Qualification 3='1' WHERE username='Admin2'
For comparison, echoing a similar (working) query variable outside of this loop (for static columns) looks like this:
UPDATE users SET profiletext='qqq' WHERE username='Admin2'
As you can see the string format is definitely as planned, yet somehow doesn't execute. What am I doing wrong?
PS. Yes I did research this to death before posting it, as I have hundreds of other issues since I started web developing a month ago. Somehow this one has left me stumped though, perhaps due to it being a god awful hack that nobody would even consider in the first place.
You need to use backticks when referring to column names which have spaces in them. So your first query from the loop is outputting as this:
UPDATE users SET Example Qualification 3='1' WHERE username='Admin2'
But it should be this:
UPDATE users SET `Example Qualification 3`='1' WHERE username='Admin2'
Change your PHP code to this:
$sql = 'UPDATE users SET `'; // I added an opening backtick around the column name
$sql .= '$qualname`'; // I added a closing backtick around the column name
$sql .= '=\'$qualbool\' WHERE username=\'$profilename\'';
Example Qualification 3 : Is that the name of your Mysql Column name ?
You shouldnt use spaces nor upper / lower case in your columnname.
Prefere : example_qualification_3
EDIT :
To get column name and Comment
SHOW FULL COLUMNS FROM users
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.
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.
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 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.