使用多维数组更新MySQL数据库

时间:2014-08-28 06:51:43

标签: php mysql pdo multidimensional-array mysqli

我的要求是加密密码并一次更新MySQL数据库。

这就是我尝试这样做的方式。但没有成功。

这是一个好方法吗?

PHP:

require_once("conn.php"); //PDO
//I've set all passwords in an array
$values = array ( 
    array ( "studentID"  =>  "SCI164" , "pass" =>  "ABCD12"),
    array ( "studentID"  =>  "GEO24" , "pass" =>  "XYZ1"),
    array ( "studentID"  =>  "SCI112" , "pass" =>  "PQR89")
)
foreach ($values as $temp) {
    foreach($temp as $key => $val){
      $stuID = $key"studentID";
      $rawPass = $key"pass";
      $encPass = md5($rawPass);

      $sql_update = "UPDATE students_db
      set pass = $encPass
      where studentID = $stuID Limit 1";
    }
}

4 个答案:

答案 0 :(得分:2)

此查询加密来自students_db的所有传递值。

UPDATE students_db SET pass = MD5(pass)

答案 1 :(得分:0)

我没有涉及任何安全问题,我无法讨论它,但你的代码应该是这样的:

require_once("conn.php"); //PDO
//I've set all passwords in an array
$values = array ( 
    array ( "studentID"  =>  "SCI164" , "pass" =>  "ABCD12"),
    array ( "studentID"  =>  "GEO24" , "pass" =>  "XYZ1"),
    array ( "studentID"  =>  "SCI112" , "pass" =>  "PQR89")
)
foreach ($values as $val) {
      $stuID = $val["studentID"];
      $rawPass = $val["pass"];
      $encPass = md5($rawPass);

      $sql_update = "UPDATE students_db
      set pass = $encPass
      where studentID = $stuID Limit 1";
    }
}

答案 2 :(得分:0)

尝试使用此功能,您必须在single quotes周围提供$encPass,因为传递列将具有varchar数据类型。

foreach($values as $value) {
    $stuID = $value["studentID"];
    $rawPass = $value['pass'];
    $encPass = md5($rawPass);

    $sql_update = "UPDATE students_db set pass = '$encPass' where studentID = $stuID Limit 1";
}

答案 3 :(得分:0)

您无法使用。已编辑 $stuID = $key"studentID";这应该会出错。

foreach($values as $key=>$val) {
      $sql_update = "UPDATE students_db
      set pass ='". md5($val['pass'])."'
      where studentID =". $val['studentID']."Limit 1";
      echo $sql_update;
    }

单引号,因为md5将返回类似xvm456n334的值,即字母数字。