简体   繁体   中英

How to concatenate a string with a variable to dynamically set the header location?

I wrote a function within a class that updates a simple product table within a MySQL-database, which works fine so far.

However, upon succesful update, I would like that the header location redirects dynamically to the respective edit page for each item, eg edit.php?id=5 . With the code below, the url and the $id -variable are not concatenating succesfully. All I get in the browser is .../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);  
        }
    }

How can I achieve this?

concatenation with the string looks correct to me.

Are you sure your DB record is correctly updated? If you pass the correct $id to this method it should exists in the redirection header.

I suggest you to reproduce the eventuality where you don't have a value for $id in the new location and do some debug, for example:

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

Check if the printed $id values are the same, are the expected and if the record was really updated. You should not see the string 'result not valid' as the code exit before.

This is not best practice of testing but should help you understand what is happening.

Cheers

PS. When you say 'All I get in the browser is ' do you mean you've been redirected to that page, right?

The final solution was to define $id once again in the method like so:

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

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