I´m creating a simple register and login system for a school project where you sign up through a form.
This is my code for the sign up process (without the bunch of tests´ that determine if fields were left empty etc.), this is just the query part.
Sorry about the variables containing Danish signs (ÆØÅ), and being in danish, but i have made a couple of tests where it didn´t matter if i used æøå or some other kind of letters.
I simply can´t understand why this little piece of code won´t work:
//I retrieve alot of variables from a form
$Fornavn = mysql_real_escape_string($_POST["Fornavn"]);
$Efternavn = mysql_real_escape_string($_POST["Efternavn"]);
$Koen = mysql_real_escape_string($_POST["Koen"]);
$Etnicitet = mysql_real_escape_string($_POST["Etnicitet"]);
$Brugernavn = mysql_real_escape_string($_POST["Brugernavn"]);
$Password = mysql_real_escape_string($_POST["Password"]);
$Mail = mysql_real_escape_string($_POST["Mail"]);
$Haarfarve = mysql_real_escape_string($_POST["Haarfarve"]);
$Oejenfarve = mysql_real_escape_string($_POST["Oejenfarve"]);
$Vaegt = mysql_real_escape_string($_POST["Vaegt"]);
$Hoejde = mysql_real_escape_string($_POST["Hoejde"]);
//The query
mysqli_query($con, "INSERT INTO bruger (Fornavn, Efternavn, Køn, Etnicitet, Brugernavn, Password, Mail, Hårfarve, Øjenfarve, Vaegt, Højde)
VALUES ('$Fornavn', '$Efternavn', '$Koen', '$Etnicitet', '$Brugernavn', '$Password', '$Mail', '$Haarfarve', '$Oejenfarve', '$Vaegt', '$Hoejde')");
echo $Fornavn;
Edit:
I know it doesn´t work since nothing appears in my mysql database after i run the code.
It just returns zero rows (i use phpmyadmin btw.) And i don´t really get any error messages or anything.
As suggested i have tried to use Mysqli_* for my variables instead:
//I retrieve alot of variables from a form
$Fornavn = mysqli_real_escape_string($con,$_POST["Fornavn"]);
$Efternavn = mysqli_real_escape_string($con,$_POST["Efternavn"]);
$Koen = mysqli_real_escape_string($con,$_POST["Koen"]);
$Etnicitet = mysqli_real_escape_string($con,$_POST["Etnicitet"]);
$Brugernavn = mysqli_real_escape_string($con,$_POST["Brugernavn"]);
$Password = mysqli_real_escape_string($con,$_POST["Password"]);
$Mail = mysqli_real_escape_string($con,$_POST["Mail"]);
$Haarfarve = mysqli_real_escape_string($con,$_POST["Haarfarve"]);
$Oejenfarve = mysqli_real_escape_string($con,$_POST["Oejenfarve"]);
$Vaegt = mysqli_real_escape_string($con,$_POST["Vaegt"]);
$Hoejde = mysqli_real_escape_string($con,$_POST["Hoejde"]);
//The query
mysqli_query($con, "INSERT INTO bruger (Fornavn, Efternavn, Køn, Etnicitet, Brugernavn, Password, Mail, Hårfarve, Øjenfarve, Vaegt, Højde)
VALUES ('$Fornavn', '$Efternavn', '$Koen', '$Etnicitet', '$Brugernavn', '$Password', '$Mail', '$Haarfarve', '$Oejenfarve', '$Vaegt', '$Hoejde')");
echo $Fornavn;
But it doesn´t work.
Everything is stored as "Varchar" in the database with collation "utf8_danish_ci".
Answer to comments:
#John #Jayaram I do not retrieve any error messages, or perhaps i don´t know where they go? Im really new to Mysql and PHP.
#Adunahay Vaegt and Højde are stored as Varchar in the table.
#Gordon The code for the connection is as follows:
//We check the connection
$con = mysqli_connect("localhost","Mads","","meat-market");
//If there is a fail.
if (mysqli_connect_errno())
{
echo "<h1> Det er vores fejl:</h1><br /><h2>Kunne ikke forbinde til Databasen:</h2><br /> " . mysqli_connect_error();
exit;
}
Altough im sure the table exist and the database does since i can see it in Phpmyadmin. The user Mads also has all of the necessary permissions.
#Raphaël I´m not aware if you can use special chars, but i have made a couple of tests before where i tried with special chars and it seemed to work fine.
#dboals I don´t know what you mean (i´m new to php), further explanation would be welcomed.
It's because you're using mysql_* for your POST variables and mysqli_* for your DB connection and in your query using $con as the first variable, which is mysqli_* syntax.
Change:
$Fornavn = mysql_real_escape_string($_POST["Fornavn"]);
to
$Fornavn = mysqli_real_escape_string($con,$_POST["Fornavn"]);
and do the same for the others.
Sidenote: Use all mysqli_* functions exclusively for your entire code --- mysqli_* and mysql_* functions do not mix together.. (which I recommend you use and with prepared statements, or PDO)
An example of preparing and binding for mysqli_ can be found HERE.
I found out what was wrong.
First off i needed to change mysql_* to mysqli_* in my variables.
But after that it still didn´t work.
Then i tried to change the letters "æ ø å" to something that wasn´t special letters in the database.
It didn´t seem to matter in the variable names tho.
So instead:
Æ = AE
Ø = OE
Å = AA
So apparently special characters are no go, eventough it seems to be a bit inconsistent since i have done it with special characters before... I don´t know if it is dependent of the collaction of the database...
But thanks to everyone!
EDIT!:
I´m using the UTF8_Danish_ci collation in my table and all the rows.
But after this i still had the problem that if i entered a special character in the form, it would show up as A| or something like that in the database.
I have fixed this by doing the following for each variable that comes from the form:
$Fornavn =utf8_decode($_POST["Fornavn"]);
$Fornavn = mysqli_real_escape_string($con,$Fornavn);
And add the following parameter to my FORM tag:
accept-charset="UTF-8"
Still haven´t been able to execute mysqli queries where the row names contains Æ Ø or Å.
Related
I'm trying to use paypal ipn in order to insert things into a database when an order is complete.
I need to insert a sentence in a sql database, the sentence is:
"This is my sentence à é è"
The "é" and the "è" characters works completely fine but for the "à", it is replaced in the dabatase by "?".
I have litteraly no idea why the "à" doesn't work, I guess it's a problem with charset.
Here is my code:
$config = parse_ini_file('config.ini');
$conn = mysqli_connect($config['server_name'], $config['mysql_username'], $config['mysql_password'], $config['db_name']) or die(mysqli_error($conn));
mysqli_set_charset($conn, "utf8");
$mysql_qry_insert = "SET NAMES utf8 ";
$resultttt = mysqli_query($conn,$mysql_qry_insert) or die(mysqli_error($conn ));
mb_internal_encoding("UTF-8");
$sentence = $customIpnPaypalVar;
$mysql_qry_insert2 = "insert into dbTest values ('".mysqli_real_escape_string($conn,$customIpnPaypalVar)."')";
$resultttt = mysqli_query($conn ,$mysql_qry_insert2) or die(mysqli_error($conn ));
And the database show me: "This is my sentence ? é è".
I also tried to replace the à with à but it didn't work.
Thank you.
Edit:
I think that my problem come from paypal when passing datas from my form to the IPN, any ideas of what is going on ?
Edit 2:
The problem come from Paypal for sure, when I pass a custom variable in the custom field from paypal Form and retrieve it in the ipn in log it shows me good accent but when I insert the variable in the database the accent doesn't work, why is that ?
The solution of my problem was using mysqli prepared statement, for some reason the specials characters worked with this method. Moreover it seems to be more secure.
Thank you Magnus Eriksson for helping me there.
I am creating a chat feature for my project where people can send messages to each other, but the problem is i want user to send anything, text, quotes or anything... But the problem is when i am sending degree symbol or sign, it does not inserts anything.
My code (This is example of what i have tried) :
<?php
$message = htmlspecialchars($_POST['message']);
$message = mysqli_real_escape_string($con, $message);
//Here i am inserting everything
mysqli_query($con, "INSERT INTO message (message) VALUES ('$message')");
?>
Hope you guys have understand my problem, i need help, please help me.
It may be something related to the database's collation. Try changing it to utf8. You may also consider this option of mysqli - mysqli::set_charset().
Try with PDO, it should work even if $message contains quotes or anything:
$query=$pdo->prepare("INSERT INTO message (message) VALUES (:message)");
$query->execute(array(
"message"=>$message
));
I have made a database where email id and corresponding name and password is stored. I have successfully obtained a form's data.. where the user enters updated name and password. But the problem is occuring with the query which is as follows
$db = mysqli_connect(all details)...
$name = $_POST['name'];
$password = $_POST['password']:
$email = $_POST['email'];
$query = "UPDATE mytable SET name='$name',password='$password' WHERE emailid='$email'";
$result = mysqli_query($db,$query);
Though I am getting all form values succesffuly and until and unless I put the 'where' clause.It works.But obviously updates all values. i want it to work with where..but so far unsuccessful :(
you need to put {} around the variables if its surrounded by quote ''
so your query should look like this
$query = "UPDATE mytable SET name='{$name}',password='{$password}' WHERE emailid='{$email}'";
$result = mysqli_query($db,$query);
EDIT : also before saving data to database make sure to filter and validate data
You need to make sure that emailid exists in mytable, you truly intended to filter by it and in your database scheme it has a type which supports the posted data. It seems that you are sending strings, like 'foo#bar.lorem' and your emailid is an int or something in the database scheme. Check it by running
desc mytable;
You need to put curly brackets around variables if you use apostrophe around them, but as a matter of style I like to close the string and attach the $variable with a . as this coding style is closer to me personally.
If everything fails, see what is generated, by echoing out the query string, try to run that directly, see what the error is and fix until...
... until it is fixed.
Also, you do not encrypt the password and your code is vulnerable to SQL injection too. Please, read about password encryption and SQL injection and then protect your project against these dangers.
You can write your statement as:
$query = "UPDATE mytable SET name='".$name."',password='".$password."' WHERE emailid='".$email."'";
using . as string concatenating operator
I have a problem with inserting data in mysql base. I am using code below. Everything is OK but when I insert "Croatian" letters (č,ć,š,đ,ž) I get wrong letters in base (something like this "Ä,ć,Å¡,Ä‘,ž"). My mysql table is utf8_croatian_ci.
if (isset($_POST['nazivpredmeta'])) {
$nazivpredmeta = filter_input(INPUT_POST, 'nazivpredmeta', FILTER_SANITIZE_STRING);
if ($insert_stmt = $mysqli->prepare("INSERT INTO predmet (ImePredmeta) VALUES (?)"))
{
$insert_stmt->bind_param('s', $nazivpredmeta);
if (! $insert_stmt->execute())
{
header('Location: ../error.php?err=Greska: INSERT');
}
}
header('Location: ./index.php?page=predmeti&unospredmeta=OK');
}
But when I am using code below everthing is OK and for croatian letters I am getting correct letters.
if (isset($_POST['nazivpredmeta'])) {
$naziv = $_POST['nazivpredmeta'];
$sqlquery="INSERT INTO predmet (ImePredmeta) VALUES ('$naziv')";
$results = mysql_query($sqlquery);
if (mysql_error()) echo "GREŠKA! ".mysql_errno().":".mysql_error();
}
My question is what is wrong with first code and what I need to edit in first code??? And short explanation
It’s the use of the filter FILTER_SANITIZE_STRING in combination with anything else than pure ASCII, as I read from documentation.
FILTER_SANITIZE_STRING
sets the following filter_flags:
FILTER_FLAG_NO_ENCODE_QUOTES,
FILTER_FLAG_STRIP_LOW,
FILTER_FLAG_STRIP_HIGH,
FILTER_FLAG_ENCODE_LOW,
FILTER_FLAG_ENCODE_HIGH,
FILTER_FLAG_ENCODE_AMP
FILTER_FLAG_STRIP_LOW: strips characters that has a numerical value <32
FILTER_FLAG_STRIP_HIGH: strips characters that has a numerical value >127
See the documentation on filters sanitize and related documentation on filter flags for more information.
So this filter is only applicable to pure ASCII & should avoided at all.
Don't use filter_input(). It's one of those weird legacy PHP functions.
You want literal values, not 'filtered', because the db layer handles encoding etc. You can use mysqli statements (good!), but don't use filter_input().
To see the difference, you should var_dump() both values:
var_dump(filter_input(INPUT_POST, 'nazivpredmeta', FILTER_SANITIZE_STRING));
var_dump($_POST['nazivpredmeta']);
Using more functions isn't always better =)
Try: utf8_encode(filter_input(INPUT_POST, 'nazivpredmeta', FILTER_SANITIZE_STRING));
Try to make sure the connecting is UTF8 before you run the actual query. So this:
if ($insert_stmt = $mysqli->prepare("INSERT INTO predmet (ImePredmeta) VALUES (?)"))
Would change to this:
if ($insert_stmt = $mysqli->prepare("SET NAMES UTF8; INSERT INTO predmet (ImePredmeta) VALUES (?)"))
Or perhaps do it this way:
$mysqli->query($this->connecDB, "SET NAMES 'utf8'");
if ($insert_stmt = $mysqli->prepare("INSERT INTO predmet (ImePredmeta) VALUES (?)"))
Also, unrelated but worth pointing out is in he first chunk of code you are making calls to $mysqli->prepare() but in the next—where you say things are working—you are using mysql_query(). While not 100% technically wrong, you are mixing the mysql_* and mysqli_* extensions by doing this which can cause inadvertent confession in cases like this. You should stick to mysqli_* since mysql_* is depreciated and will be eliminated in PHP 5.5.
Before everything I just add $mysqli->set_charset('utf8');
And now both codes working.
Hi when ever I want to insert a comment into my database, I sanitize the data by using Mysql Escape String function this however inserts the following verbatim in field. I print the comment and it works fine and show me the text however when ever I sanitize it, it literally inserts the following into my db
mysql_real_escape_string(Comment)
This is my insert statement, The Id inserts correctly however the comment doesn't it just inserts the "mysql_real_escape_string(Comment)" into the field. what can be wrong?
foreach($html->find("div[class=comment]") as $content){
$comment = $content->plaintext;
$username = mysql_real_escape_string($comment);
$querytwo = "insert into Tchild(Tid,Tcomment)values('$id','$username')";
$resulttwo = $db -> Execute($querytwo);
}
If I'm reading the documentation correctly, you should make the call like this:
$db->Execute("insert into Tchild(Tid,Tcomment)values(?, ?)", array($id, $username));
That will account for proper escaping. Having unescaped values in your query string is dangerous and should be avoided whenever possible. As your database layer has support for SQL placeholders like ? you should make full use of those any time you're placing data in your query.
A call to mysql_real_escape_string will not work unless you're using mysql_query. It needs a connection to a MySQL database to function properly.
Since you're using ADODB, what you want is probably $db->qstr(). For example:
$username = $db->qstr($comment, get_magic_quotes_gpc());
See this page for more information: http://phplens.com/lens/adodb/docs-adodb.htm