如何在mysql查询中写一个字符串变量?

时间:2014-06-03 05:43:35

标签: php mysql

我想实现此查询:

if(x=1){
$update = "close = '$date'";
}
else {
$update = "open = '$date'";
}
$query = "Update table1 set $update where id=100";
mysql_query($query);

但我收到错误,Mysql无法执行查询?

5 个答案:

答案 0 :(得分:1)

   <?php
    if($x==1){
    $update = "close = '".$date."'";
    }
    else {
    $update = "open = '".$date."'";
    }
    $query = "update table1 set $update where id=100";
    mysql_query($query);
    ?>

答案 1 :(得分:0)

将您的查询放在引号中。请尝试以下方法:

if(x==1){
  $update = "close='".$date."'";
}
else {
  $update = "open = '".$date."'";
}
$query = "Update table1 set ".$update." where id=100";
mysql_query($query) or die(mysql_error());

使用mysql_error()来检查你从mysql获得的错误

答案 2 :(得分:0)

使用此

<?php


if(x==1){
$update = "close = '$date'";
}
else {
$update = "open = '$date'";
}
$query = "Update table1 set '".$update."' where id=100";
mysql_query($query);

?>

答案 3 :(得分:0)

尝试使用此代码........

<?php
if($x==1){ // use $ for variables
    $update = "close = '".$date."' "; //always concatenate variables
}
else {
    $update = "open = '".$date."' ";
}
$query = "Update table1 set '".$update."' where id=100";
mysql_query($query, $connection); // don`t forget to add mysql connection 

?>

答案 4 :(得分:-1)

Replace 
$query = Update table1 set $update where id=100;

to
$query = "Update table1 set ".$update." where id=100";