我有这个功能:
public function populateAtribut()
{
$this->db->query("TRUNCATE atribut");
$this->db->query("insert into `atribut` values
('', 'Total', 'Total')
");
$this->insertAtribut('pertanyaan_1');
$this->insertAtribut('pertanyaan_2');
$this->insertAtribut('pertanyaan_3');
$this->insertAtribut('pertanyaan_4');
$this->insertAtribut('pertanyaan_5');
$this->insertAtribut('pertanyaan_6');
$this->insertAtribut('pertanyaan_7');
$this->insertAtribut('pertanyaan_8');
$this->insertAtribut('pertanyaan_9');
$this->insertAtribut('pertanyaan_10');
$this->insertAtribut('pertanyaan_11');
$this->insertAtribut('pertanyaan_12');
$this->insertAtribut('pertanyaan_13');
$this->insertAtribut('pertanyaan_14');
$this->insertAtribut('pertanyaan_15');
$this->insertAtribut('pertanyaan_16');
$this->insertAtribut('pertanyaan_17');
$this->insertAtribut('pertanyaan_18');
$this->insertAtribut('pertanyaan_19');
$this->insertAtribut('pertanyaan_20');
}
我得到了这样的函数insertAtribut
:
public function insertAtribut($atribut) {
$sqlAtribut = $this->db->query("SELECT distinct `$atribut` FROM data_kepribadian ORDER by `$atribut`");
while ($rowAtribut = $sqlAtribut->result_array()) {!
$this->db->query("insert into `atribut` values
('', '$atribut', '$rowAtribut[$atribut]')");
}
}
但我收到了错误:
消息:未定义的索引:pertanyaan_1
并且程序不停地向数据库插入数据。
我该如何解决这个问题?
答案 0 :(得分:0)
while循环是有条件的:
while (condition is true) {
code to be executed;
}
你没有条件所以它只是连续循环。你需要一个foreach循环:
public function insertAtribut($atribut) {
$sqlAtribut = $this->db->query("SELECT distinct `$atribut` FROM data_kepribadian ORDER by `$atribut`");
if ($sqlAtribut->num_rows() > 0) {
$rowAtribut = $sqlAtribut->result_array();
foreach ($rowAtribut as $row) {
$this->db->query("insert into `atribut` values ('', '$atribut', '$row[$atribut]')");
}
}
}
检查num_rows
也有帮助,否则如果$sqlAtribut
没有结果,则foreach循环将失败。
您还可以清理查询并使用查询构建器(但在测试上面的代码后测试它以查看逻辑是否有效):
public function insertAtribut($atribut) {
$q = $this->db->distinct()->select($atribut)->get('data_kepribadian');
if ($q->num_rows() > 0) {
$rows = $q->result_array();
foreach ($rows as $row) {
$this->db->insert('atribut', array($atribut => $row[$atribut]));
}
}
}