Can't Save MySQL Query [duplicate] - php

This question already has answers here:
Escaping single quote in PHP when inserting into MySQL [duplicate]
(8 answers)
Closed 7 years ago.
I'm having an issue with my MySQL query/php, I try to update a row in my database that will work usually, but when the string has a ' in it, for example
I don't like green eggs and ham.
The ' in it will cancel the whole response out and not update the row, so if I put something like this without the ' for example:
I dont like green eggs and ham.
The string will save to the row. Below is the MySQL query used and where I get the string from.
$NewMessage = $_POST['message123'];
mysql_query("UPDATE Account SET `function` = 'Message', `note` = '$NewMessage' WHERE `id` = '$ID' AND `Online` = '1'");
If you need anymore source or anything, please let me know, let me know what you think, thanks!

Use *_real_escape_string
$NewMessage = mysql_real_escape_string($_POST["message123"]);
But of course, mysql_* API is already deprecated and I would recommend to you to use prepared statement instead.

Hey friend you are need to change single ' with '' commas 2 times. then it is insert your value correct in table other generate error.
Real escape string use where we are need value like this doest. if we user value in database like it does't then right one is use '' 2 time single commas no doule commas

Use simply addslashes() To read more about it click here
E.g in you code simply use addslashes() something like this
$NewMessage = addslashes($_POST['message123']);
I hope it will work for you.

Related

SQL add to already existing value [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 4 years ago.
I have a value in my MYSQL database, all I want to do is to increase the current value with a new one, this is what I have tried
} elseif ($gametype == "veckanskluring"){
$sql = "UPDATE users SET veckanskluring='veckanskluring'+'$score' WHERE id='$id'";
$retval = mysql_query( $sql, $link );
echo "GAME == $gametype";
}
But for some odd reason, this won't work.
I have searched online and found examples, but they all look, almost exactly the same as my code.
// Sidenote this is not the whole code, obviously.
Everything except the part where I add the new value to the old value works, and if I remove 'veckanskluring'+ it updates without any problems.
I strongly believe something is wrong with this part - 'veckanskluring'+ as the other part works fine.
//NOTE2 score is always 999, just have it set to $score if I want to change it later.
UPDATE -
MY fault, apparently I had put '' around veckanskluring.
$sql = "UPDATE users SET veckanskluring=veckanskluring +'$score' WHERE id='$id'"; <-- Working.
Assuming that $score and $id are number you shoudl not use sigle quote around this vars
and assuming that veckanskluring is column name you must not use single quote aroud column name
"UPDATE users SET veckanskluring= veckanskluring +$score WHERE id=$id";
But the use of php var in sql is deprecated you at risk for sql injection .. take a look at your mysql driver for bindig param

Protect SQL query from special characters [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 8 years ago.
I'm trying to change the content of a string (from user's input), I'd like to remove any character that will let my query fail. For example, if I insert a second name with a " ' " in it, the query will fail.
Since I have to then output these rows from the DB, I'm wondering if there's any way to insert the string in the database while replacing the special character with its HTML value so that when I'm outputting it, the browser will do the rest.
I'm leaving you an example:
$string = $_POST['user_input']; // Let it be Lol'd
$sql = "INSERT INTO table(field) VALUES('$string')";
Now without anything done to the string I'd get the query as:
INSERT INTO table(field) VALUES('Lol'd')
What I'm looking for is something to turn the ' into ' so that in the DB it's saved Lol'd but when I echo it it'll just print Lol'd
There are lot of solutions. You can use a function like htmlentities():
$string = htmlentities($_POST['user_input']); // Let it be Lol'd
$sql = "INSERT INTO table(field) VALUES('$string')";
To read the string from your MySQL table, use html_entity_decode()
try this
$string = str_replace("'","\'",$_POST['user_input']);
$sql = "INSERT INTO table(field) VALUES('$string')";

how to create a dynamic query using 'IN' in mysql

I want to pass a string that contains many usernames, seperated by a comma,and want to pass it to query
$name_list='kesong,nicholas,jane'; //this value would change
$select_occupy=mysql_query("SELECT * FROM user_data WHERE `username` IN('$name_list') ORDER BY `occupy_date` ");// i think this would just search for a username which is 'kesong,nicholas,jane', instead searching them seperately
echo mysql_num_rows($select_occupy); //would echo 0
I know it works only when you specify like IN('$name1','$name2','$name3'), but I need a dynamic one
As a suggestion, just hold your names into an array and do like below:
$names=array('name1','name2','name3');
$namesToCheck="";
foreach($names as $name){
$namesToCheck.="'$name',";
}
//to remove the last ,
$namesToCheck=substr($namesToCheck,0,-1);
Now, you can put $namesToCheck into your IN query.
EDIT:
In this answer, this is assumed that you will prevent any possible SQL injections as current answer is just an idea about your question. The minimum suggestion to perform preventing SQL injections would be using mysql_real_escape_string function, which escapes special characters in a string for use in an SQL statement. For example:
$namesToCheck.="'".mysql_real_escape_string($name)."',";
//OR DO THIS ON FINAL STRING
NOTE THAT This extension is deprecated as of PHP 5.5.0. You can take a look at the PHP's official document in the following link:
mysql_real_escape_string
You can do it like this :
$namesToCheck = "'" .implode( "','" ,explode( ',' ,$name_list ) ) ."'";
And then use the $namesToCheck in the IN clause of your query .
The above code would convert :
kesong,nicholas,jane
to :
'kesong','nicholas','jane'

Cannot insert when word contains single quotes [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
How to escape single quotes in MySQL
(19 answers)
Closed 8 years ago.
I want to add single quotes word like "Dwi'q" and "Jum'at" in PHP MYSQL,
but I cant add that word, I try search anything but I dont found it.
my query is:
$query=mysql_query("INSERT INTO `pln`(`ppno`,`persno`,`pernum`,`psgrup`,`lv`,`pos`,`nppsimkp`,`persub`,`busrea`,`pdthr`,`gk`,`marstakey`,`bkey`,`bakun`,`numtd`,`email`,`bdate`) VALUES ('".$ppno."','".$persno."','".$pernum."','".$psgrup."','".$lv."','".$pos."','".$nppsimkp."','".$persub."','".$busrea."','".$pdthr."','".$gk."','".$marstakey."','".$bkey."','".$bakun."','".$numtd."','".$email."','".$bdate."')") or die(mysql_error());
Thanks for help.
In simple.. you can escape it with backslash..
$search_keyword="jum\'at";
but i recommend you to first sanitize the value before passing it into query.. using php function called
mysql_real_escape_string($search_keyword)
for ex;
$search_keyword=mysql_real_escape_string("jum'at");
first do this:
$a = mysql_real_escape_string("Dwi'q");
$b = mysql_real_escape_string("Jum'at");
and then run your query providing these variables in your query.
In order to insert values with ' you need to use mysqli_real_escape_string or mysql_real_escape_string. Also it better to use always when you are inserting values into DB in order to avoid SQL Injection.
And one more thing Please stop using mysql_* functions and start using mysqli_* function or PDO
Example
Using mysql_real_escape_string
$a = "some one's text";
$a = mysql_real_escape_string($a);
Using mysqli_real_escape_string
$con = mysqli_connect("localhost","dbusername","dbpassword","dbname");
$a = "some one's text";
$a = mysqli_real_escape_string($con,$a);

Why is there extra space being added whenever I execute PHP code that updates any text field in a MYSQL database?

I am building a blog site and am having trouble with updating fields in my MYSQL database. Whenever I hit the update button on the form that uses PHP, it adds extra space before the text string in the MYSQL text field. Here is the PHP code:
//UPDATE TEXT
$updated_text = $_POST['text'.$the_post['ID'][$n]];
if ($updated_text != "") {
$sql = "UPDATE posts SET TEXT = '".addslashes($updated_text)."' WHERE ID = '".$the_post['ID'][$n]."'";
$text_result = mysql_query($sql) or die(mysql_error());
}
Thanks
Not sure why you have this problem, but you could first try using trim to remove white-characters at the beginning and end of your string :
$updated_text = trim($_POST['text'.$the_post['ID'][$n]]);
If this solves the problem, it's because you are receiving those whitespaces from the form -- else... Well, strange ^^
A couple of other notes :
When escaping data to send it to your DB server, yOu should use the functions that are specific to your DB. Here, you are working with a MySQL database, and the mysql_* function, which means you should use mysql_real_escape_string instead of addslashes.
You are escaping the data you're putting in the TEXT ; but, to avoid SQL injections, you should protect the data use in the where clause too.
If your ID is a char/varchar in DB, it means using mysql_real_escape_string on $the_post['ID'][$n] too
If your ID is an integer in database :
the quotes arround the value are not necessary : quotes, in SQL, are the string-delimiter ; there is no need for any delimiter for integers
you should make sure you are sending an integer to the DB ; for instance, using intval($the_post['ID'][$n])
This will not change anything about your problem -- but taking care of security is always best ;-)
Perhaps its an issue of the text-area tag of your html - for example if its indented or so..
I found that the empty mySQL field was inserting " " into my html form value, so I used:
$variable = trim($variable," ");
to trim the unwanted space.
If you have a space or line break (in your code editor) in between and then remove them. I had the same issue earlier, but is now fixed.

Categories