Am I doing something wrong here?
Of course I am, hah otherwise it'd be working. Can anybody tell me what in these statements aren't allowed?
$signedin = $_SESSION['signed_in'];
mysqli_query($con, 'UPDATE users SET last_created_article = NOW() WHERE username ="' . $signedin .'"');
If you use double quotes to wrap your mysql query, then you don't have to outquote the $signedin.
$signedin = $_SESSION['signed_in'];
mysqli_query($con, "UPDATE users SET `last_created_article` = NOW() WHERE `username` = '$signedin'");
Also, why isn't your mysql stuff in a class? You can find tons of them on the web. So all your connection related files are in one place. So you can simply do $db->query("");
Also, most of those mysql classes have very good debugging methods. I would send you mine, but it takes time to upload it to GitHub.
https://github.com/a1phanumeric/PHP-MySQL-Class/blob/master/class.MySQL.php
Here is something similar.
EDIT: So where is my mysql macro. In the readme, you can figure out how to use it. And this one will output an error right away, if something is wrong :)
http://kallevaravas.github.io/kvMysqlMacros/
Related
I'm getting this error in my Magento script:
Product not added exception:exception 'PDOException' with message
'SQLSTATE[42000]: Syntax error or access violation: 1064 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 Secret'' at
line 1'
Some background info:
I have a PHP script running on a cron job to add and update products. It runs a while now, but I got just now this error. I think it's because the manufacturers name got an apostrophe in it. But I have no clue how to fix it.
Changing the manufacturer's name is not a option.
function addManufacture($pid,$men){
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = "SELECT manufacturers_id FROM p1_manufacturers WHERE m_name='".$men."'";
$lastid = $readConnection->fetchOne($query);
$write = Mage::getSingleton("core/resource")->getConnection("core_write");
if($lastid){}else{
$url = createUrl($men);
$query = "insert into p1_manufacturers (m_name,identifier,status) values ('".$men."','".$url."',1)";
$write->query($query);
$lastid = $write->lastInsertId();
}
$query1 = "insert into p1_manufacturers_products (manufacturers_id,product_id) values ('".$lastid."','".$pid."')";
$write->query($query1);
$query3 = "SELECT manufacturers_id FROM p1_manufacturers_store WHERE manufacturers_id='".$lastid."'";
$mid = $readConnection->fetchOne($query3);
if($mid){} else {
$query2 = "insert into p1_manufacturers_store (manufacturers_id,store_id) values ('".$lastid."',0)";
$write->query($query2);
}
}
Here is the problem:
$query = "SELECT manufacturers_id FROM p1_manufacturers WHERE m_name='".$men."'";
Replace that with:
$menEscaped = mysql_real_escape_string($men);
$query = "SELECT manufacturers_id FROM p1_manufacturers WHERE m_name='".$menEscaped."'";
For readability, I might be inclined to reformat it thus:
$menEscaped = mysql_real_escape_string($men);
$query = "
SELECT
manufacturers_id
FROM
p1_manufacturers
WHERE
m_name='{$menEscaped}'
";
The problem is you are not escaping your input variables, and if this comes from user input, you may find people injecting SQL of their own choice into your database. And that's generally not good!
Addendum: the above may work, but I've just spotted you are using a library called Mage. This being the case, you will need to find out how to escape strings using that library - it will be something like $write->escapeString($men).
As has been noted in the comments, it is even better if you can switch to paramerisation. You'll need to check if your library supports that.
Your problem is being caused by an unescaped single-quote appearing in your data, and creating a syntax error in the queries you are submitting to your database.
Unfortunately, your database access code is hidden in some class, so it's not immediately obvious what changes are required. However...
As an absolute minimum you should escape any user data before applying it to the database. For this function this means
$men = mysql_real_escape_string($men);
$pid = mysql_real_escape_string($pid);
added at the top of the function. I have assume you are using 'mysql()` in this code.
Watch the line $url = createUrl($men); as this will be affected by this change. You may need further modifications here, and createUrl() may need to be changed too.
You will need to make similar changes in every function that accesses your database.
If you are using mysqli() more work will be required as the arguments are different and this 'easy' fix won't work.
Ultimately you should look to rewrite your code to use prepared statements.
Your code is seriously vulnerable to attack. There is a lot of work here. Get to it!
Edit
Thanks to #halfer for spotting the use of Mage. Magento uses the Zend framework which in turn uses PDO objects. Delving into the code you can rewrite the functions to use prepared statements which will deal with your problem effectively. This answer has a fuller description. This is a better fix than I suggested above, but you still have a great deal of work to do.
I found similar questions but can't solve my problem yet. Here is the relevant code:
$query = "SELECT * FROM conceptos WHERE descripcion = '$descripcion'";
if ($result = mysql_query($query,$connection)){
if (mysql_num_rows($result) > 0){
//Do something
} else {
die($query);
exit;
}
} else {
die(mysql_errno() . ' - ' . mysql_error());
exit;
}
I don't have problems with the connection or the permissions, because this code snippet is inside a loop and the other queries enter the "Do something" section. But when I take the echoed query and execute it in phpMyAdmin, it returns 1 value as expected. Why? What reasons can lead to this behavior? Thanks in advance for any advice.
I had this problem and found that it was because I junked up my database by copy/pasting directly to the database from MS Word. Pasting had inserted special slanted apostrophes that PHPMYADMIN could apparently parse but my php code could not. Once I replaced those with a standard single quote, all was well.
Try this "SELECT * FROM conceptos". If it's worked, you have bad query in "WHERE ..."
Are you sure your query is searching for the right description? The double quotes should expand all internal variables, but you do have single quotes as well in case there is a copying to stackoverflow issue.
This will ensure that the description is expanded in case.
$query = "SELECT * FROM conceptos WHERE descripcion = '" . $descripcion . "'";
Secondly, have you validated the variable contents you are using, as suggested by #crotos?
The mysql_ are also deprecated, so you should use PDO, or at the least, mysqli_.
You can try to setup the general query log of your mysql server and see what queries are really executed. See http://dev.mysql.com/doc/refman/5.1/en/query-log.html
Also, check your encodings. Maybe your mysql connection is in ISO8859-1 and your table fields are in UTF-8 (or the opposite). Do you have any accents or special characters in your data?
i also faced this problem and got it solved using:
mysqli_query($con,$query);
instead of
mysql_query($query);
coz its depreciated
source:
File Downloading error from database php
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.
[UPDATED] with new code "sql_real_escape_string()"
[UPDATED] if anyone wants to look at the site its at Test site
[UPDATED] with the while code showing any results via echo
Hello All,
I have looked at many posts on this matter, but simply cannot understand why the following code doesn't work:
$username = $_POST['username'];
// get the record of the user, by looking up username in the database.
$query = sprintf("SELECT UserName, Password FROM userlogin WHERE UserName='%s'", mysql_real_escape_string($username));
$result = mysqli_query($dbc, $query) or
die ("Error Querying Database for: " . $query .
"<br />Error Details: " . mysql_error() . "<br/>" . $result);
while ($row = mysqli_fetch_assoc($result))
{
Echo($row['UserName']);
}
The Code seems to be correct... the database is working perfectly (for input purposes) and the connection is a shared connection applied with require_once('databaseconnection.php'); that is working for the registration side of things.
like normal I'm sure this is something simple that I have overlooked but cannot for the life of me see it!
I do not get any error messages from the myssql_error() its simply blank.
any help would be much appreciated.
Regards
Check the username you try to query as it might be empty. Do you really use a post-request to run that script? How do you verify that it does not work? What do you do with $data after the query?
If just nothing seems to happen it is likely your query did not match any record. Check for whitespace and case of the username you are looking for.
Mind those warnings:
Use a prepared statement or at least sql-escape any user-input before using it in sql.
Don't use die in serious code only for debugging.
The $data will contain a result object. You need to iterate over it using something like mysqli_fetch_assoc($data).
Also, you can interpolate variables directly into double quoted strings - i.e. UserName='".$username."'" could be written more cleanly as UserName='$username' rather than breaking out of the string.
Also, please sanitize your input - all input is evil - using mysqli_real_escape_string() function. You've got a SQL injection exploit waiting to happen here.
Bear in mind that it's a very good idea to validate all data to be inserted into a database.
Very often you have problems with query itself, not implementation. Try it in phpMyAdmin first and see if there are any problems.
Check server logs.
BY THE WAY: Never put variables from POST to query! That's definitely a SQL injection'
You might have some issue with the query.
Have you Tried to echo the $query and run that directly with mysql client or workbench?
This piece of code seems ok. That is, if $dbc contains an actual database connection. But the choice of naming that variable $data while the function actually returns a result object or a boolean, indicates that you may process the data wrong.
If that is not the problem, we'll definately have to see more code.
Try printing $data variable instead of printing only query. Check, whether you are able to get any error messages. If you could see any data then you should use mysql fetch function to iterate things. Try it.
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