MySQLi UPDATE has an error with one column - php

The query I'm using (from php) is
"UPDATE articles SET
title='".$_POST['title']."',
contents='".$_POST['cont']."',
category='".$_POST['cat']."',
desc='".$_POST['desc']."'
WHERE stitle='".$_POST['stitle']."'";
and I get the 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 'desc='hello' WHERE stitle='banana'' at line 1.
If I remove desc='".$_POST['desc']."' the query works. The field 'desc' is varchar(150). I can insert text directly from phpMyAdmin, the field is definitely called 'desc', and $_POST['desc'] definitely captures a value (I tried using echo $_POST['desc']; and a value is passed). I tried changing the code to desc='test' and that doesn't work.
Any ideas?

I managed to resolve the issue. I created a new column in the table, copied the information from 'desc' into that column, deleted 'desc'. I ran the query with the new column name, and it works. I don't know what the issue was, but that fixed it.

The problem are your $_POST['desc'] contains an apostrophe. I recommend you to use on all parameters the function mysqli_real_escape_string (doc: http://be2.php.net/manual/en/mysqli.real-escape-string.php).
Also, try to escape all rows and tables with backticks, to avoid reserved words creating errors.
Your query example looks like this with them:
"UPDATE `articles` SET `title` = '".mysqli::real_escape_string($_POST['title'])."', `contents` = '".mysqli::real_escape_string($_POST['cont'])."', `category` = '".mysqli::real_escape_string($_POST['cat'])."', `desc` = '".mysqli::real_escape_string($_POST['desc'])."' WHERE `stitle` = '".mysqli::real_escape_string($_POST['stitle'])."'";
If you are programming with procedural style calls to mysqli functions, use:
"UPDATE `articles` SET `title` = '".mysqli_real_escape_string($link, $_POST['title'])."', `contents` = '".mysqli_real_escape_string($link, $_POST['cont'])."', `category` = '".mysqli_real_escape_string($link, $_POST['cat'])."', `desc` = '".mysqli_real_escape_string($link, $_POST['desc'])."' WHERE `stitle` = '".mysqli_real_escape_string($link, $_POST['stitle'])."'";
(Obviosuly, replace $link with the variable initialized when you do mysqli_connect())
Using these function, you can avoid these errors, and, also, a lot of SQL exploits. There's no required if the variable contains an integer, but, you always need to check the data passed to the SQL engine to avoid problems.
Is a good practice, to have some checks, for example, testing who integer vars contains integers, or doing escape with mysqli::real_escape_string. And, if something are incorrect on the input data, halt the process and don't request the SQL query.

Related

oci_bind_by_name not working when unescaped works

Working on an UPDATE query for an Oracle database. The field in question is of the type NCHAR(25), which accepts a 25 character UTF-8 byte string. My input values are in ASCII which should work no problem.
The following snippet uses the oci_bind_by_name function to escape the variable in the WHERE clause and insert into the placeholder variable :herp.
$sql = "UPDATE MYTABLE SET OPT = '1' WHERE FIELD = :herp";
$stmt = oci_parse($this->conn, $sql);
oci_bind_by_name($stmt, ":herp", $record['value'], -1, SQLT_CHR);
This next snippet does not use the oci_bind_by_name function and instead inserts the variable into the SQL statement unescaped (YOLO).
$sql = "UPDATE MYTABLE SET OPT = '1' WHERE FIELD = '".$record['value']."'";
$stmt = oci_parse($this->conn, $sql);
My problem
The first snippet does not work, while the second one works fine, i.e. the UPDATE statement succeeds every time on the second method while it fails every time on the first.
Both versions of the UPDATE should work. However when I use the oci_bind_by_name function for a few fields, somehow the variable is getting changed. (I am doing more rigorous error checking in the actual code).
My question
What is going on here? How can I still use the oci_bind_by_name instead of just concatenating the variable directly into the SQL statement?
Per the developers:
Neither PHP OCI8 or PDO_OCI support NVARCHAR, NCHAR or NCLOB types.

MySQL Update Syntax

I'm trying to write a MySQL in my PHP script which will update a field in the database however I get the error:
Fatal error: Wrong SQL: 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 ''user' SET 'currentsong' = '' WHERE 'userid' = '1893''
While using this code.
$setcurrentsongsql = "UPDATE 'user' SET 'currentsong' = '$currentsong' WHERE 'userid' = '$sql1'";
$setcurrentsong = $db->query($setcurrentsongsql);
I'm sure it's something simple however I'm completely baffled. Even if I replace the variables with just a normal string it doesn't work.
Thank you in advance for any help.
Use back ticks not single quotes for table names and column names. Try the following:
$setcurrentsongsql = "UPDATE `user` SET `currentsong` = '$currentsong' WHERE `userid` = '$sql1'";
In MySQL, identifier quote character is the backtick " ` ". This short page should give you a good understanding of the schema rules, identifiers and so on: http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
mySQL uses the backtick ` for column and table names, and apostrophes ' for string constants. However these aren't needed unless you're using a reserved keyword (such as your table is actually called "table") or your table or column name contains spaces (such as "my table").
You can use:
$setcurrentsongsql = "UPDATE `user` SET `currentsong` = '$currentsong' WHERE `userid` = '$sql1'";
Or:
$setcurrentsongsql = "UPDATE user SET currentsong = '$currentsong' WHERE userid = '$sql1'";
Also, if $currentsong comes from an untrusted source, you might want to worry about SQL injection.

Using reserved word in sql update query in php overwrites the whole table

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

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.

SQL syntax error were am i goign wrong?

Hello guys and girls im trying to a sql update but think i forgot a ' or a "
im getting this error messege
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 ''Brock'='1'WHERE username = 'admin'' at line 1
The fault lies with in this bit of code if i take the code out the page loads witht he rest of the scripts on it. But need it two do the update.
$blah = mysql_query("UPDATE users SET '".$_SESSION['gymleader']."'='1'WHERE username = '".$_SESSION['username']."'")
or die(mysql_error());
Were am i going wrong ?
You miss a space between the '1' and the WHERE if I am not mistaken. And you should use backticks (`) when you want to escape a column name
So your code becomes:
$blah = mysql_query("UPDATE users SET `".$_SESSION['gymleader']."`='1' WHERE username = '".$_SESSION['username']."'")
Note the ` instead of the ' around the column name (right after the SET).
Further possible improvements:
In case the column is of type INT, you can replace the '1' by 1 (without the ')
You should never directly use the $_SESSION,$_POST,$_GET or other values which can be altered by users in your queries. Do a Google search on SQL injection for more information
UPDATE user SET field = '1' WHERE ...
instead of
UPDATE user SET 'field' = '1' WHERE ...
and if your field is of type int, you might use
UPDATE user SET field = 1 WHERE
If you want to escape your fieldname, use
`field`
in backticks `
Besides the fact that this looks like a bad idea to code like this, assuming you have a column named Brock then you should use this types of quotes instead:
$blah = mysql_query("UPDATE users SET `".$_SESSION['gymleader']."`='1' WHERE username = '".$_SESSION['username']."'")
or die(mysql_error());
Notice I replaced your ' with `

Categories