MYSQL, PHP: Insert records from one database to another - php

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`");

Related

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')"))

PHP single query inside a while loop not running on MySQL

$sql="SELECT retail_peak, number from callplandata ";
$rs=mysql_query($sql,$conn);
$sql2='';
while($result=mysql_fetch_array($rs)) {
$sql2.="UPDATE callplandata set ".$_POST["callplancopy_newname"]." = '".$result[$_POST["callplancopy"]]."' where number = '".$result["number"]."'; ";
}
$rs2=mysql_query($sql2,$conn) or die(mysql_error());
I am trying to run the above queries, i have set $sql2 with a ; on the end so i just run one query rather than many separate queries.
I am getting this Error message:
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 'UPDATE callplandata set dcabr = '0' where number = '44*116'; UPDATE callplandata' at line 1
when i echo $sql2, it looks like - http://www.wepaste.com/sql2/
mysql is deprecated but it also doesn't allow multiple statements in a single query.
You can however use multiple statements in a single query with mysqli by using mysqli_multi_query
Your immediate problem is that you are concatenating the $sql2 queries in the while loop to make one long string and then trying to execute the long string as one query.
You should move the execution of $sql2 into the while loop and drop the .= operator in favor of =:
$sql2=''; // Don't need this line
while($result=mysql_fetch_array($rs)) {
$sql2="
UPDATE callplandata
SET ".$_POST["callplancopy_newname"]."='".$result[$_POST["callplancopy"]]."'
WHERE number = '".$result["number"]."'
";
$rs2=mysql_query($sql2,$conn) or die(mysql_error());
}
You could also follow Rob's suggestion and execute the long string as a multiple query.
You would also do well to heed the warnings in the comments about SQL injection and deprecated functions.
You can actually run this as one statement by dropping the WHERE clause.. it is the same logic.
You are using an anti-pattern for what this code is trying to achieve: to update all rows in the callplancopy table (where the number column is not null) to set a column equal to a value.
(NOTE: the "WHERE number =" in the original UPDATE statement would effectively prevent rows with a NULL value in that column from being updated.)
The entire mess of code is performing RBAR (Row By Agonizing Row) what could be more simply and efficiently accomplished with just one single UPDATE statement issued to the database:
UPDATE callplandata d
SET d.`somecol` = 'someval'
WHERE d.number IS NOT NULL
(NOTE: The WHERE clause is included to reproduce the behavior of the original UPDATE statements, avoiding updating rows where the number column is NULL. If that's not desired, or is not necessary, then the WHERE clause can be omitted.)
(NOTE: This assumes that you are assigning a literal value to the column, as in the original UPDATE, where we see "callplancopy" enclosed in single quotes, making it a string literal. If you are meaning to copy the value from another column in the row, then we'd enclose the column identifier in backticks, not single quotes.)
SET d.`somecol` = d.`some_other_col`
If we insist on using the deprecated mysql interface, we really need use the mysql_real_escape_string function to make unsafe values "safe" for inclusion in the SQL text.
$sql = "UPDATE callplandata d
SET d.`" . mysql_real_escape_string($_POST["callplancopy_newname"]) . "`"
. " = d.`" . mysql_real_escape_string($_POST["callplancopy"] . "`
WHERE d.number IS NOT NULL";
# for debugging, echo out the SQL text
#echo $sql;
NOTE: The PHP mysql interface is deprecated. New development should make use of the PDO or mysqli interface.

update the session field in database

I have a database. I had created a a table containing only one row in DB if it wasn't constructed before.
Why it has only 1 row is that I just use it to keep some info.
There is a field of TYPE NVARCHAR(100) which I want to use it to store session id,
and here comes the headache for me:
It seems that I can't even properly INSERT(I use phpmyadmin to check and it's blank) and UPDATE(syntax error...) it with a session id obtained from session_id(), which is returned as a string.
Here is the portion of my code relating to my action:
//uamip,uamport is in URL;I use $_GET[]
$_SESSION[uamport] = $_GET['uamport'];
$_SESSION[uamip] = $_GET['uamip'];
**$_SESSION[sid] = session_id();**
//construct
$sql="CREATE TABLE trans_vector(
`index` INT NOT NULL AUTO_INCREMENT,
`sid` NVARCHAR(100),
`uamip` CHAR(15),
`uamport` INT,
PRIMARY KEY (`index`)
)" ;
mysql_query($sql);
//insert(first time, so not constructed)
$sql="INSERT INTO trans_vector (sid,uamip,uamport) VALUES(
'$_SESSION[sid]',
'$_SESSION[myuamip]',
'$_SESSION[myuamport]'
)";
mysql_query($sql);
//update(from 2nd time and later, table exists, so I want to update the sid part)
$sql="UPDATE trans_vector SET sid="**.**$_SESSION[sid];
mysql_query($sql)
Now, when I use phpmyadmin to check the sid field after INSERT or UPDATE, It is blank;
But if I do this:
$vector=mysql_fetch_array(mysql_query("SELECT TABLES LIKE 'trans_vector'"));
and echo $vector[sid] ,then it's printed on webpage.
Another question is:
With the UPDATE statement above, I always get such error:
"Unknown column xxxxxx....(some session id returned, it seems it always translate it first and put it in the SQL statement, ** treating it as a column NAME** that's not what I want!)"
I tried some TYPE in CREATE statement, and also lots of syntax of the UPDATE statement(everything!!!) but it always give this error.
I am dealing trouble with ' and string representation containing a variable where the latter's value is actually what I want... and maybe the problem arise from type in CREATE and string representation in UPDATE statement?
Should CAST() statement helpful for me?
Wish you can help me deal with this...and probably list some real reference of such issue in PHP?
Thanks so much!!
$insert = "INSERT INTO trans_vector (`sid`, `uamip`, `uamport`) VALUES(
'".$_SESSION["sid"]."',
'".$_SESSION["myuamip"]."',
'".$_SESSION["myuamport"]."'
)";
this should solve at least some warnings, if not errors.
and for update...
$update = "UPDATE trans_vector SET `sid`='".$_SESSION["sid"]."';";
Notes about your code:
Array values have to be put into the string with operator '.' and cannot be inserted directly. Array indexes must be strings (note the ") or integers.
Column names should have `` around them. To insert a string with SQL, you have to put string into ''s, so the parser knows what is string and what column name. Without ''s parser is assuming you are stating a column.
and for mysql_escape_string, I assumed you handle that before storing data to sessions. Without those, you might can get unwanted SQL injections. And in case you did not do that, you can either do that (before you create queries):
foreach($_SESSION as $key => $value)
$_SESSION[$key] = mysql_escape_string($value);
or manually escape strings when you create a query.
As for the update statement, it’s clear that there are apostrophes missing. You always need apostrophes, when you want to insert a string value into the database. Moreover, you should use mysql_real_escape_string.
However, I think standard mysql is deprecated and has been removed in newer versions of PHP in favor of MySQLi and PDO. Thus you should switch to MySQLi or PDO soon.
You should also use apostrophes when referencing values within $_SESSION. Otherwise PHP will try to find a constanst with the name sid and later fallback to the string 'sid'. You will get into trouble if there once really is a constant called sid defined.
Here, the corrected update statement in mysql library:
$sql = "UPDATE trans_vector SET sid='" . mysql_real_escape_string($_SESSION['sid']) . "'";
Even better:
$sql = "UPDATE `trans_vector` SET `sid`='" . mysql_real_escape_string($_SESSION['sid']) . "'";
Using backticks makes clear for MySQL that this is a column name. Sometimes you will have column names that are called like reserved keywords in SQL. Then you will need apostrophes. A common example is a column called order for the sequence of entries.

PHP array INSERT into MySQL failing [duplicate]

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]."')"
}

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