Codeigniter foreach循环没有正确读取数据库

时间:2014-06-26 14:42:07

标签: php mysql codeigniter

我有一个简单的嵌套foreach循环,它应该从数据库读取起始值currentNumber,从另一个表$co['count']中取另一个值,将两者加在一起newCount并更新初始号码。

问题是在初始查询数据库时,循环将值设置为某个随机(但一致)值。奇怪的是,如果我在第二次运行时运行控制器方法两次,它的行为与预期的一样。当我正确输入authorlist数据时,好像我没有正确设置默认值零。如果我创建authorlist,然后通过phpmyadmin手动编辑count值为零,一切正常????

这是我的控制器:

foreach($authors as $key => $list){
    foreach($coauthors as $key => $co){
        $searchword = $list['author'];
    $id = $list['id'];
        $matches = array_filter($co, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
    if($matches){
            $currentNumber = $this->csv_model->get_number($id);

        $newCount = $currentNumber + $co['count'];
            $data = array(
                'count'=> $newCount,
            );
            $this->csv_model->update_number($list['id'], $data);
        }
    }
}

没有观点。这是模型:

function get_number($id) {     
    $this->db->select('count');
    $this->db->where('id', $id);

    $query = $this->db->get('authorlist');
    $ret = $query->row();
    return $ret->count;
}
function update_number($id, $data)
{
    $this->db->where('id', $id);
    $this->db->update('authorlist', $data);
}

并且因为我认为这可能是db表的一个问题,这里是表的sql,只有4个条目

-- phpMyAdmin SQL Dump
-- version 3.5.8.1deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 26, 2014 at 02:30 PM
-- Server version: 5.5.32-0ubuntu0.13.04.1
-- PHP Version: 5.4.9-4ubuntu2.3

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

-- Database: `authors`

-- Table structure for table `authorlist`

CREATE TABLE IF NOT EXISTS `authorlist` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `author` varchar(255) NOT NULL,
  `count` int(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

-- Dumping data for table `authorlist`


INSERT INTO `authorlist` (`id`, `author`, `count`) VALUES
(1, 'adam', 0),
(2, 'adams', 0),
(3, 'ahmed, m', 0),
(4, 'staz', 0);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

修改

在循环的第一次运行中生成的看似随机数不是随机的。事实证明,这个数字是循环运行的总和。有点难以描述,但我已经粘贴了一些我从其中一位作者的内循环打印出的代码。您可以看到起始编号与所有添加的总和相同,即正好是最终值的一半。这是怎么回事?

current 1255 //this should read zero form the initial construction of the table
to add 653
new sum 1908
current 1908
to add 302
new sum 2210
current 2210
to add 300
new sum 2510

0 个答案:

没有答案