为mysql更新创建动态数组 - php

时间:2012-06-30 20:51:22

标签: php mysql arrays

如何在insertDntoDb中为updateDbRecord创建一个动态查询?鉴于我想使用update_id=$_GET['id'];更新特定ID,因为我的ID存储在我的网址中,即somepage.php?id = 12

function insertIntoDb($db, $table, $carry, $carryUrl) {
    mysql_select_db($db) or die("Could not select database. " . mysql_error());
    $resultInsert = mysql_query("SHOW COLUMNS FROM " . $table);
    $fieldnames=array();
      if (mysql_num_rows($resultInsert) > 0) {
        while ($row = mysql_fetch_array($resultInsert)) {
            $fieldnames[] = $row['Field'];
            $values = array_intersect_key( $_POST, array_flip($fieldnames) );
        }
      }
      $sql = sprintf('INSERT INTO %s (%s) VALUES ("%s")', $table, 
      implode(', ', array_map('mysql_escape_string', array_keys($values))), implode('", "',array_map('mysql_escape_string', $values))); 
      mysql_query($sql);
      /* if ($carry == 'yes') {
        redirect($carryUrl.'?id='.$_REQUEST['id']);
      }
      else { echo '<div class="success">Data was entered into the database successfully!<br><a href="view.php?type=recent">View listing?</a></div>'; } */
}

function updateDbRecord($db, $table) {
    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'];
            $values = array_intersect_key( $_POST, array_flip($fieldnames) );
        }
      }
      #update syntax
}

1 个答案:

答案 0 :(得分:1)

沿着these行创建更新语句。

// todo sanitise with mysql_escape_string()
foreach($arr as $key => $v) {
    $val = is_numeric($v) ? $v : "'" . $v . "'";

    $set .= sprintf("%s=%s%s", $key, $val, ($v == end($arr) ? "" : ", "));
}

$sql = sprintf("UPDATE %s SET %s", $table, $set);