SQL, PHP update query error - php

I have some PHP code and I'm trying to insert or to update data in a MySQL table.
The insert query works, but the update query doesn't. The values are printed correctly at the end.
<?php
$nm=$_GET["nm"];
$reg=$_GET["regno"];
$con=mysql_connect("localhost","root","admin");
mysql_select_db("Q14",$con);
// $res=mysql_query("insert into stdtable values('$nm','$reg')",$con);
$res=mysql_query("UPDATE stdtable SET `NAME`='$nm',`REG NO`='$reg' WHERE
'REG NO'='$reg'",$con);
echo "SUCCESS";
echo $nm.$reg;
?>

Here:
'REG NO'='$reg'",$con);
you've used ', but has to be `

For REG NO (in where clause) you have to use backticks not single quotes. Or better rename the column, without blanks in the name:
$res=mysql_query("UPDATE stdtable SET `NAME`='$nm',`REG NO`='$reg' WHERE
`REG NO`='$reg'",$con);
Do not longer use deprecated mysql_* API. Use mysqli_* or PDOwith prepared statement.

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 database using a while loop

I need to insert data from a table named wishlist into another table (wishlisturi_salvate) and altough the insert looks ok, something doesn't work right and no inseration is being made.Thanks for the help, I really appreciate it.
<?php
session_start();
include ('conex.php');
$sel2="select id_wishlist from wishlisturi_salvate";
$que2=mysql_query($sel2);
while($rez2=mysql_fetch_array($que2))
{
$a=$rez2['id_wishlist'];
}
$id_wishlist=$a;
echo $id_wishlist;
$sel="SELECT * from wishlist";
$que=mysql_query($sel);
while ($rez=mysql_fetch_array($que))
{
$insert="INSERT INTO 'wishlisturi_salvate'('id_user', 'id_wishlist', 'id_produs', 'nume_produs', 'pret_produs', 'cantitate_produs', 'suma')
VALUES('".$_SESSION['id']."','".$id_wishlist."','".$rez['id_produs']."','".$rez['nume_produs']."','".$rez['pret_produs']."','".$rez['cantitate_produs']."','".$rez['suma']."')";
if(!mysql_query($insert)) echo "fml";
echo "<br>".$insert;
}
if(mysql_query($insert))
{
header("location:user.php");
}
else echo "Nu s-a facut inserarea";
?>
No insertion is being made most likely because of the errors inside the query:
Right of the bat, there is already an error:
INSERT INTO 'wishlisturi_salvate'('id_user', 'id_wishlist', 'id_produs', 'nume_produs', 'pret_produs', 'cantitate_produs', 'suma')
The proper quoting of table/column names must be backtickts, not single quotes
INSERT INTO `wishlisturi_salvate` (`id_user`, `id_wishlist`, `id_produs`, `nume_produs`, `pret_produs`, `cantitate_produs`, `suma`)
Or just omit them, its okay in this case.
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Sidenote:
If you haven't already, always turn on error reporting:
error_reporting(E_ALL);
ini_set('display_errors', '1');
First of all I'll rcomend you to use PDO or mysqli instead of mysql to avoid SQL injection.
Anyway, if you want to insert elements from one table to another one I recommend you to use an insert statment with a subselect. That way it'll be faster and you will waste less memory.
Not an answer, more of an observation ; It will be far more efficient to loop through your results to build up a single SQL insert multiple statement that you send to the db once.
$insert = "INSERT INTO 'wishlisturi_salvate'('id_user', 'id_wishlist', 'id_produs', 'nume_produs', 'pret_produs', 'cantitate_produs', 'suma') VALUES ";
foreach( of your results ){
$insert .= "(x,y,z,a,b,c,d),";
}
// now trim off last comma, then send to db.
// or create an array then join it to the $insert
Same info can be read here : http://www.electrictoolbox.com/mysql-insert-multiple-records/

PHP & MySql query with apostrophes

I have the following php version:
PHP Version 5.3.2-1ubuntu4.19
and this php string:
$l_sDesc = "It doesn' t contain any dangerous substances";
If i try to make a query with db_query (Drupal) i get an error due to the apostrophe;
db_query("UPDATE mytable SET description= '$l_sDesc' where id = $id");
I've tried to use mysql_real_escape_string() but i get an empty string:
$l_sDesc = mysql_real_escape_string($l_sDesc); //i have an empty string as result
What's the problem?
Drupal use another DB Wrapper. Normally you can create prepared statements.
https://api.drupal.org/api/drupal/includes!database!database.inc/group/database/7
Here is a correct example. If you use the correct prepared statements your input will be filtered.
Otherwise use stripslashes().
http://php.net/manual/de/function.stripslashes.php
Tom, you need to "prepare" the string for SQL before you actually run the statement.
Try the PHP function mysql_real_escape_string on your strings before you actually use them.
http://php.net/manual/en/function.mysql-real-escape-string.php
I suggest to use $l_sDesc = htmlspecialchars($l_sDesc);

PHP integer value in SQL query

Here $id is integer value and it's not deleting from MySQL:
$Query="DELETE FROM table WHERE id='.$id.' and cid='".$cid."'";
Your problem in short: you have mixed different quotation marks - " and '.
This problem would not arise if you would use prepared statements, as you would have had a single string literal:
$Query="DELETE FROM table WHERE id=? and cid=?";
This would also remove the possibility of SQL injections.
This would also speed-up you program if you need to execute the same prepared statement several times (the statement is already prepared and does not need to be parsed on the second+ invocation).
And finally, in case you are still using the officially deprecated PHP mysql extension you MUST switch to mysqli and use its full benefits like prepared statements. The mysql extension is no longer officially supported and may be removed in future (though I foresee that it will be moved to PEAR or so).
As a temporary solution, use mysql_real_escape_string to encode all variables which are derived from the user input. Please do NOT use mysql_escape_string as it is highly vulnerable to character encoding!
You forgot to close your "
The Solution:
$id = mysql_real_scape_string($id);
$cid = mysql_real_scape_string($cid);
$Query="DELETE FROM table WHERE id='".$id."' and cid='".$cid."'";
The Problem
So, if you were to echo out your statement as it was, the result would look like:
DELETE FROM table WHERE id='.1.' and cid='2'
See the problem with that?

Problems with mysql insert

My php script won't work if i try to insert into database something in Saxon genitive (for example value "mike's" won't be inserted).
PHP code is plain and simple:
"INSERT INTO cache (id,name,LinkID,number,TChecked) VALUES(".$idUser.",'".$LinkName."',".$LinkID.",".$number.",NOW());"
Everything works great until "$LinkaName" get some value with "special character". How to put values like "mike's", "won't" etc. into MySql database?
You need to escape these strings properly. In addition, the technique that you're using right now exposes you to an SQL injection attack.
The PHP docs for mysql_real_escape_string gives a good example of what you should do:
// Query
$query = sprintf("INSERT INTO cache (id,name,LinkID,number,TChecked) VALUES(%d,'%s',%d,%d,'%s');",
mysql_real_escape_string($idUser),
mysql_real_escape_string($LinkName),
mysql_real_escape_string($LinkID),
mysql_real_escape_string($number),
mysql_real_escape_string(NOW()));
You must escape them first, otherwise you generate an invalid query. The single quote matches the single quote at the start of the string.
$LinkName = mysql_real_escape_string($LinkName);
You can also use prepared statements to bind parameters to the query instead of concatenating and sending a string (use the PDO or mysqli libraries instead of the mysql lib).
You need to use mysql_real_escape_string() on those values.
Also make sure if you are not quoting those other variables, to cast them to integer (the only reason why you wouldn't quote them).
If you're using mysqli or PDO and not the standard extension, you can use a prepared statement instead of escaping.

Categories