0

I am trying to save a string with number and math operator into database. I want to save the face value of string, but php or mysql is calculating the string and then saving it to the database.

For example:

$stringValue = "24/2";
$query = "UPDATE winter";
$query .= " SET value =".$stringValue;
$query .= " WHERE name = 'xyz'";
$result = mysqli_query($connection, $query);

After running the code, I want the value saved in database to be "24/2", but it is being saved as 12.

3
  • 1
    It's mysql, because your query is ...SET value = 24/2...; try adding single quotes around it; or better yet, use parameterized queries to avoid "sql injection" vulnerabilities. (Edit: and by "it" I mean around the string value in the query.) Commented Jul 12, 2016 at 23:28
  • "but it is being saved as 12" - Because 24/2 is 12. Maybe you meant '24/2' as a string? Commented Jul 12, 2016 at 23:39
  • Uueerdo solution worked. I added quotes. Thanks Commented Jul 12, 2016 at 23:43

1 Answer 1

2

As @Uueerdo said you need to add ' sign before and after string in SQL.

$stringValue = "24/2";
$query = "UPDATE winter";
$query .= " SET value ='".$stringValue."'";
$query .= " WHERE name = 'xyz'";
$result = mysqli_query($connection, $query); 

Also you probably should use prepared statements (not much longer, but more safer).

$stringValue = "24/2";
$name = "xyz";
$query = "UPDATE winter";
$query .= " SET value=?";
$query .= " WHERE name=?";

$stmt = $connection->prepare( $query );
$stmt->bind_param( 'ss', $stringValue, $name );
$stmt->execute();
$res = $stmt->get_result();
Sign up to request clarification or add additional context in comments.

1 Comment

Note: even when you are the one generating the data, it's worth preventing sql injection since you can unintentionally sql-inject yourself. Rule of thumb: never trust any input.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.