I want to send my input data to an SQL Query in my CodeIgniter application in the following way:
$sdata['department'] = $this->input->post('department'); //Data as text input
$sql = "SELECT MAX(roll) FROM student WHERE department = ".this->db->escape_str($sdata['department']);
The above code is inside my controller.
And I keep getting the following error:
Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR)
Most likely, this is a syntax error, but I just can't figure out which part of my code is responsible.
I've also gone through the Queries section of the user guide of CodeIgniter, but it wasn't explained clearly there.
Can anyone please tell me where my mistake is, and what is the correct syntax for what I'm trying to do?
My controller -
<?php
if ( ! defined('BASEPATH')){ exit('No direct script access allowed');}
class Student extends CI_Controller
{
function __construct()
{
parent::__construct();
#$this->load->helper('url');
$default_roll = '20141000';
$this->load->model('student_model');
$this->load->helper('string');
}
//Show all Students
public function index()
{
$data['student_list'] = $this->student_model->get_all_students();
$this->load->view('student_view', $data);
}
//Insert a student
public function insert_student_db()
{
$sdata['name'] = $this->input->post('name');
$sdata['department'] = $this->input->post('department');
$sql = "SELECT MAX(roll) FROM student WHERE department = ".this->db->escape_str($sdata['department']);
$query = $this->db->query($sql);
$rolltext = substr($query, 9);
$year = substr($query, 3, -3);
if($rolltext == NULL && $year == NULL)
{
$rolltext = str_pad(1,3,'0',STR_PAD_LEFT);
$year = '2014';
}
else
{
$rolltext++;
$rolltext = str_pad($rolltext,3,'0',STR_PAD_LEFT);
if($rolltext == '100')
{
$rolltext = str_pad(1,3,'0',STR_PAD_LEFT);
$year++;
}
}
$sdata['roll'] = $sdata['department'].$year.$rolltext;
$sdata['email'] = $this->input->post('email');
$sdata['mobile'] = $this->input->post('mobile');
$res = $this->student_model->insert_student($sdata);
if($res)
{
header('location:'.base_url()."index.php/student/".$this->index());
}
}
}
?>
[Courtesy: user Ismael Miguel]
Problem was with this line inside my controller, student.php
:
$sql = "SELECT MAX(roll) FROM student WHERE department = ".this->db->escape_str($sdata['department']);
A very silly mistake, in a very basic thing. All variables in PHP must be preceded with a '$
' sign. I just missed that.
So, after correcting that bit, it looks like this:
$sql = "SELECT MAX(roll) FROM student WHERE department = ".$this->db->escape_str($sdata['department']);
And it's working fine now.
PHP didn't recognise this
, without the '$
' sign. That's why it threw the parse error.