I have a table user (id VARCHAR(5), name VARCHAR(30))
I used INSERT INTO query in two way:
1) Directly:
...
$sql="INSERT INTO user (id,name) VALUES ('00001','abcd');
...
---> result: id(00001), name(abcd).
That's the right result.
2) By function:
function insert($id,$name)
{
$sql="INSERT INTO user (id,name) VALUES ($id,$name)";
....
}
I used this function with 2 kind of parameter
a)
insert('00001','00123');
---> result: id(1), name(123) (all zeros have been cut).
b)
insert('00001','abcd');
---> error: Unknown column 'abcd' in 'field list'.
I want to ask: why all the zeros have been cut, and why when I used a string value it make an error. How can I fix it to get right result by function.
Many thanks!
You never bothered quoting your values:
INSERT INTO user (id,name) VALUES ($id,$name)
^^^^^^^^^---here
So the query becomes
INSERT INTO user (id, name) VALUES (1, abcd)
Without the quotes, abcd is seen as a FIELD NAME, not a value. Since your table has no field named abcd, you get your error. Try:
INSERT INTO user (id,name) VALUES ($id, '$name')
as a short-term fix (note the ' quotes around $name). Long term fix: Start using prepared statements and/or placeholders, which eliminate the need for this kind of quoting.
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
hi can you help me to make my query update if table if id exist then if not insert it?
here's my query:
if(isset($_POST['submit'])){
$a=$_POST['no1']; $b=$_POST['ans1']; $c=$_POST['det1'];
$d=$_POST['no2']; $e=$_POST['ans2']; $f=$_POST['det2'];
$g=$_POST['no3']; $h=$_POST['ans3']; $i=$_POST['det3'];
$j=$_POST['no4']; $k=$_POST['ans4']; $l=$_POST['det4'];
$m=$_POST['no5']; $n=$_POST['ans5']; $o=$_POST['det5'];
$p=$_POST['no6']; $q=$_POST['ans6']; $r=$_POST['det6'];
$s=$_POST['no7']; $t=$_POST['ans7']; $u=$_POST['det7'];
$v=$_POST['no8']; $w=$_POST['ans8']; $x=$_POST['det8'];
$y=$_POST['no9']; z=$_POST['ans9']; $zz=$_POST['det9'];
$aa=$_POST['no10']; $bb=$_POST['ans10']; $cc=$_POST['det10'];
$sql=mysql_query("insert into bfp_personnel_questions `(`id`,`question_number`,`answer`,`details`) VALUES ('$id', '$a', '$b','$c'), ('$id','$d','$e','$f'), ('$id','$g','$h','$i'), ('$id','$j','$k','$l'), ('$id','$m','$n','$o'), ('$id','$p','$q','$r'), ('$id','$s','$t','$u'), ('$id','$v','$w','$x'), ('$id','$y','$z','$zz'), ('$id','$aa','$bb','$cc')") or die(mysql_error());`
?><script>alert("Successfully Saved.");window.location="pds_1st.php?part=11";</script><?php }
}
Try SQL syntax insert on duplicate key update.
First off, your script screams for prepared statements. You could drastically improve the speed and performance by switching (especially since you're using the obsolete mysql extensions).
I assume that id is a PRIMARY KEY or at least a UNIQUE index. The simplest way to do this is to do INSERT IGNORE, which will try to insert your record and, if they collide, ignores the error and moves on
INSERT INGORE INTO table(col1, col2)
VALUES('1', '2');
If you want to replace the values, you can use REPLACE in later versions of MySQL
REPLACE INTO table(col1, col2)
VALUES('1', '2');
If the key already exists, the row is updated.
I have dumped the contents of a database in an sql file in a form like
insert into `a` values
(17,11,5),
(18,12,7),
(19,12,10),
(21,14,45),
(22,15,46),
(24,16,46),
(25,16,49),
(26,17,21),
(27,17,30),
(28,17,45),
(29,17,54),
(30,18,32),
(31,18,35),
(32,19,23),
(33,19,27),
(34,19,54),
(35,20,53),
(36,21,32),
(37,21,35),
(38,21,45),
(39,22,23),
(40,22,30),
(41,22,45),
(57,24,19),
(58,25,46),
(59,26,39),
(60,27,49),
(61,27,56),
(62,28,34);
insert into `b` values (14,'2009-01-06',''),
(15,'2009-02-01',''),
(16,'2009-03-01',''),
(17,'2009-03-25',''),
(18,'2009-04-05',''),
(19,'2009-04-17',''),
(20,'2009-04-18',''),
(21,'2009-04-19',''),
(22,'2009-04-23',''),
(24,'2009-07-05',''),
(25,'2009-08-02',''),
(26,'2009-08-07',''),
(27,'2009-09-06',''),
(28,'2009-09-14','');
etc..
I have 4 such tables with no foreigh key constrains. Then I try to upload the data into the db (mysql). I read the file's contents, I pass each table's insertion into an array and then i do mysql_query for each element :
$sqlArray = explode(';',$sqlFile);
for($i=0;$i<sizeof($sqlArray);$i++){
mysql_query($sqlArray[$i]) or die ('Error: '.mysql_error());;
}
The result is that the last three tables are inserted but the first one is not, and the error is :
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 ' insert into `a` values (17,11,5), (18,12,7), (19,12,10), (21,14,4' at line 1
I validated that the $sqlArray has the correct contains and the queries are correct and runnable from phpmyadmin.
The problem seems to be regardless of the first table (i.e. it will show up even if b was first) and it always seems to "cut" the query in the middle (or after almost 70 characters).
Any help will be appreciated!
Your second statement has a typo ("int" should be "into"):
insert int `b` values (14,'2009-01-06',''),
Alternately, if that's not the issue, try using separate insert statements to get a clearer error message:
insert into `a` values (17,11,5);
insert into `a` values (118,12,7);
...
I have experienced on some older versions of MySQL that they don't like the extended inserts. You can also try specifying the column names explicitly with the real names of your columns. This would be useful if you have more than 3 columns in those tables (an auto-increment column for example).
insert into `a` (`[column1name]`, `[column2name]`, `[column3name]`) values (17,11,5);
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 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.