mysql更新的动态数组创建-php [英] Dynamic array creation for mysql update - php

查看:70
本文介绍了mysql更新的动态数组创建-php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为updateDbRecord创建类​​似于insertIntoDb的动态查询?鉴于我想使用 update_id = $ _ GET ['id']; 更新特定的ID,因为我的ID存储在URL中,即somepage.php?id = 12

How would I create an dynamic query like that in insertIntoDb for updateDbRecord? Given that I want to update a specific ID using update_id=$_GET['id']; since my ID is stored in my URL i.e. 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
}


推荐答案

沿着这些行可以创建更新语句。

something along these lines to create the update statement.

// 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);

这篇关于mysql更新的动态数组创建-php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆