2012-05-02 114 views
0

我在表格中编辑数据库中的表格。然而,用户可能不会选择一个图像,所以如果他们不我不想更新该字段。我尝试了几种方法来做到这一点,但没有工作。有没有简单的方法?谢谢。if语句在php mysql中

if ($_POST["image"]!=='') { 
     $image= "image=%s"; 
     $imageValue = "GetSQLValueString(".$_POST['image'].", 'text'),"; 
}; 

$insertSQL = sprintf("UPDATE taxi SET name=%s, taxi_link=%s, ". $image." WHERE id=%s", 
        GetSQLValueString($_POST['name'], "text"), 
        GetSQLValueString($_POST['link'], "text"), 
        $imageValue, 
        GetSQLValueString($_POST['id'], "int")); 
+0

你上面的尝试没有一个工作的原因所在。 'taxi_link =%s'后面的','。删除','并将第二行更改为'$ image =“,image =%s”;'。 –

+0

感谢您的指针,仍然有一个问题,在$ imageValue是空白的,但仍然把一个空白的输入给出一个错误 –

+0

我修复了您的查询在下面的答案。 –

回答

1

你可以做别的事情:

$arr_values = array('name' => $_POST['name'], 
        'taxi_link' => $_POST['link']); 

if (! $_POST["image"]) 
    $arr_values['image'] = $_POST['image']; 

$this->db->update($arr_values, array('id' => $_POST['id'])); 

update()仅处理数组,您可以根据条件简单地向数组添加其他值。

就我个人而言,我做了我自己的函数,这个函数可以完美地添加和使用数组值。

固定查询:

$image = ''; 
if ($_POST["image"] !== '') 
     $image= ", image=".GetSQLValueString($_POST['image'], 'text'); 

$insertSQL = sprintf("UPDATE taxi SET name=%s, taxi_link=%s {$image} WHERE id=%s", 
        GetSQLValueString($_POST['name'], "text"), 
        GetSQLValueString($_POST['link'], "text"), 
        GetSQLValueString($_POST['id'], "int")); 
+0

对不起,这里没有一个选项,虽然 –

+0

检查评论你的答案。它说你的例子有什么问题。 –

+0

再次感谢您的帮助,它的工作原理是,如果我将图像字段留空,但是当我选择图像时,出现错误49行上的taxi-edit.php中的参数太少查询是空的 –

2

如果我理解你的话,你不能把整个事情放在if语句中吗?

if ($_POST["image"]!=='') { 
     $image= "image=%s"; 
     $imageValue = "GetSQLValueString(".$_POST['image'].", 'text'),"; 
     $insertSQL = sprintf("UPDATE taxi SET name=%s, taxi_link=%s, ". $image." WHERE id=%s", 
        GetSQLValueString($_POST['name'], "text"), 
        GetSQLValueString($_POST['link'], "text"), 
        $imageValue, 
        GetSQLValueString($_POST['id'], "int")); 
     //execute query 
} else { 
    //tell the user nothing happened 
} //no semicolon required 

所以,现在它会构建,如果指定的图像执行查询,如果如果你使用像笨的框架,你可以简单地不是指定它

+0

我虽然这是他的第一意思,但他的意思是有更多优雅(和功能)的方式来更新图像列,然后他已经做到了。 –

+0

是的想到这个,但想知道有没有写多个查询的方式 –