0

For first time I have a mysql problem. I have an input field such as

<input type="text" name="myfield" id="myfield" />

So when the user presses the submit button I am getting the value with php

$myval = $_POST['myfield'];

Everything is ok so far. If my value in this input field contains an apostrophe ' and for example:

<input type="text" name="myfield" id="myfield" value="Niko's Dog" />

the mysql query:

mysql_query ("INSERT INTO users (myfield) VALUES ('$myval')");

Fails to insert the data..

Any opinions please? I need all characters to be valid.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Irene T.
  • 1,393
  • 2
  • 20
  • 40

6 Answers6

3

Try to add slashes like

$myval = addslashes($myval);
mysql_query ("INSERT INTO users (myfield) VALUES ('".$myval."')");

Either you can use mysql_real_escape_string directly.

mysql_query ("INSERT INTO users (myfield)
              VALUES ('".mysql_real_escape_string($myval)."')");
GautamD31
  • 28,552
  • 10
  • 64
  • 85
0

This happens when you don't escape your input

INSERT INTO users (myfield) 
VALUES ('Niko's Dog')
             ^-----------string end

You better use prepared statements. See here

Community
  • 1
  • 1
juergen d
  • 201,996
  • 37
  • 293
  • 362
0

Look into using Prepared Statements, to avoid escape issues, as well as malicious input:

$result;
if ($stmt = $mysqli->prepare("INSERT INTO users (myfield) VALUES (?)") {
    $stmt->bind_param("s", $myval);
    $stmt->execute();
    $stmt->bind_result($result);
    $stmt->fetch();
    echo "Your result is $result";
    $stmt->close();
}

You ahould also be using mysqli_*, as the old mysql_* functions are deprecated.

Rogue
  • 11,105
  • 5
  • 45
  • 71
0

First of all, never ever trust user input! Always filter it before using, because user is evil (you have to think like that while writing any software).

Also, you should skip using deprecated mysql_* and instead use eg. PDO (or mysqli_* if you want to use something more similar to mysql_*) which is very easy and gives you more possibilities. Eg. allows you to use prepared statements. Using this allows you to write safer and better software.

Elon Than
  • 9,603
  • 4
  • 27
  • 37
0

Just add below code into your server side file. so it will check every field of your form.

foreach ($_POST as $key => $value) {
    if(!is_array($value)){
        $_POST[$key] = mysql_real_escape_string($value);
    }
}  
Dhaval Bharadva
  • 3,053
  • 2
  • 24
  • 35
-1

other than addslashes and mysql_real_escape_string you can also use str_replace for the same:

$myval=str_replace("\'","'","$myval");
R R
  • 2,999
  • 2
  • 24
  • 42