Sandeep Singh
Sandeep Singh

Reputation: 897

How to save variable as a string in database?

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.

Upvotes: 0

Views: 1919

Answers (1)

Arnial
Arnial

Reputation: 1441

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();

Upvotes: 2

Related Questions