如何将字符串与变量连接以动态设置标题位置?

时间:2014-04-29 17:09:06

标签: php mysql

我在类中编写了一个函数,用于更新MySQL数据库中的简单产品表,到目前为止工作正常。

但是,一旦成功更新,我希望标题位置动态地重定向到每个项目的相应编辑页面,例如edit.php?id=5。使用下面的代码,url和$id - 变量不会成功连接。我在浏览器中获得的只是.../edit.php?id=

public function update($id,$category_id,$name,$description,$price,$image){

        $query="UPDATE $this->db_table SET id='$id', category_id='$category_id', name='$name', description='$description', price
        ='$price', image='$image' WHERE id='$id'";

        $result= $this->Database->query($query) or die(mysqli_connect_errno()."Data cannot be inserted.");

        if($result){
            header('location:edit.php?id=' . $id);  
        }
    }

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

与字符串串联对我来说是正确的。

您确定您的数据库记录是否已正确更新? 如果将正确的$ id传递给此方法,则它应存在于重定向标头中。

我建议你重新发现在新位置没有$ id值的可能性并进行一些调试,例如:

public function .....
    echo "The ID is " . $id;

    // the update code here

    if($result){
        echo 'location:edit.php?id=' . $id; 
        exit; 
        header('location:edit.php?id=' . $id);  
    }

    die('result not valid');

检查打印的$ id值是否相同,是否是预期的以及记录是否真正更新。您不应该看到字符串'result not valid'作为之前的代码退出。

这不是测试的最佳实践,但应该可以帮助您了解正在发生的事情。

干杯

PS。 当你说'我进入浏览器的所有内容'是你的意思是你已被重定向到那个页面,对吗?

答案 1 :(得分:0)

最终解决方案是在方法中再次定义$id,如下所示:

public function update($id,$category_id,$name,$description,$price,$image){

        $query="UPDATE $this->db_table SET id='$id', category_id='$category_id', name='$name', description='$description', price
        ='$price', image='$image' WHERE id='$id'";

        $result= $this->Database->query($query) or die(mysqli_connect_errno()."Data cannot be inserted.");

        $id = $_REQUEST['id'];

        if($result) {

            header('location:edit.php?id=' . $id);  
        }
    }