【问题标题】:Trying to paste values of array into variable试图将数组的值粘贴到变量中
【发布时间】:2015-03-12 15:45:30
【问题描述】:

目前我被困在如何将数组的值添加到变量中,以便在查询中输出。

这是我存储的数据:

try {

    $link->create(array(

        'uid'       =>  $user->data()->id,
        'name'      =>  Input::get('name'),
        'hyperlink' =>  Input::get('hyperlink')

    ));

} catch (Exception $e) {

    die($e->getMessage());

}

通过这个函数,我试图将该数组中的值放入 1 个变量中:

    public function insert($table, $fields = array()) {

        if (count($fields)) {

            $keys = array_keys($fields);

            $x = 1;

            foreach ($fields as $field => $values) {

                if ($x < count($fields)) {

                    $values .= ', ';

                }

                $x++;

            }

            $sql = "INSERT INTO `$table` (`" . implode('`, `', $keys) . "`) VALUES ({$values})";

            die($sql);

            if (!$this->query($sql, $fields)->error()) {

                return true;

            }

        }

        return false;

    }

但是当我回显 sql 时,它只给出数组的最后一个值。我究竟做错了什么?

谢谢!

【问题讨论】:

  • $values = $values;覆盖东西是吗?
  • 已编辑:用于测试目的..但它仍然不起作用。
  • 使用你在循环中使用的变量有点讨厌,对吧?!如中, $values 在循环内重新分配..
  • SQL 注入是一种威胁吗?
  • 它是否容易受到 sql-injection 的影响?

标签: php sql arrays oop


【解决方案1】:

你可以尝试这样的事情,减少循环,实际上可以合并成一行...编辑:忽略引用值...适当更新

if (count($fields)) {

  $field_list = implode(", ", array_keys($fields));
  $value_list = implode("', '", array_values($fields));

  $sql =  "insert into `$table` ($field_list) values('$value_list')";

}

【讨论】:

  • 谢谢,非常简单的解决方案!
【解决方案2】:

这是另一个选项,我无法弄清楚您的脚本出了什么问题,它看起来正确但无法找到问题所在。动态插入 db 值时,我总是使用此类方法。

   function insertRecord ($fieldarray)
   {
      $this->errors = array();


      //Connect to the DB for table insert
      global $dbconnect, $query;
      $dbconnect = db_connect($this->dbname) or trigger_error("SQL", E_USER_ERROR);

     //Now, using the contents of $fieldlist which was set in the class constructor we can edit the input array to filter out any items which do not belong in this database table. This removes the SUBMIT button, for example.

      $fieldlist = $this->fieldlist;
      foreach ($fieldarray as $field => $fieldvalue) {
         if (!in_array($field, $fieldlist)) {
            unset ($fieldarray[$field]);
         } // if
      } // foreach

      //Now construct the query string to insert a new 
      //record into the database:

      $query = "INSERT INTO $this->tablename SET ";
      foreach ($fieldarray as $item => $value) {
         $query .= "$item='$value', ";
      } // foreach

      //You may have noticed that each 'name=value' pair was appended 
      //to the query string with a trailing comma as a separator, 
      //so we   must remove the final comma like so:

      $query = rtrim($query, ', ');

      //Now execute the query. Notice here that instead of the default 
      //error checking I look specifically for a 'duplicate key' error  
      //and return a simple error message rather terminating the whole   
      //script with a fatal error.

      $result = @mysql_query($query, $dbconnect);
      if (mysql_errno() <> 0) {
         if (mysql_errno() == 1062) {
            $this->errors[] = "A record already exists with this ID.";
         } else {
            trigger_error("SQL", E_USER_ERROR);
         } // if
      } // if

      //Last act is to return control to the calling script.

      return;

   } // insertRecord

恕我直言,上面的函数对插入语句和错误处理进行了必要的检查,我发现这很有用。

【讨论】:

    【解决方案3】:

    我认为你可以像使用函数 array_keys 一样使用函数 array_values 来更容易地做到这一点。

    public function insert($table, $fields = array()) {
    
            if (count($fields)) {
    
                $keys = array_keys($fields);
                $values = array_values($fields); // why another logic for the same result.. ?
    
                $sql = "INSERT INTO `$table` (`" . implode('`, `', $keys) . "`) VALUES (`" . implode('`, `', $values) . "`)";
    
                die($sql);
    
                if (!$this->query($sql, $fields)->error()) {
    
                    return true;
    
                }
    
            }
    
            return false;
    
        }
    

    【讨论】:

      【解决方案4】:

      问题是 $values = $values 在 foreach 循环内。

      foreach ($fields as $field => $values) {
          // The problem is right here, each time this loops, you are
          // setting the entire $values variable to be just the current iteration
          // of the $fields variable.
      
          $values = $values;
      
          if ($x < count($fields)) {
      
              $values .= ', ';
      
          }
      
          $x++;
      
      }
      

      试试这个:

      $sql_values = '';
      foreach ($fields as $field => $values) {
      
          if ($x < count($fields)) {
      
              $sql_values.= $values.', ';
      
          }
      
          $x++;
      
      }
      
      $sql = "INSERT INTO `$table` (`" . implode('`, `', $keys) . "`) VALUES ($sql_values)";
      

      【讨论】:

      • 您是否忘记将$values 附加到$sql_values
      • @bloodyKnuckles - 好电话。我完全忘记了。无论如何,这并不重要,因为同时提交了几个正确的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多