php INSERT into column with variable name MySQL - php

Been looking around all over forums and found similarish issues like MySQL INSERT INTO with PHP $variable . But it's not quite getting to my question.
I want to use variables for the columns but I get errors with my MySQL insert statement
$columns = 'id, test';
$sql_store = "INSERT into test ('$columns') VALUES (NULL, 1)";
$sql = mysqli_query($db, $sql_store) or die(mysql_error());
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''id, Storlek') VALUES (NULL, 1)' at line 1
Thankful for help!

Problem : Your $columns variable is string which is not true.
Try like this,
PHP
$columns_array = array('id','test');
$columns = implode(",",$columns_array);
$sql_store = "INSERT into test (".$columns.") VALUES (NULL, 1)";
$sql = mysqli_query($db, $sql_store) or die(mysql_error());

It looks like your SQL command, after variable substitution, looks like
INSERT into test ('id, Storlek') VALUES (NULL, 1) /* wrong! */
It needs to say this ...
INSERT into test (id, Storlek) VALUES (NULL, 1)
or maybe this...
INSERT into test (`id`, `Storlek`) VALUES (NULL, 1)
So get rid of the quote marks surrounding your $columns variable.

Related

same sql query works using phpmyadmin but does not work using php

I entered the following sql query in phpmyadmin, it successfully inserted a new record.
INSERT INTO `table` (id, timestamp) VALUES (1, '2013-09-18 13:00')
However, when I try to use it using php.
//...connection
$query = "INSERT INTO `table` (id, timestamp) VALUES (1, '2013-09-18 13:00')";
$result = mysql_query($query, $cms2013) or die("error:".mysql_error());
It throws error like this:
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 '13:00)' at line...
Can someone provide me some hints? Thank you.
your query is working fine i have checked it from my end.
Please execute the following.
$sql = "INSERT INTO tables (id, timestamp) VALUES (1, '2013-09-18 13:00')";
mysql_query($sql) or die("! sql");
Have you selected the database before mysql_query()?
Try query using:
$query = "INSERT INTO `db_name`.`table` (id, timestamp) VALUES (1, '2013-09-18 13:00')";
$result = mysql_query($query, $cms2013) or die("error:".mysql_error());

Wrong SQL Syntax? [duplicate]

This question already has answers here:
MySQL, safely using reserved word in query [duplicate]
(2 answers)
Closed 9 years ago.
I am building a small Twitter clone for personal use, and I have so trouble with it.
Fist, I want to show you my SQL structure of the table "poke_history":
http://puu.sh/3Sci0.png
This is the command I use to insert the values into a table (in PHP):
$insert = "INSERT INTO poke_history (id, from, time, reason) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
This is the annoying error that I am getting:
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 'from, time, reason) VALUES ( '1'' at line 3.
Let me clarify some things.
$to_id is a number.
$from_id is a number.
$time is a number (coming from PHP's time()).
$reason is a text string.
I am using MySQL and PHP5.
Try to quote your column identifiers like
INSERT INTO poke_history (`id`, `from`, `time`, `reason`) ...
Everything inside `` is considered to be a "identifier" not a language keyword. From the SQL-syntax it should be clear that after INSERT INTO tablename cannot come a FROM, but the MySQL sometimes needs this kind of guidance (and other sql parsers, too).
credit to mario as well:
from is a reserved keyword. Use backticks to escape them.
for example
`from`
INSERT INTO table (`from`) ....
So your code would like this:
$insert = "INSERT INTO poke_history (`id`, `from`, `time`, `reason`) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
$insert = "INSERT INTO poke_history (`id`, `from`, `time`, `reason`) VALUES (".$to_id.", ".$from_id.", ".$time.", '".$reason."')";
mysql_query($insert) or die(mysql_error());
Numbers don't need to be quoted. Only strings.
Also don't use mysql, it's deprecated. Better use PDO, with prepared statements, to avoid issues like this.
You should try to use prepared statements to prevent SQL injection.
$query = "
INSERT INTO
poke_history (`id`, `from`, `time`, `reason`)
VALUES
(:id, :from, :time, :reason)";
$db = new PDO("mssql:host=sqlserver;dbname=database", "username", "password");
$statement = $db->prepare($query);
$parameters = array(
":id" => $name,
":from" => $from,
":time" => $time,
":reason" => $reason
);
$statement->execute($parameters);
I think that you forgot to add * in between INSERT and INTO, here is the fixed script:
$insert = "INSERT * INTO poke_history (id, from, time, reason) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
The reason why you are getting the error is because you are trying to use a built in function name for one of your columns. Say you have the following CREATE TABLE...
CREATE TABLE customers
(
name varchar(80),
streetAddr varchar(160),
"from" varchar(60),
);
Notice that to create the table I had to put the column from in quotes. Now if you wanted to insert a row into this table, your insert statement should look like the following:
INSERT INTO ShoppingFun.dbo.customers
(
name,
streetAddr,
"from"
)
VALUES
(
'MRBubbleGum',
'1061 SW BubbleGumVillage St',
'yourmom'
)

PHP : how to insert (into an Sql table) a variable and concatenate it with the date function

i've been trying to insert a row into an Sql database table , and that row's last column is supposed to contain a variable and i can't figure out how to concatenate that variable with a date function. The problem becomes the single quote marks
$SQL = "INSERT INTO news VALUES (NULL, '$user', '$text'.'date('Y-m-d H:i:s')')";
That $text is supposed to have a "date now" function called right after it so that i would have the date that it was inserted into the table...
Thanks
Try this:
$sql = "INSERT INTO news VALUES (NULL, '$user', '$text<br>".date('Y-m-d H:i:s')."')";
You can try this
$SQL = "INSERT INTO news VALUES (NULL, '$user', '".$text." now()')";

PHP Insert not Working Properly

I have the following lines of PHP code in my file along with some other code:
$command = "INSERT INTO inventory_items (Index, Name, Price) VALUES (NULL, 'Diamond', '3.99')";
$insertion = mysql_query($command) or die(mysql_error());
if ($insertion == FALSE)
{
echo "Error: Insert failed.";
}
else
{
echo "Insert successful.";
}
It keeps returning this 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 'Index, Name, Price) VALUES (NULL, 'Diamond', '3.99')' at line 1
myAdmin says I am using MySQL client version 5.0.91. What am I doing wrong? I just can't figure it out! I tried searching a lot...
Index is a reserved word in MySQL and as such, you need to either change the name of the column, or escape it with backticks. Try this $command:
$command = "INSERT INTO inventory_items (`Index`, Name, Price) VALUES (NULL, 'Diamond', '3.99')";
Read more about reserved words here: http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html
Try this:
$command = "INSERT INTO inventory_items (`Index`, Name, Price) VALUES (NULL, 'Diamond', '3.99');";
MySQL reserved words and how to treat them.
Can you verify that the columns in your inventory_items table are:
Index
Name
Price
And that you have the Index field set to AUTO_INCREMENT.
The best thing is probably to remove that field from your insert statement.
Try
$command = "INSERT INTO inventory_items (Name, Price) VALUES ('Diamond', '3.99')";
Since you're not inserting an Index anyway.
Hope that helps!

MySQL Insert syntax error - Cant find it!

There's gotta be something small I keep missing here, but I can't find it for the life of me.
$insert = mysql_query("INSERT INTO USERS
(`FBID`, `FIRST_NAME`, `LAST_NAME`, `GENDER`)
VALUES ('$fbid', '$firstName', '$lastName', '$gender')");
The error is:
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' at line 1
Any ideas?
You are not having variables correctly escaped. Use mysql_real_escape_string and code like this:
$insert = mysql_query("INSERT INTO USERS (`FBID`, `FIRST_NAME`, `LAST_NAME`, `GENDER`)
VALUES (
'".mysql_real_escape_string($fbid)."',
'".mysql_real_escape_string($firstName)."',
'".mysql_real_escape_string($lastName)."',
'".mysql_real_escape_string($gender)."'
)");
If the variables contain any quotes, they create the problem if you don't properly escape them.
Do any of your names contain single quotes?
Try writing out the value of the query to log/console/debug to ensure that it's what you expect.
Try wrapping your variables in {}.
'{$fbid}', '{$firstName}', '{$lastName}', '{$gender}'
Otherwise you are going to have to use string concatenation.
'".$fbid."','".$firstName."','"...
I'm assuming your variables already contain proper escaped data.
Try doing it like this:
$sql = <<EOL
INSERT INTO USERS (`FBID`, `FIRST_NAME`, `LAST_NAME`, `GENDER`)
VALUES ('$fbid', '$firstName', '$lastName', '$gender')
EOL;
$stmt = mysql_query($sql) or die("MySQL error: " . mysql_error());
This will preserve the query for you in $sql so you can echo it out elsewhere and see what was actually produced.

Categories