PHP - PostgreSQL error updating table - php

I fetch some values from a database and display them on some textfields. When I change one specific value and try to store it back to the database, it's done properly. But when I try to do the same with any other value from any other textfield, I get the error "syntax error at or near where". Any thoughts?
'UPDATE table1 SET "intcolumn"='. $value .', "stringcolumn"=\''. $value2.'\''.' WHERE "column2"='.$value3);
Update on intcolumn is done properly. On stringcolumn I get the error, even if I update only stringcolumn

Changing your apostrophes to quotes and putting your values inside delimiters will help readability.
This should make debugging easier, and easier to spot rather than having to escape characters etc.
pg_query($db, "UPDATE table1 SET intcolumn={$value}, stringcolumn='{$value2}' WHERE column2={$value3}");
A better approach would be to use pg_query_params and let postgres worry about escaping characters, and will stop injection attacks.
$params = array($value, $value2, $value3);
pg_query_params($db, "UPDATE table1 SET intcolumn=$1, stringcolumn=$2 WHERE column2=$3", $params);

Related

MySQL Update Syntax Using Parentheses

In the following code $keyresult and $valueresult are comma separated lists of columns in my db and the values I want to put into them in the identified row. The problem is, the code isn't doing what I hoped it would and is returning a syntax error in the query.
$q3 = "UPDATE post SET ($keyresult) VALUES ('$valueresult') WHERE user_id='$user_id' AND post_id='$post_id' AND post_status='active'";
How can I fix the syntax of this?
You are mixing INSERT and UPDATE syntax.
$q3 = "UPDATE `post` SET `$keyresult` = '$valueresult'
WHERE user_id='$user_id' AND post_id='$post_id' AND post_status='active'";
I am assuming you are properly escaping $valueresult, $user_id, and $post_id before you are executing your query. If not, and these are user-supplied values, you are wide open to SQL injections. I recommend looking into prepared statements to eliminate this risk.

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.

MySQL Update from PHP form

As a novice MySQL user I tried to insert, but I just read on the MySQL documentation that you can only insert on blank rows. My UPDATE statement needs work though, and I'm not sure that I have the syntax correct.
$query3 = "UPDATE `offices` SET `scash`="$total" WHERE `officename`="$office"";
offices is the table name. scash is the row to be updated. $total is a variable pulled from a post. $office is a variable pulled from the same database. I only want to set scash to total where the officename is $office.
Parse error: syntax error, unexpected T_VARIABLE is the error I'm getting.
$query3 = "UPDATE `offices` SET `scash`='$total' WHERE `officename`='$office'";
Replace the double quotes with normal quotes in the string since double quotes are string delimiters and can't be used in the string.
And as Marc B mentioned your code might be vurnerable for SQL injections. See this post how you can avoid that.
You are going wrong at quotes
$query3 = "UPDATE `offices` SET `scash`="$total" WHERE `officename`='$office'";
Also always use LIMIT 1 if you want to update just a single row...
And sanitize your inputs before updating your row, atleast use mysqli_real_escape_string()
if you still want to use double quotes inside double quotes escape it..
your query can be modified as follows..
$query3 = "UPDATE `offices` SET `scash`=\"$total\" WHERE `officename`=\"$office\"";

Simple PHP/MySQL Syntax error, told to "check manual?"

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 's website.
mysql_query("UPDATE Scholarships2 SET Requirements2 = '$requirements2'
WHERE scholarshipID = '$sID'")
or die("Insert Error1: ".mysql_error());
I read other Stackoverflow questions/answers on this subject but cannot find the reserved word I am using.
$sID is just an int while, $requirements2 is
$regex = '/<h4>Requirements<\/h4>([\n\n\n]|.)*?<\/table>/';
preg_match_all($regex,$data,$match);
$requirements2 = $match[0][0];
for the right syntax to use near 's website
This means it's complaining about the bit of your query that is 's website. "Where is that bit in your query?", I hear you ask.
Well, one of those variables in there contains something like Bob's website and the fact that you're blindly injecting that into your query will give you something like:
UPDATE Scholarships2 SET Requirements2 = 'Bob's website' ...
This particular query will not go down well with the SQL parser :-)
Other possibilities that don't immediately choke the parser will also not go down well with your customer base when little Bobby Tables steals or deletes your credit card database.
See this link for a fuller explanation and strategies for avoidance. In your case, that's probably going to involve mysql-real-escape-string.
In other words, you'll need something like:
mysql_query(
"UPDATE Scholarships2 SET Requirements2 = '" .
mysql_real_escape_string($requirements2) .
"' WHERE scholarshipID = '" .
mysql_real_escape_string($sID) .
"'"
) or die("Insert Error1: ".mysql_error());
As an aside, if $sID is just an integer (and not subject to injection attacks), you could probably remove the quotes from around it. I don't think it matters with MySQL (due to its "everything is a string" nature) but your query won't be portable to other DBMS'.
It depends on the values you have in your variables
Depending on the data type here is what you can do
$requirements2 = mysql_real_escape_string($requirements2); // escape string
$sID = (int)$sID; // force integer
the problem is if you have a string in your $requirement and it contains a single quote ' it will break your sql statement.
Here is something i often do to organize my code.
$sql = "UPDATE Scholarships2 SET Requirements2 = '%s'
WHERE scholarshipID =%d";
$sql = sprintf($sql,
mysql_real_escape_string($requirements2),
(int)$sID
);
Are you just taking form fields in from a POST or AJAX query? It sounds like you have a string containing 's website.
Make sure you run your code though mysqli_escape_string.
You need to escape whatever input you are getting in $requirements2
You can do this by
$req2=mysql_real_escape_string($requirements2);
mysql_query("UPDATE Scholarships2 SET Requirements2 = '$req2'
WHERE scholarshipID = '$sID'")
or die("Insert Error1: ".mysql_error());
This will escape any special characters like the apostrophe found in $requirements2
The problem is that your $requirements2 variable contains a single quote (the error message shows it when it says near 's website - presumably you're inserting something like welcome to Sal's website). When MySQL encounters this character, it's interpreting it as the termination of the entire string.
For example, if you substituted the phrase Welcome to Sal's website into your query where $requirements2 currently is, your query would look like this:
UPDATE Scholarships2 SET Requirements2 = 'Welcome to Sal's website'
As you can see, this results in a quoted string Welcome to Sal with the rest of the string hanging off the end not a part of anything. That's the part that the error is complaining about.
You really need to switch to PDO and prepared statements, otherwise you're leaving yourself wide open to these types of errors, including SQL injection which is a Very Bad Thing.
Prepared statements allow you to specify queries with placeholders where dynamic data can be placed. This extra data is then passed to PDO in a separate function where PDO/the database can determine the best way to sanitize it so that it doesn't get misinterpreted as part of the query structure itself.

Sql query problem

I have the below sql query that will update the the values from a form to the database
$sql=
"update leads set
category='$Category',
type='$stype',
contactName='$ContactName',
email='$Email',
phone='$Phone',
altphone='$PhoneAlt', mobile='$Mobile',
fax='$Fax',
address='$Address',
city='$City',
country='$Country',
DateEdited='$today',
printed='$Printed',
remarks='$Remarks'
where id='$id'";
$result=mysql_query($sql) or die(mysql_error());
echo '<h1>Successfully Updated!!.</h1>';
when i submit I dont get any errors and the success message is displayed but the database isnt updated . When i echo the $sql, all the values are set properly. and when i ech the $result i get the value 1.
can someone please tell me what am i doing wrong here??
Have you tried running the echo of $sql directly using some DB tool? It may provide a more informative error. Alternatively, if that works you may have an issue where the transaction isn't being committed. Often a connection is set to automatically commit transactions, but that may not be the case here. Try adding a commit.
And have you ever heard of SQL injection attacks?
If you have a query that is not giving the expected result or receiving an error, and the problem isn't obvious, you should generally take a look at the final query just before it's run. Try using this right before running the query:
echo $sql;
exit;
Viewing the actual query often makes it obvious what the problem is, especially when the query includes variables. If the problem still isn't obvious, you can paste the query as is into a query browser to get feedback directly from the database engine.
Interestingly, using parametrized queries, you won't get to see the parameter values, as the parameters get replaced by MySQL, not PHP, however, you'll still get to see the entire prepared query.
Also, you can see the number of affected rows from your UPDATE statement with the mysql_affected_rows() function. You could put this immediately after the query is run:
echo ("Updated records:", mysql_affected_rows());
Spaces are often forgotten when concatenating queries.
$sql = "SELECT * FROM ducks";
$sql .= "WHERE duck = 'goose'";
When echoing the above query, we see:
SELECT * FROM ducksWHERE duck <> 'goose'
I'm guessing that the WHERE clause in your UPDATE statement isn't matching an "id = '$id'".
Also, is the id column really a string? You've put single quotes around the value. MySQL will cast the string to an integer if needed, but if it's an integer, save the database some work and remove the single quotes.
try to echo $sql and run it directly in any database console, may be there is no record with id = $id
SQL Injection can be the answer. Not an intentional attack (at this moment), but if your parameters have some unexpected information like quotes or other reserved characters you can have strange results. So, try to run this SQL directly in your database administration utility.
Try doing this
"""update leads set
category="$Category",
type="$stype", etc...; """
See if that works

Categories