简体   繁体   English

如何在数据库中将变量另存为字符串?

[英]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. 我想保存字符串的面值,但是php或mysql正在计算字符串,然后将其保存到数据库。

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. 运行代码后,我希望保存在数据库中的值为“ 24/2”,但是将其保存为12。

As @Uueerdo said you need to add ' sign before and after string in SQL . 正如@Uueerdo所说,您需要在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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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