I have a number box <input type='number' step='any' name='number' id='number'>
and I take that value and call it in a function like so:
insertIntoDB($number)
function insertIntoDB($number = null){
//insert into db
"INSERT INTO 'tablename' (number) VALUES " . $number;
}
and I get this error:
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 ' '
Is there away so if the user leaves the field blank it will enter the value as null?
You can set default values when creating the table itself, but apart from that, the code you pasted is missing some brackets:
INSERT INTO `tablename` (number) VALUES (" . $number.")";
If you want to use a NULL when inserting and get a default value in the table, you can do it when creating the table like this:
CREATE TABLE test
(
id INT NOT NULL AUTO_INCREMENT,
someField VARCHAR(15) NOT NULL DEFAULT 'on'
)
Now when you try to insert data into it, you can do the following:
insert into `tablename` (id, someField) values (null, null)
and get a row with an incremented ID and the string 'on' in the column someField.
If you want to check for nulls when inserting data into a table, you can then use something like the following to ensure you have the value:
$someField=(isset($number))?$number:'null';
INSERT INTO `tablename` (number) VALUES (" . $someField.")";
This is assuming you have already verified that $number is either numeric or isn't submitted when sending the form.
Related
I am new to SQL Server. I have created a script where I import data and insert into SQL Server. The update query works fine but the insert query does not . I get a error
Error converting data type varchar to float.. INSERT INTO dbo.
This is the code
$amount = trim(str_replace('$','',$data[2]));
// echo ($amount); // prints 1,000,000.00
// INSERT QUERY
//Try 1 : Fails
$Query = "INSERT INTO dbo.testtable (id, name, amount)
values ( 11, 'John' , $amount )";
//Try 2 : Fails
$Query = "INSERT INTO dbo.testtable (id, name, amount)
values ( 11, 'John' , CONVERT(FLOAT,'$amount') )";
How in the world can I insert a proper float value from the variable ($amount) into SQL Server?
use this:
cast('$amount' as money)
Updates:
It actually depends on what's the type of your column amount. If it's varchar, it should not throw an error for 1st line. So, I guess it's something like decimal(18, 2). Refer to the demo here
declare #amount varchar(25)
SET #amount = '1,000.00'
create table #tmp_money (amount FLOAT)
insert into #tmp_money
SELECT cast(#amount as money)
select * from #tmp_money
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.
I am trying to insert data into Mysql table, but it is giving me an error as-
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 'Scoretab VALUES ('UX 345','22','0.8562675')' at line 1
This is the php-mysql snippet that im using :
if($value >= 0.70){
$mu_id = $ros['c_id'];
$moc_id = $ram['t_id'];
$query="INSERT INTO Scoretab VALUES ('$mu_id','$moc_id','$value')";
$op1 = mysql_query($query) or die(mysql_error());
}
This is my table structure:
CREATE TABLE IF NOT EXISTS `Scoretab` (
`mu_id` varchar(10) NOT NULL,
`moc_id` int(5) NOT NULL,
`score` decimal(5,4) NOT NULL,
UNIQUE KEY `mu_id` (`mu_id`)
)
There could potentially be a few problems with this query
$query="INSERT INTO Scoretab VALUES ('$mu_id','$moc_id','$value')";
Does the number of columns match the fields your trying to insert? Have you tried using using specific column identifier Scoretab (col,col,col) values (val, val, val)
Does any of your values contain an unescaped apostrophe? You might want to consider using mysql_real_escape_string for $mu_id and intval for $moc_id maybe!
$value is a float you don't need to ad apostrophes while inserting
Are you sure you are connected to the same database you have this table in?
this could be a possible working solution (edit)
if ($value >= 0.70)
{
$mu_id = mysql_real_escape_string($ros['c_id']);
$moc_id = intval($ram['t_id']);
$query = "INSERT INTO `Scoretab` VALUES ('$mu_id', $moc_id, $value)";
$op1 = mysql_query($query) or die(mysql_error());
}
try this
$query="INSERT INTO Scoretab (mu_id,moc_id,score) VALUES ('$mu_id','$moc_id','$value')";
The error seems to be before the table name Scoretab. Did you check your syntax carefully?
Sometimes we don't see what's right in front of our eyes! :D
Just replicated the example and everything worked for me.
I am having an issue with sql right now; I have gave a value a default so if the field is left empty when the user submit, but it is not working. When the user submits an empty field to leave a comment instead of it default to anon it does nothing. Also, in the datebase the field is empty.
name VARCHAR (50) default 'anon',
$name= $_POST['name'];
$title= sha1($_POST['title']);
$texts= $_POST['texts'];
$forum_id = $_POST['forum_id'];
$name = str_replace("'","''",$name);
$title = str_replace("'","''",$title);
$title = str_replace("b074acd521","STREAMER",$title);
$texts = str_replace("'","''",$texts);
$title = substr($title,0,8);
$sql = "INSERT INTO post (name,title, texts, forum_id) VALUES ('$name', '$title', '$texts', '$forum_id')";
mysqli_query($conn1, $sql) or die('Error inserting to database.');
mysqli_close($conn1);
header('Location: requests.php');
Is there another way to do it or am I just doing something wrong?
The SQL query your using will not insert the default value from your database because you are specifying a value for name (even if that value is an empty string, or null) :
$sql = "INSERT INTO post (name,title, texts, forum_id) VALUES ('$name', '$title', '$texts', '$forum_id')";
Instead if you want the default value to be inserted into the name field you must not specify the name column in the insert statement :
$sql = "INSERT INTO post (title, texts, forum_id) VALUES ('$title', '$texts', '$forum_id')";
In SQL query you can specify for which fields, values will be provided in the query and remaining fields from the table would contain default value (in case of AUTO_INCREMENT, the next integer value will be used).
Where you given the default value directly applied in SQL? the value left in DB ultimately is what exactly you passed to DB server by SQL way, or just you defined a variable where if it don't accept a value from user then use the default value instead, please try to debug this to insure the value was handled correctly.
while insert the values you shouldn't give the column which you set default value
below Example explain it...Try like this...
create table er(id int,name char(10),gender char(2)default 'M')
Here i took gender as default
now i insert the values
insert into er (id,name)values(1,'poda')
select * from er
I want to insert a new row in my table. I want the id to be generated right automatically and not asked from the user. The user only provides title and text. I wrote this code in PHP:
<?php
$hostname = "localhost";
$database = "mydb";
$username = "myuser";
$password = "mypsw";
$link = mysql_connect( $hostname , $username , $password ) or
die("Attention! Problem with the connection : " . mysql_error());
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_query("SET NAMES ‘utf8’",$link);
mysql_select_db("mydb", $link);
$lastid=mysql_insert_id();
$lastid=$lastid+1;
$sql="INSERT INTO announcements VALUES ('$lastid',CURDATE(),'$_POST[title]','$_POST[text]')";
if (!mysql_query($sql,$link))
{
die('Error: ' . mysql_error());
}
mysql_close($link);
header("Location: announcement.php");
?>
Sadly when I test it on my website, I get this error:
Error: Duplicate entry '0' for key 'PRIMARY'
Is mysql_insert_id() not working? What is wrong?
Don't do this. mysql will happily create an auto_increment column for you:
CREATE TABLE x (
id int not null primary key auto_increment
^^^^^^^^^^^^^^---add this to your PK field
);
INSERT INTO x (id) VALUES (null); // creates id = 1
INSERT INTO x (id) VALUES (null); // creates id = 2
mysql_insert_id() only returns the last id created by the CURRENT connection. You haven't inserted any data yet when you first run it, so you get back nothing.
Your version is incredibly vulnerable to race conditions. There is NO guarantee that the last ID you retrieve with mysql_insert_id() will not ALSO get retrieved by another copy of the script running in parallel, and get sniped out from under this copy of the script.
The primary key column on announcements should be auto_increment. When you do mysql_insert_id() it retrieves the id from the last query executed from that connection.
Because the INSERT is the query you are currently performing, it errors.
Try
INSERT INTO announcements
(date_field, title, text)
VALUES (CURDATE(),'$_POST[title]','$_POST[text]')
Just replace 'date_field', 'title', and 'text' with the applicable column names.
Alternatively the following should also work, as a NULL value in the AutoIncrement value should be acceptable
INSERT INTO announcements VALUES (NULL,CURDATE(),'$_POST[title]','$_POST[text]')
As mentioned in the other suggestion posted, you should make sure that the primary key field of the announcements table is set to be auto_increment.
Just for completion, you would use mysql_insert_id() when you want to use the id for the row you just inserted, i.e. if you then want to select the row you just inserted you could do
'SELECT * FROM announcements WHERE id = '.mysql_insert_id()
The problem is that you are asking for last insert id and you didn't inserted anything.
Convert your ID field in db to be autoincrement if its not.
Insert into database your announcment
Then ask for id using mysql_insert_id to get it.
But I see that you are not using it only when inserting then you don't need that functionality anyhow. Just insert without ID like this
"insert into announcements (InsertDate, Title, Text) VALUES (CURDATE(), '$_POST[title]', '$_POST[text]')";
and you should really be careful with your queries when using values from $_POST or $_GET or any other user typed value. There is possibility to execute SQLInjection through your form fields, so I suggest you to use mysql escape command or use parameters.
I hope this helps.
Assuming your table is set up properly, with the id field as AUTO_INCREMENT, you just need to perform an INSERT where you do not specify a value for id. That means you must specify the names of the columns you are inserting. So this line:
$sql="INSERT INTO announcements VALUES ('$lastid',CURDATE(),'$_POST[title]','$_POST[text]')";
becomes this
$sql="INSERT INTO announcements (`date`,`title`,`text`) VALUES (CURDATE(),'$_POST[title]','$_POST[text]')";
I guessed what your column names might be. Obviously they need to match your table definition.
If you do this, then the mysql_insert_id() function will return the id of the row you just inserted. (That is, it gives you the value of the previous insert, not the next one.)
You probably want to add "auto increment" to the table when creating it.
This will add an id automatically when inserting something.
e.g.
CREATE TABLE announcements
(
id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
some_date int(11),
title varchar(200),
text varchar(3000)
);
mysql_insert_id "Retrieves the ID generated for an AUTO_INCREMENT column by the previous query " - http://php.net/manual/en/function.mysql-insert-id.php