$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.
Related
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`");
When I add AND operator in mysql_query() function, it stops working and anything after that stops working!
For Example:
When i wrote this:
$query1 = mysql_query("SELECT * FROM chat1 where friendname = '$_POST[fname]' ");
$row= mysql_fetch_array($query1) or die(mysql_error());
echo "$row[message]";
The above query runs successfully !
But when i do this :
$query1 = mysql_query("SELECT * FROM chat1 where friendname = '$_POST[fname]' AND username = '$_POST[uname]' ");
$row= mysql_fetch_array($query1) or die(mysql_error());
echo "$row[message]";
I get Null output!
I think the "AND" operator is not working!!!
please help me with this!!
Have a look at my complete code and Database Snapshot!
Click here
If it is returning NULL then probably the record doesn't exists. Try to output this query on the screen and post the raw query here.
Maybe your search needs a LIKE instead of a =
Likely, the row(s) you are looking for do not exist.
The AND is a boolean operator that requires that both expressions have to evaluate to true. In the context of your query, that means for a row to be returned, both of the conditions have to be true on that single row.
I suspect that you may want an OR those two conditions. Did you want to return only rows that meet both criteria, or did you want any rows that have fname with a certain value, along with any rows that have uname of a specific value? If the first query is returning rows, then replacing AND with OR should return you some rows.
For debugging this type of problem, generate the SQL text into a variable, and then echo or var_dump the SQL text, before you send it to the database.
e.g.
$sql = "SELECT * FROM chat1 where friendname = '"
. mysql_real_escape_string($_POST['fname'])
."' ";
echo "SQL=" . $sql ; # for debugging
Take the text of SQL statement that's emitted to another client, to test the SQL statement, to figure out if the SQL statement is actually returning the resultset you expect it to return.
(In your code, reference the $sql in the function that prepares/executes the SQL statement.)
Follow this pattern for all dynamically generated SQL text: generate the SQL text into a variable. For debugging, echo or var_dump or otherwise emit or log the contents of the variable. Take the SQL text to another client and test it.
Dumping code that isn't working on to StackOverflow is not the most efficient way to debug your program. Narrow down where the problem is.
How to debug small programs http://ericlippert.com/2014/03/05/how-to-debug-small-programs/
NOTES
You probably want to verify that $_POST['fname']) contains a value.
It's valid (SQL-wise) for a SELECT statement to return zero rows, if there are no rows that satisfy the predicates.
Potentially unsafe values must be properly escaped if you include them in the text of a SQL statement. (A better pattern is to use prepared statements with bind placeholders, available in the (supported) mysqli and PDO interfaces.
Also, use single quotes around fname.... e.g.
$_POST['fname']
^ ^
I am currently working on a php project and used the word 'value' as a column name. The problem being that when I run the query, it overwrites all entries in the database, even though I have a delimiter (primary key = *). I have tried everything I can think of to get this to work, and it hasn't yet. here is the complete line of code:
$SqlStatement = "UPDATE rev_exp SET Date_Entered = '".date('Y-m-d')."', Description = '".$_POST['txtUtilityType']." ".$_POST['txtAccountNumber']." ".$_POST['txtDateAdded']."', `Value` = ".$_POST['txtValueBalance'].", Notes = '".$_POST['txtNotes']."' WHERE PK_Rev_Exp = ".$row['FK_Rev_Exp'];
Note here, that $row['FK_Rev_Exp'] is the delimiter I was talking about. It is being pulled accurately from a previous query. Also, please ignore any sql injection problems, I'm just working on getting the project functional, I can optimize later.
EDIT 1: I have also tried enclosing the "value" in everything I can think of that may get rid of this problem, but no luck.
EDIT 2: I also don't think it is a problem with the statement itself, as I directly entered the statement into the mysql command line and it only affected 1 row, possibly a php problem?
EDIT 3: Full block, including the execution of the sql. Here, ExecuteSQL runs all necessary mysqli statements to execute the sql command. it takes in a sql statement and a true/false if there is a result set:
$SqlStatement = "UPDATE rev_exp SET Date_Entered = '".date('Y-m-d')."', Description = '".$_POST['txtUtilityType']." ".$_POST['txtAccountNumber']." ".$_POST['txtDateAdded']."', `Value` = '".$_POST['txtValueBalance']."', Notes = '".$_POST['txtNotes']."' WHERE PK_Rev_Exp = ".$row['FK_Rev_Exp'];
ExecuteSQL($SqlStatement, false);
I can't figure it out, and any help would be appreciated.
I think your problem is not about mysql reserver keywords because your correctly surrounded Value with backtick and that makes database understand this is a field. I'm more concerned about treating not integers as integers so i would suggest to surround with quotes '' your value since it is a decimal
`Value` = '".$_POST['txtValueBalance']."',
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.
Effectively, what I am attempting to do is enter a string similar to this string
into MySQL (it's one line, made into two for readability)
fill:#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:1px;
stroke-linecap:butt;stroke- linejoin:miter;stroke-opacity:1
MySQL allows me to INSERT the string into the field using phpMyAdmin and phpMyAdmin adds the field as (again one line, made into two for readability):
('fill:#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-
linecap:butt;stroke-linejoin:miter;stroke-opacity:1'' in ''field list')
With my PHP code I attempted to add the in field list part to my code as follows
$rectangle_array[$rstyle] = $rectangle_array[$rstyle] . "' in ''field list'";
$mysql_rectangle_table_entry = "INSERT INTO $mysql_table VALUES
($rectangle_array[$rstyle], 'rect',
$rectangle_array[$rid], $rectangle_array[$rwidth],
$rectangle_array[$rheight], $rectangle_array[$rx],
$rectangle_array[$ry])";
$run = mysql_query($mysql_rectangle_table_entry) or die(mysql_error());
And upon running the code I receive the following 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 ':#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;s' at line 1
What can I do to make this work?
As noted in the comments…
You could use mysql_real_escape_string() to escape any MySQL special characters before insertion.
For example:
$sql = "INSERT INTO my_table (string_column) VALUES ('" . mysql_real_escape_string($string) . "')";
Another option is to use Prepared Statements with PHP's MySQLi or PDO.
You might want to have a look either at prepared statements or mysql_real_escape_string to escape special characters that might break your INSERT.