PHP array INSERT into MySQL failing [duplicate] - php

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
Many posts similar to mine,none of them work.
Have an array $data['date'], $data['name'], $data['value'].
Trying to insert into MySQL table MyValues (Date, Name, Value)
Have tried 7-8 different methods, none working.
Would like something like
for ($a=0;$a<10;$a++) {
mysql_query("INSERT INTO MyValues('Date','Index_Name','Index')
VALUES ($data['date'][$a] ,$data['name'][$a], $data['value'][$a])"
}
Have also tried foreach, building a single string to give to MySQL, etc.
Get this error
Warning: mysql_error() expects parameter 1 to be resource, boolean given on line 45

columnName shouldn't be wrap with single quotes as they are identifiers not string literals.
INSERT INTO `Values` (Date,Index_Name,Index) VALUES (....)
one more thing, the only identifier here that needs to be wrap with backtick is the tableName VALUES because it is a Reserved Keyword.
MySQL Reserved Keywords List
When to use single quotes, double quotes, and backticks in MySQL
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?

Since Values is a reserved word, you can't use it as is for a table name. You must use backticks to enclose it. Similarly, it is not valid to use single quotes to name columns, you need backticks there too.
Try this:
$out = Array();
$esc = "mysql_real_escape_string";
foreach($data['date'] as $k=>$v) {
$out[] = "('".$esc($data['date'][$k])."', '".$esc($data['name'][$k])."', "
."'".$esc($data['value'][$k])."')";
}
mysql_query("INSERT INTO `Values` (`Date`, `Index_Name`, `Index`) values ".implode(",",$out));

try this, use $a++ not $ee++
for ($a=0;$a<10;$a++) {
mysql_query("INSERT INTO `Values` (`Date`,`Index_Name`,`Index`)
VALUES ('".$data['date'][$a]."' ,'".$data['name'][$a]."', '".$data['value'][$a]."' ")
}

First, I believe you want your query values quoted, so the result is 'value' and not just value. Example:
mysql_query("INSERT INTO Values(Date,Index_Name,Index) VALUES ('$data['date'][$a]' ,'$data['name'][$a]', '$data['value'][$a]');
If you are doing multiple queries, do something like:
$q = "INSERT INTO Values(Date,Index_Name,Index) VALUES ";
for {
// Add to the string here for each insert item
}
mysql_query($q);
Additionally, please start phasing out PHP's mysql_* library in favor of mysqli or PDO.

First of all, just use PDO/mysqli with prepared statements so you wont ever have any issues like this.
This will solve it though (column names with back-ticks instead of single quotes, and escaped data):
for ($a=0;$a<10;$a++) {
mysql_query("INSERT INTO `Values` (`Date`,`Index_Name`,`Index`)
VALUES ('".mysql_real_escape_string($data['date'][$a])."' ,
'".mysql_real_escape_string($data['name'][$a])."',
'".mysql_real_escape_string($data['value'])[$a]."'");
}
And try to avoid reserved names for your columns like indexand values.

This works:
for ($a=0;$a<10;$a++) {
mysql_query("INSERT INTO Values('Date','Index_Name','Index')
VALUES ('".$data['date'][$a]."','".$data['name'][$a]."','".$data['value'][$a]."')"
}

Related

MYSQL, PHP: Insert records from one database to another

I have a necessity to insert some record from one table1 in database1 to another table2 in database2.
So far I have this..
$records_r = mysqli_fetch_assoc(mysqli_query($conn_r, "SELECT * FROM `export` WHERE ID < 100"));
$columns_r = implode(",",array_keys($records_r));
$values_r = implode(",",array_values($records_r));
$import = mysqli_query($conn_i,"INSERT INTO NOTimport ($columns_r) values ($values_r)");
if (!$import) {
printf("Error: %s\n", mysqli_error($conn_i));
exit();}
It gives me the error:
Error: You have an error in your SQL syntax;
This is how the syntax looks:
INSERT INTO `NOTimport` ('xx,xx,xx,xx,xx,xx,xx,xx') values ('11,'11,E,2079,1931,xx,xx,x')
I am 99% sure that single quotes are causing the error, but why are there?
As per your original post https://stackoverflow.com/revisions/31116693/1 and completely overwriting your original post without marking it as an edit:
You're using the MySQL import reserved word
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
It needs to be wrapped in ticks
INSERT INTO `import` ($columns_r) values ($values_r)
or rename that table to something other than a reserved word.
Plus, $values_r may require to be quoted and depending on what's being passed through $columns_r, you may need to use ticks around that.
I.e.:
INSERT INTO `import` (`$columns_r`) values ('".$values_r."')
Even then, that is open to SQL injection.
So, as per your edit with these values values ('11,'11,E,2079,1931,xx,xx,x'), just quote the values since you have some strings in there. MySQL will differentiate between those values.
Escape your values:
$values_r = implode(",",array_values($records_r));
$values_r = mysqli_real_escape_string($conn_r, $values_r);
or $conn_i I'm getting confused as to which variable is which here. Be consistent if you're using the same db.
Edit:
As stated in comments by chris85, use prepared statements and be done with it.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
import is a reserved word in MYSQL. So, you need to use backticks (``) around it in your query.
So rewrite as follows:
$import = mysqli_query($conn_i,"INSERT INTO `import` ($columns_r) values ($values_r)");
Without Using PHP you can use MySql Query Which Will Perform Insert Operation As:-
$columns_r='`name`,`class`';
mysqli_query($conn_i,"INSERT INTO `import` ({$columns_r}) select {$columns_r} from `export`");

INSERT INTO sql query is using variable string rather than field name

Getting really confused surrounding this INSERT INTO. It should insert three fields into the table, userID, activateKey and isActivated.
The activateKey is a 25 letter randomly generated key such as 63n20kw24ba1mlox34e8n2awv
The userID comes from another table and is set by auto_increment.
The isActivated is always 0 at this stage.
It seems like quite a simple INSERT statement
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES (".$userID.",".$activateKey.",'0')"))
{
echo("Error description: " . mysqli_error($con));
}
However it doesn't work when I include the $activateKey field. What it does is try to search the string variable $activateKey as a column name. The error I get is:
Error description: Unknown column '63n20kw24ba1mlox34e8n2awv' in 'field list'
Of course there is no such column as 63n20kw24ba1mlox34e8n2awv, this is the data I'm trying to insert, hence why it's in the VALUES section. Any ideas why it's trying to search this as the column name?
Edit to clarify: the var is activateKey, the column name is activationKey
I would put the query in a different variable to avoid confusion, and PHP automatically substitutes variable names in strings in double quotes.
Try this:
<?php
$query = "INSERT INTO activations (userID,activationKey,isActivated) VALUES($userID,'$activateKey','0')
if (!mysqli_query($con,$query)
{
echo("Error description: " . mysqli_error($con));
}
You are not surrounding the values with quotes, that's why they get interpreted as variable names.
Use single quotes, like this:
"INSERT INTO activations (userID,activationKey,isActivated) VALUES
('".$userID."','".$activateKey."','0')"
However, be aware that stringing together query strings exposes you to SQL injection attacks, if that's a concern in your code you should use parameterized queries. In fact, using parameterized queries is always better.
Change your query to this:
"INSERT INTO activations
(userID,activationKey,isActivated)
VALUES ('$userID','$activateKey','0')"
You dont need to use the concatenation (.) operator as variables will be interpolated into the string.
The single quotes tell mysql to treat the variables as literals instead of column names.
As a side note you would be better to use parameterized queries. See How can I prevent SQL injection in PHP?
Solved!
It was a case of not properly wrapping the dynamic fields (the vars in the VALUES section) in ticks:
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES ('".$userID."','".$activateKey."','0')"))
Instead of
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES (".$userID.",".$activateKey.",'0')"))
Might be a difficult one to spot. The variables still need to be 'in ticks' or they won't register as strings.
As activationKey is a string column, you must use single quotes for $activationKey.
Try with:
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated)
VALUES (".$userID.",'".$activateKey."','0')"))

Inserting $variable or $_POST value into mysql table [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
My question concerns why one piece of code works and two that does not, and how i can get the code that does not work to work.
The code that works:
mysql_select_db("webuser1", $con);
mysql_query("INSERT INTO users (column 1, column2) VALUES ('value1', 'value2')");
mysql_close($con);
Code no1 that does not ($var1 contains 'value1' etc.):
mysql_select_db("webuser1", $con);
mysql_query("INSERT INTO users (column 1, column2) VALUES ($var1, $var2)");
mysql_close($con);
And code no2 that does not work ($_POST['value1'] contains 'value1' etc.):
mysql_select_db("webuser1", $con);
mysql_query("INSERT INTO users (column 1, column2) VALUES ($_POST['value1'], $_POST['value2'])");
mysql_close($con);
Am i not supposed to be able to insert $var or $_POST in mysql? I hope you do not find this Q stupid but i have been looking around for solutions but i have not understood them.
Thank you
In SQL, string values need to be quoted:
VALUES ('value1', 'value2')"
When you use variables:
VALUES ($var1, $var2)");
They are not quoted … unless the quotes are in the values themselves.
So if $var1 = 'value1'; $var2 = 'value2' then (after the variables are interpolated in your string) your SQL looks like this:
VALUES (value1, value2)"
You could resolve your immediate problem by adding quotes:
VALUES ('$var1', '$var2')");
but this doesn't fix your major security vulnerability and lets your data break the query in different ways.
You should avoid creating SQL statements by assembling strings from variables. This way leads to SQL Injection security holes. Use an interface that supports bound arguments. They will handle quoting and escaping for you.
mysql needs single quotes to enclose a string... so you would need something like this:
mysql_query("INSERT INTO users (column 1, column2) VALUES ('".$_POST['value1']."', '".$_POST['value2']."')");
for everything that is not a string you won't need the single quotes (')
as mentioned before you should not forget to escape strings that you want to put into the database.
for example use prepared statements. by binding the parameters it is ensured that your passed value is of the type you specified within the prepared statement.
Seems like you're not escaping and quoting your arguments to mysql properly.
To insert variables in MySQL you need to escape them at least: $var = mysql_real_escape_string($_POST['variable']) and then ".. VALUES ('".$var."')"
You should also probably consider using libraries for connecting to MySQL like DOCTRINE: http://www.doctrine-project.org/ that handles this for you.
Use this solution, its 100% works
mysql_query("INSERT INTO users (column 1, column2) VALUES ('{$_POST[value1]}', '{$_POST[value2]}')");
when you use {}, you dont need write value in ' '
mysql_select_db("webuser1", $con);
mysql_query("INSERT INTO users (column 1, column2) VALUES ('$var1', '$var2')");
mysql_close($con);
When not using Apostrophes around values, it is supposed to be non string value.
Your variables are not recognized as variables. They are a part of your string.
Try:
mysql_query("INSERT INTO users (column 1, column2) VALUES ('".$var1."', '".$var2."')");
Same for your second problem.
Because the POST variables have ' in them, you have to concatenate instead.
I.E.
mysql_query("INSERT INTO users (column 1, column2) VALUES (".$_POST['value1'].", ".$_POST['value2'].")");
Or
mysql_query("INSERT INTO users (column 1, column2) VALUES ({$_POST['value1']}, {$_POST['value2']})");
It's also a good idea to put quotes around the variables, in case its empty (or a string rather than an integer)
$var1=$_POST['variable_name1'];
$var2=$_POST['variable_name2'];
$q="INSERT INTO `users` (`column 1`, `column2`) VALUES ($var1, $var2)";
$result=mysql_query($q);

SQL and PHP problems

What is wrong with this query?
$query3 = "INSERT INTO Users
('Token','Long','Lat')
VALUES
('".$token."','".$lon1."','".$lat."')";
You have several issues with this.
Column names should be backtick escaped, not quoted (also LONG is a datatype in MySQL hence it's reserved and must be backtick-escaped).
You have SQL injection problems if those arguments aren't escaped.
You should provide us with the result of mysql_error() if it's not working.
Try running this code:
$token = mysql_real_escape_string($token);
$lon1 = mysql_real_escape_string($lon1);
$lat = mysql_real_escape_string($lat);
$query3 = "INSERT INTO `Users` (`Token`, `Long`, `Lat`)
VALUES ('{$token}', '{$lon1}', '{$lat}')";
$result3 = mysql_query($query3) or die("Query Error: " . mysql_error());
If that still doesn't work, give us the error message that's produced.
Long is the mysql reserved word and reserved words needs to be enclosed in backticks
$query3 = "INSERT INTO Users
(`Token`,`Long`,`Lat`)
VALUES
('".$token."','".$lon1."','".$lat."')";
You're using single quotes around your field names. This isn't valid in any SQL variant I know of. Either get rid of them or quote the field names in the correct way for your SQL flavor.
Your code likely has an SQL injection vulnerability, unless you left out the code that escapes $token etc
You shouldn't be putting values into the SQL string like that. This isn't the 1990s - we have parametrized queries now.
The mysql_ functions make it a bit difficult to do queries properly. Switch to either mysqli or PDO.

more PHP mySQL INSERT fun

mysql_query("INSERT INTO dictionary ('word', 'definition') VALUES ('".$word."','".$definition."');")
That just will not execute, when I echo it - I get this:
INSERT INTO dictionary ('word', 'definition') VALUES ('monkey','monkey');
So the values are being brought into it properly, if I out put mysql_error() I get:
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 ''word',
'definition' VALUES
('monkey','monkey')' at line 1
Any ideas? I'm stumped.
You need to use backticks for field names:
INSERT INTO dictionary (`word`, `definition`)
(or, of course, no quotes at all. But it is better to have them.)
Yeh remove the quotes from the column definitions. You only need them around the strings you are inserting.
When referencing column names for INSERT you should be using backticks (`) not single quotes. (Single quotes is telling MySQL those values are strings and not column references).
Either remove the single quotes or use the backticks and the problem should resolve itself.
Change your single quotes around word and dictionary to backticks:
INSERT INTO dictionary (`word`, `definition`) VALUES ('monkey','monkey');
Correct Method:
mysql_query("INSERT INTO `dictionary` (`word`, `definition`) VALUES ('".$word."','".$definition."');")
which will be ouput as this:
INSERT INTO `dictionary` (`word`, `definition`) VALUES ('monkey','monkey');
if this is not working:
mysql_query("INSERT INTO dictionary (word,definition) VALUES ('".$word."','".$definition."')");
then you have problem with field names... check your name in table... or maybe you missing something! what your table look like?
mysql_query("INSERT INTO dictionary (`word`, `definition`) VALUES ('".$word."','".$definition."');")
Note the apostrophes. The field names should either use no apostrophes, or use the ones shown here.

Categories