1

I am doing work with php object oriented and mysqli. i have class name Database.php inside this class i have defined a function name update. i did some thing wrong i think that's why it doesn't work fine. when i use to run click at update then data retrieves in Form but when i try to save the updated form it always updated only first column of my database. function code is given below:

    public function update($tablename, $value, $where){
    $Update = " UPDATE ".$tablename." SET ";
    $array_keys = array_keys($value);
    $array_values= array_values($value);
    $count = count($array_keys);
    for($i=0; $i< $count; $i++){
        $value[$i] = " = '".$value[$array_keys[$i]]."' ";
    }
       //$value = implode(" ",$value);
    print_r($value);
  $Update .= " ".$value." WHERE ".$where;

    $Utest = $this->DbCon->query($Update);
    if($Utest){
        return true;
    }else{
        return false;
    }

here is php code that i have tried before

if(isset($_POST['update'])){
    $id1 =  $_POST['id'];
    $name =  $_POST['name'];
    $city = $_POST['city'];
    $success=$DbQuery->update("record", array(" name " => $name ,"city" => $city)," id =".$id1);
    if($success){
       header("LOCATION:index.php");
    }else{
        echo "try again ";
    }

}

do you have any good suggestion for update function how ic an improve this function. actually i am new in php object oriented so suggest me easy method to this. Thanks

1 Answer 1

1

The problem is that you're trying to convert the $value array to a string in $Update .= " ".$value." WHERE ".$where;. You can't do that. You have to construct the query in the for loop above it instead of populating the $value array. Either way you shouldn't be building the query by hand. You REALLY should use PDO::prepare() or $mysqli::prepare() to prevent vulnerabilities. Yes, that might feel like an overkill if you're just learning, but you should start forming good habits from the very beginning.

Also, fix your formatting. Your code is really hard to read. I recommend reading through the PSR standard (or any widespread PHP standard) and adapting it in your code. Again, might feel like overkill, but it's a good habit to pick up early.

Here's an adapted version of your code for you to easily play with. You can see the problem if you run php index.php in the CLI window at the bottom.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.