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
));
Related
When I send an email through PHP I want it to update a database saying it has sent the message. But the code below is what I can find online that should work but it does not and I definitely have a connection to the database.
$sql = "UPDATE Mail SET Sent='1' WHERE key='$key'";
And I get no errors and everything else on the page runs right. Any help?
That's because "key" is a reserved word in MySQL. There are some others which you find here.
In SQL, 'key' is a keyword, maybe you can:
$sql = "UPDATE Mail SET Sent='1' WHERE `key`='$key'";
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 Å.
I want to store my values to db. Also I want to upload one image. My insert query is below. It's not working.
$query = mysql_query("insert into designingoption set name='$name1',positionCode='$pos',assetType='$ass',price='$price',createdOn='$createdon',lastModifiedOn='$laston',lastModifiedBy='$lastby')",$con);
Here name=$name is my image upload field..
Not sure whats not working, but, i gotta a pretty good idea the values are not inserted since you used ' (single quote) around $variables.
Try like this.
$query=mysql_query("insert into designingoption set name='".$name1."',positionCode='".$pos."',assetType='".$ass."',price='".$price."',createdOn='".$createdon."',lastModifiedOn='".$laston."',lastModifiedBy='".$lastby."')",$con);
You have mixed the syntax for the UPDATE and INSERT statements.
Correct syntax:
INSERT INTO designingoption ('name', 'positionCode', 'assetType', 'price', 'createdOn', 'lastModifiedOn', 'lastModifiedBy') VALUES ($pos, $ass, $price, $createdon, $laston, $lastby)
While you're at it, you might also want to consider switching to the mysqli-functions. The mysql-functions are deprecated.
Also be careful of SQL-injection. More information on the subject can be found here.
Update your query structure.
INSERT INTO designingoption (name,positionCode,assetType,price,createdOn,lastModifiedOn,lastModifiedBy) VALUES ('$name1','$pos','$ass','$price','$createdon','$laston','$lastby')
Also, make sure that all variables are populated, otherwise you get a PHP notice.
It wouldn't hurt to enclose table rows with `, like this:
INSERT INTO `designingoption` (`name`,`positionCode`,`assetType`,`price`,`createdOn`,`lastModifiedOn`,`lastModifiedBy`) VALUES ('$name1','$pos','$ass','$price','$createdon','$laston','$lastby')
Some words are reserved by the system and must be used properly, otherwise you just receive error.
A little research as revealed (even to my surprise) that your syntax is correct.
http://dev.mysql.com/doc/refman/5.5/en/insert.html
Would you please edit your question with exact error you're getting?
I am doing a really simple script to delete a row out of a database. I have done it before with almost identical code but for some reason this wont work!
Viewmessages.php has no problem running but when I try and delete the row using deletemessage.php I receive the an sql error, I only have one line of sql:
viewmessage (sending info to deletemessage.php):
echo "<a href='deletemessage.php?contactname=".$contactname."'>Delete</a>";
The following is the delete message code:
<?php
session_start();
if ( !isset($_SESSION['adminusername']))
{
header("Location:admin.php");
exit();
}
require "dbconn.php";
$contactname = $_GET['contactname'];
$query = "DELETE FROM message WHERE contactname =".$contactname;
$results = mysql_query($query) or die(mysql_error());
header("Location: viewmessages.php");
?>
I cant work out what the error is! $contactname in the viewmessages.php file definately speaks of the primary key for the table!
Any Ideas?>
EDIT: I know that the problem lies with the contactname in the sql... for some reason it is not recieving it well, I did an echo to see what it thought the contactname was and it was correct. I then changed the variable and put in a string of one values in contactname and it deleted the row correctly... so the problem is the GET_['contactname'] but I am not sure what....
Enclose $contactname in quotes in the query, since it is a string. But escape it first! It is highly vulnerable to SQL injection the way it is now. I understand it may be an administrative page, but it is a very good habit to always observe, even when your users are trusted. (Especially since Mr O'Malley would break the SQL statement when you tried to delete him)
$concatname = mysql_real_escape_string($_GET['contactname']);
$query = "DELETE FROM message WHERE contactname ='".$contactname . "'";
Always beware when deleting via a hyperlink. Looks like you are checking for admin privileges before allowing this to execute, but be sure these links are not accessible to the broad Internet, where they might get crawled.
Wild guess here? $contactname is a STRING. Therefore it must be in quotes in the query. Also, you want people to destroy your database, apparently.
$query = "DELETE FROM `message` WHERE `contactname` = '".mysql_real_escape_string($contactname)."'";
You need quotes around a string you're inserting.
$query = "DELETE FROM message WHERE contactname ='".$contactname."'";
Note that this is MASSIVELY vulnerable to SQL injection. Someone could delete your entire database table with this code as it stands.
[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.