Codeigniter查询错误:未定义偏移量1

时间:2019-06-26 10:40:28

标签: php codeigniter-3

我只是在下面提到的模型代码中运行查询:

...
    /**
     * @ORM\Column(type="simple_array", nullable=true)
     */
    private $testArray = [];

    public function getTestArray(): ?array
    {
        return $this->testArray;
    }

    public function setTestArray(?array $testArray): self
    {
        $this->testArray = $testArray;

        return $this;
    }
...

假设 /** * @Route("/{id}/edit", name="test_entity_edit", methods={"GET","POST","PATCH"}) */ public function edit(Request $request, TestEntity $testEntity): Response { $form = $this->createForm(TestEntityType::class, $testEntity); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('test_entity_index', [ 'id' => $testEntity->getId(), ]); } return $this->render('test_entity/edit.html.twig', [ 'test_entity' => $testEntity, 'form' => $form->createView(), ]); } 和我使用public function friend($name) { $arr = explode(" ",$name); $fname = $arr[0]; $lname = $arr[1]; $this->db->select('*'); $this->db->from('client'); $where = "fname='".$fname."' and lname='".$lname."'"; $this->db->where($where); $sql = $this->db->get(); if($sql->num_rows() > 0) { $result = $sql->result_array(); return $result; } else { $this->session->set_userdata('err','<p style="color:red;">No information found!</p>'); } } 函数来获取$name='Jhon Carter'explode。我的表中有两列,即firstname。我想根据这些列获取数据,那么我该怎么做呢?请帮助我。

谢谢

1 个答案:

答案 0 :(得分:0)

您需要使用isset()

$arr = explode(" ",$name);
$fname = (isset($arr[0]) ? $arr[0] :'');
$lname = (isset($arr[1]) ? $arr[1] :'');

并防止SQL注入代码:

public function friend($name)
{
    $arr = explode(" ",$name);
    $fname = (isset($arr[0]) ? $arr[0] :'');
    $lname = (isset($arr[1]) ? $arr[1] :'');

    if(!empty($fname) && !empty($lname)){

        $sql = "SELECT * FROM client WHERE fname = ? AND lname= ?"; 
        $this->db->query($sql, array($fname, $lname));

    }else if(!empty($fname) && empty($lname)){

        $sql = "SELECT * FROM client WHERE fname = ?"; 
        $this->db->query($sql, array($fname));

    }else if(empty($fname) && !empty($lname)){

        $sql = "SELECT * FROM client WHERE lname= ?"; 
        $this->db->query($sql, array($lname));

    }
    $sql = $this->db->get($query);

    if($sql->num_rows() > 0)
    {
        $result = $sql->result_array();
        return $result;
    }
    else
    {
        $this->session->set_userdata('err','<p style="color:red;">No information found!</p>');
    }
}