简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM