Sandeep Singh Sandeep Singh - 4 months ago 6
SQL Question

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.

Answer

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