来自 php 数组的简单更新 MySQl 表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7884284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:34:01  来源:igfitidea点击:

Simple UPDATE MySQl table from php array

phpmysqlarrays

提问by RipzCurlz

I am trying to put together a function that does the following:

我正在尝试组合一个执行以下操作的函数:

  1. retrieve a JSON encoded string from a form
  2. decode the string to a php array
  3. loop through the generated php array to get the values for each part of the array so that I can update a MySql table
  1. 从表单中检索 JSON 编码的字符串
  2. 将字符串解码为 php 数组
  3. 循环遍历生成的 php 数组以获取数组每个部分的值,以便我可以更新 MySql 表

Here is my function code so far:

到目前为止,这是我的函数代码:

public function saveTestimonials() {


    $existing_testimonials_update = $this->post('data');

    $update_array = json_decode($existing_testimonials_update);

    foreach ($update_array as $key => $testimonials) {
         foreach($testimonials as $key => $value) {
            //echo "$key = $value\n";

        }
    }

    $db = Loader::db();
    $sql = "UPDATE testimonials SET name=var, content=var WHERE id=var";
    $db->query($sql);

    $this->redirect('/dashboard/testimonials/');

}

Here is the array stored in the $update_array variable:

这是存储在 $update_array 变量中的数组:

Array
(
[0] => stdClass Object
    (
        [id] => 1
        [name] => Mr. John Doe, Manager, ABC Ltd
        [content] => my content 1.
    )

[1] => stdClass Object
    (
        [id] => 2
        [name] => Mr. Joe Smith, Manager, ABC Industries
        [content] => my content 2.
    )

[2] => stdClass Object
    (
        [id] => 3
        [name] => Mr. Mike Smith, Manager, ABC Industries
        [content] => my content 3.
    )

[3] => stdClass Object
    (
        [id] => 4
        [name] => Ms. Jane Doe, Manager, ABCD Ltd
        [content] => my content 4.
    )

)

I have got steps 1 and 2 working fine, however I am stuck on step 3.

我的第 1 步和第 2 步工作正常,但是我坚持第 3 步。

I still learning PHP and struggle with syntax at times. I have tried to work this one out on my own and have spent several hours on it, but just can't seem to figure this one out.

我仍在学习 PHP 并且有时会在语法上挣扎。我试图自己解决这个问题并花了几个小时,但似乎无法解决这个问题。

Any assistance is very much appreciated.

非常感谢任何帮助。

回答by Marc B

foreach ($update_array as $key => $testimonials) {
    $name = mysql_real_escape_string($testimonials->name);
    $content = mysql_real_escape_string($testimonials->content);
    $id = intval($testimonials->id);

    $sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id=$id";
    $result = mysql_query($sql);
    if ($result === FALSE) {
        die(mysql_error());
    }
}

回答by Alex

I'm using something like this. Might be a help to you!

我正在使用这样的东西。可能对你有帮助!

function updateDbRecord($db, $table, $carry, $carryUrl) {   
    mysql_select_db($db) or die("Could not select database. " . mysql_error());
    $resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
    $fieldnames=array();
      if (mysql_num_rows($resultInsert) > 0) {
        while ($row = mysql_fetch_array($resultInsert)) {
            $fieldnames[] = $row['Field'];
            $array = array_intersect_key( $_POST, array_flip($fieldnames) );
        }
      }
      foreach ($array as $key => $value) {
        $value = mysql_real_escape_string($value);
        $value = "'$value'";
        $updates[] = "$key = $value";
      }
      $implodeArray = implode(', ', $updates);
      $sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $implodeArray, $_POST['id']);
      mysql_query($sql);
      if ($carry == 'yes') {
        redirect($carryUrl.'?id='.$_REQUEST['id'].'&'.$table);
      } else { echo "Done!"; }
}

回答by Jeff Day

These are objects you're dealing with inside of the update_array, so you should be able to access them like this:

这些是您在 update_array 内部处理的对象,因此您应该能够像这样访问它们:

$update_array = json_decode($existing_testimonials_update);

foreach ($update_array as $key => $testimonials) {
     $testimonials = (array) $testimonials;
     foreach($testimonials as $key => $value) {
        //echo "$key = $value\n";

    }
}

Or, more simply, you can use the arrow operator ($testimonials->name) to access the variables.

或者,更简单地说,您可以使用箭头运算符 ($testimonials->name) 来访问变量。

回答by Abenil

You are getting an object from json_decode(). If you pass true as second argument to json_decode() you get an associative array.

您正在从 json_decode() 获取一个对象。如果将 true 作为第二个参数传递给 json_decode() ,则会得到一个关联数组。

http://php.net/manual/de/function.json-decode.php

http://php.net/manual/de/function.json-decode.php

回答by bumperbox

try something like this

尝试这样的事情

 $db = Loader::db();

foreach ($update_array as $key => $testimonials) {
         foreach($testimonials as $testimonial) {

             // escape data to avoid sql injection
             $id = mysql_escape_string($testimonial->id);
             $name = mysql_escape_string($testimonial->name);
             $content = mysql_escape_string($testimonial->content);

             $sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id='$id'";
             $db->query($sql);

             // TODO check for database error here

        }
    }

回答by Metin Erbek

function update($table_name, $myarray, $my_wheres) {
    $sql = "Update`".$table_name.
    "` SET ";
    $i = 0;
    foreach($myarray as $key => $value) {
        $sql.= $key." = '".$value."'";
        if ($i < count($myarray) - 1) {
            $sql.= " , ";
        }
        $i++;
    }
    if (count($my_wheres) > 0) {
        $sql.= " WHERE ";
        $i = 0;
        foreach($my_wheres as $key => $value) {
            $sql.= $key.
            " = ".$value;
            if ($i < count($my_wheres) - 1) {
                $sql.= " AND ";
            }
            $i++;
        }
    }

    return mysqli_query($sql);
}

Hope, this code can help you. Not try one by one update i think. Think performance.

希望,此代码可以帮助您。我认为不要尝试一一更新。想想性能。