php, MySQL and variables containing å, ä and ö escape problem - php

I'm having some problem with my SQL syntax/escaping variables on my LAMP server.
The command I want to use is the following:
$sql=mysql_query("INSERT INTO '$table' (FirstName, LastName, StartDate, TimeStroke, DueDate, Duration, Price, Retailer, Checksum)
VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[startdate]','$_POST[timestroke]','$duedate','$_POST[duration]','$price','$_SESSION[name]','$random')");
The problem is that sometimes the $table variable contains characters like å, ä and ö.
Hence I need to put ' ' around $table to make sure it stays the same. However when doing that recieve the error:
"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 ''tablename' (FirstName, LastName, StartDate, TimeStroke, DueDate, Duration, P' at line 1".
Looks like the escaping by ' ' creates a problem.
I've tried with replacing the query with a mysql_real_escape_string:
"$sql=sprintf("INSERT INTO '".mysql_real_escape_string($table)."' (FirstName, [...]"
but that doesnt help me either.
Is there a way to keep the data in the variable intact and still be able to run the query? Or do I have to accept that å,ä,ö is banned from php/MySQL?

This is do to with character-encoding. Check out http://www.sitepoint.com/blogs/2006/03/15/do-you-know-your-character-encodings/
Put header('Content-Type: text/html; charset=utf-8'); at the top of your page
Also try doing mysql_set_charset('utf8'); before insert/reading from DB. Then you should put the following on your form that's posting to your PHP file:
<form action="/your-post-controller.php" method="post" accept-charset="utf-8">
Notice the accept-charset="utf-8 -- this is extremely important otherwise your header will report to the PHP file its in latin1
It should work then.
Also take a look at http://www.phpwact.org/php/i18n/charsets -- was trying to find the link, definitely worth a read for anyone interested in getting character encoding right, see the Iñtërnâtiônàlizætiøn string for testing your PHP&MySQL table

You would use backticks (`) to surround the table name. Nothing to do with Character-encoding:
$sql=mysql_query("INSERT INTO `$table` (FirstName, LastName, StartDate, TimeStroke, DueDate, Duration, Price, Retailer, Checksum)
VALUES ('{$_POST['firstname']}','{$_POST['lastname']}','{$_POST['startdate']}','{$_POST['timestroke']}','$duedate','{$_POST['duration']}','$price','{$_SESSION['name']}','$random')");
A couple of side notes here:
A: you should really user mysql_real_escape_string on any input coming in from an unknown source to avoid someone destroying your database with SQL Injection.
B: You should use ' around array associative indexes, reason being is that these all would throw notice undefined constant (or something to that matter) errors. Which will fill up your error log and make finding more critical errors a bit harder if you ever need to go back.

Related

Excecuting mysql querys in wordpress

im using the insert php code plugin in wordpress and im trying to do inserts and mysql querys, but there's an error that appears me:
Error: INSERT INTO porschec_clientes.clientes(
ID,
NAME,
LAST_NAME,
EMAIL,
PHONE,
PORSCHE,
REFERENCE,
STATUS
CODE,
)
VALUES (NULL,’name’,’last_name’,’email#gmail.com’,’123123′,’911′,’name’, 0, ‘cdcc34cd554621097f9a6fdc3b2cc728′)
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 ‘CODE,
)
look that in "CODE" there's this quote symbol " ‘ " (i dont know if the correct translation is quote but... whatever haha) but in my php code i have it this way
VALUES (NULL,'name','last_name','email#gmail.com','123123′,'911′,'name', 0, 'cdcc34cd554621097f9a6fdc3b2cc728')";
wordpress is changing the quote symbol when i update the page, there's any way that i can avoid this? thank you
You missed a ,after STATUS, that's what the error tells you. Usually it shows the part after the error.
REFERENCE,
STATUS, <--
CODE,
Beside that let it change the quotes. That's all right.

PHP Error with mySQLi

I'm learning PHP and MySQL and made a small website to help me learn. While I was implementing MySQLi, I kept getting an error with the code. I tried various things like trying to query all the tables contents but I get 0 rows even though I have a few already there. I'm using WAMP Server 2.5 and The connection is successful but anything else seems to not work.
When I use the code:
$sql = "USE mydb
INSERT INTO persons (Name, User, Pass)
VALUES ('John', 'Doe', 'johnexample');";
if ($conn->query($sql) === TRUE){
echo "Success";
}else{
echo "Error, Please Try Again Later<br>".$conn->error;
}
$conn->close();
I'm surprised this doesnt work because it's almost the exact same as the example on the W3 Schools webiste. I've seen other posts with this error but their solutions dont work. The error I get is:
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 'INSERT INTO
persons (Name, User, Pass) VALUES ('John', 'Doe', 'johnexample')' at line 2
Any help is appreciated! Thank You!
The issue is mysqli::query doesn't support multiple queries, and even if it did, it would require the ; terminator. This is causing your SQL syntax error.
If you want to change the current database for the connection, you can use:
$conn->select_db('mydb');
Then you can do your INSERT query without the USE part, which will be applied to mydb.
Be aware that the fieldnames are case-sensitive! please check if Name, User, Pass are really start with a capital.

What is wrong with my SQL/PHP syntax here?

So I have a database of downloads on my site set up that enables me to track the number of downloads, and I'm trying to set up a front-end for me and my compatriots to insert new downloads into the database. I'm setting up the front-end with primarily PHP.
The way my paging is set up removes the possibility of my forms simply posting, so instead I have JS serializing the data and reloading the page, then I unserialize the data in PHP, stick the values into a mysql query, and try to run it.
Here's what my SQL code looks like inside of PHP:
$sql = "INSERT INTO dl (id, file, desc) VALUES ('$idd', '$file', '$desc')";
Which turns into this string:
INSERT INTO dl (id, file, desc) VALUES ('a56', 'test.zip', 'cake')
But when the page tries to run it, I get this 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) VALUES ('a56',
'test.zip', 'cake')' at line 1
And the weirdness of that is compounded by the fact that the line of code running the query is not on line 1. It's on line 28.
Any help is appreciated :)
desc is a reserved keyword in MySQL.
The recommended workaround is to use backticks. From MySQL manual:
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.
If renaming the table or column isn't possible, wrap the offending identifier in backticks (`):
$sql = "INSERT INTO dl (id, `file`, `desc`) VALUES ('$idd', '$file', '$desc')";
Take a look at this question too: When to use single quotes, double quotes, and backticks in MySQL
Please change the column name of desc, its reserved by MYSQL. for more details please see list of reserved words on MYSQL Reserved Words
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
desc is a reserved word in SQL.
It is (together with ASC) used to determine the sorting order of the results.
Please try this.
$sql = "INSERT INTO dl (`id`, `file`, `desc`) VALUES ('".$idd."', '".$file."', '".$desc."')";
hope this is your useful.

php select statement doesn't give answer

I used php code from tutorial and it worked fine. But when I am rewriting it to me it gives me null. This code gives me what I want I mean it gives data in JSON format:
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
But this code even it looks identically doesn't work it gives null:
$q=mysql_query("SELECT username, firstname, lastname, email, phone1, skype, city, description
FROM mdl_user WHERE username LIKE'".$_REQUEST['usern']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
If I don't use $_REQUEST['usern'] and am getting data in JSON. But I need to use request to search specific data. So where could be the problem. Because I trustfully don't understand. It looks the same to me.
To make a pattern with LIKE use a %. Put it around or at any end, beginning or end.
$username = mysql_real_escape_string($_REQUEST['usern']);
$q=mysql_query("SELECT username, firstname, lastname, email, phone1, skype, city, description
FROM mdl_user WHERE username LIKE '$username%'");
^
|
// You also missed this space --+
Note your query is wide open to SQL injection. Just think if someone inserts year as '; drop table people; --. Use mysql_real_escape_string to sanitize those field.
And it's better to use explicitly $_POST or $_GET,ths makes sure your data is coming from proper source.
With LIKE you can use the following two wildcard characters in the pattern.
% Matches any number of characters, even zero characters
_ Matches exactly one character
I assume that you are getting no result because your username is not the exact same as $_REQUEST['usern'], and that's why you're using LIKE in the first place. You should therefore place wildcard characters to tell MySQL to look for any characters (%) before or after your string, for example:
LIKE '%".$_REQUEST['usern']."%'
Keep in mind that this is inefficient and you should try to use only one % after the string (if this will work for you), or better yet, find another way to search the table.
Edit: Also as a user in the comments noted and I failed to mention, this particular code is vulnerable to SQL injections. You should sanitize the variable $_REQUEST['usern'] before passing it onto the query.

PHP/AJAX issue inserting to mysql database

I'm having a problem inserting some data to a mysql database. I have used the same method with other features on the site, and this is the only one causing problems. It's meant to input into 3 field in the database (To, From, Message). As you can see it's a very basic messaging system.
I have the data coming into PHP via AJAX. But the problem is within the INSERT. I have messed around with it for over an hour now - no luck! Here is the code to insert:
mysql_query("INSERT INTO messages (To, From, Message) VALUES('$to','$loggedin','$message') ")
or die(mysql_error());
And here is the SQL syntax 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 'To, From,
Message) VALUES('Ryan','Ryan','hhh')'
at line 1
I have tried adjusting a lot of things, no luck! :(
"TO" and "FROM" are reserved keywords, it's not wise to use them as column names. You have to escape them with a back-tick "`". Try this:
INSERT INTO messages (`To`, `From`, `Message`)
See the list with reserved words: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

Categories