4

Hi so I have an insert statement which works well, but need to create a separate update function which uses array keys and array values, which would be quite like the insert function but updates.

I have this for my insert

$sql = "INSERT INTO $tablename (".implode(",", array_keys($DATA).")" . " DATA ('".implode("','",array_values($DATA))."')";
connect()->query($sql); 

This is what I have for my update so far but am stuck with it,

<?php
    function updatethis (array $id, array $values, $tablename)
    {
        $sql = "UPDATE $tablename SET (".implode(",", array_keys($DATA)).")" . " DATA ('".implode("','",array_values($DATA))."')";
        dbconnect()->query($sql); 
    } 
?>

Therefore I would like help on the update feature please .

So I am getting an error with the UPDATE syntax

This is the part i am struggling with, i cna give further explanation, but i must have put in the wrong syntax to update the database after i click edit on the index page it calls the function just the syntax is incorrect.

also its php to mySQL

index page for PHP updatee fucntion

 {
     $values = array();
     $idValues = array($idColumn => $id);
     foreach($_POST as $key => $value)
     {
         if(!empty($value) && ($value != "Submit"))
         {
             $values[$key] = $value;
         }
     } 
     $result = update($idValues, $values, $tableName);
 }

Edit: Error I am getting edit has not been successfull from below

  if(isset($_POST['Submit']))
                {
                    if($result>0)
                    {
                        echo 'Edit has been successful.  Return to index page';
                    }
                    else
                    {
                        echo 'Edit has not been successful.';
                    }
                }

My code

function updateAll(array $id, array $values, $tablename)
{
    $sIDColumn  = key($id);
    $sIDValue   = current($id);
    $arrayValues = $values;
    array_walk($values, function(&$value, $key){
        $value = "{$key} = '{$value}'";
    });
    $sUpdate = implode(", ", array_values($values));
    $sql        = "UPDATE {$tablename} SET {$sUpdate} WHERE {$sIDColumn} = '{$sIDValue}'";


    connect()->query($sql);
}

My aim: takes the input of the unique identifier of the row to be edited as an array of 1 then the value plus the name of the column representing the primary key, an array containing the values indexed by the column names as well as a string representing the table name useing array_keys and array_vaules like th insert but to update

3
  • 1
    What do you mean by "but am stuck with it"? Do you get an error(if so, show us the error) or do you get no error? What have you tried so far to solve this problem(this is so we can rule out some possibilities)? Edit the question with these question answered so we can help you better. Commented Dec 8, 2015 at 9:19
  • 1
    echo $sql please and u need where clause Commented Dec 8, 2015 at 9:26
  • @SugumarVenkatesan I just noticed that you beat me to it :P Commented Dec 8, 2015 at 9:28

3 Answers 3

8

You cannot UPDATE in the same way of INSERT. It should be like this :

$valueSets = array();
foreach($values as $key => $value) {
   $valueSets[] = $key . " = '" . $value . "'";
}

$conditionSets = array();
foreach($id as $key => $value) {
   $conditionSets[] = $key . " = '" . $value . "'";
}

$sql = "UPDATE $tablename SET ". join(",",$valueSets) . " WHERE " . join(" AND ", $conditionSets);

See details here http://dev.mysql.com/doc/refman/5.7/en/update.html

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

20 Comments

Okay thanks, I have to use the function updatethis(array $id, array $values, $tablename) i will have a look at that
that kind of works but updates all of the fields not just 1
You want to update only one field? Which one field? How do you tell your function about that field?
Hi that's what i am struggling with, i have an idex page where i pefrom the data input, but with the above code it updates every row not just the single row
You need to add the where conditions in the last line of my code block
|
1

I believe the pattern you are using is incorrect?

UPDATE table SET (rows) DATA ('values');

I think updates look more like this:

UPDATE table SET row1 = 'value1', row2 = 'value2';

In which case, this may be closer to what you are looking for.

function updatethis(array $id, array $values, $tablename)
{
    $sIDColumn  = key($id);
    $sIDValue   = current($id);
    $arrayValues = $values;
    array_walk($values, function(&$value, $key){
        $value = "{$key} = '{$value}'";
    });
    $sUpdate = implode(", ", array_values($values));
    $sql        = "UPDATE {$tablename} SET {$sUpdate} WHERE {$sIDColumn} = '{$sIDValue}'";
    dbconnect()->query($sql);
}

Using it, I get this query:

$testArray = array(
    "id" => 19,
    "username" => "test"
);
updatethis(array("id" => 9), $testArray, "users");

UPDATE users SET id = '19', username = 'test' WHERE id = '9'

I hope this at least helps but when it comes to databases, I only know MySQL and it is possible you are using another language.

2 Comments

Thanks I think this may be nearly there i just get an update function failed though i have added my index page to the top of the page for you to look into
I have updated my the function a little. If this still does not work, you will need to show us the exact error. If you do not know how to get that error then maybe tell us what database class you are using.
0

I think you can try something like this : $champs : Array of fields to update $valeurs : Array of value to update fields $conditions : Array of conditions

 protected function modify($table,$champs,$valeurs,$conditions){
            $Requete = "UPDATE ".$table." SET ";
            $nbChamps = count($champs);
            $nbValeurs = count($valeurs);
            if($nbChamps == $nbValeurs){
                for($i = 0; $i < $nbChamps ; $i++){
                    if($i < ($nbChamps - 1)){
                        if(is_numeric($valeurs[$i]))
                            $Requete = $Requete.$champs[$i]." = ".$valeurs[$i].",";
                        else
                            $Requete = $Requete.$champs[$i]." = '".$valeurs[$i]."',";
                    }
                    else
                        if(is_numeric($valeurs[$i]))
                            $Requete = $Requete.$champs[$i]." = ".$valeurs[$i]." ";
                        else
                            $Requete = $Requete.$champs[$i]." = '".$valeurs[$i]."' ";
                    }
                    $Requete = $Requete.$this->genereConditions($conditions);
                    $this->db->query($Requete);
                }
                else
                    throw new Exception("Le nombre de champs n'est pas identique au nombre de valeurs", 1); 
            }

    private function genereConditions($conditions){
            $condition = "WHERE ";
            for($i = 0 ; $i < count($conditions); $i++){
                if($i < (count($conditions)) - 1)
                    $condition = $condition.$conditions[$i]." AND ";
                else
                    $condition = $condition.$conditions[$i];
            }
            return $condition;
        }

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.