Welcome Guest, Not a member yet? Register   Sign In
Simple MySQL Query Not Working | Brain Fart?
#1

[eluser]mfroseth[/eluser]
Alright, Simple form that submits and pulls data from a database. The database table is "5000" and I'm trying to grab everything in that table where the age input matches the age in the database.

I have this in my model "results.php"

Code:
<?php
function getGraded($amount,$age) {

  $query = $this->db->query("SELECT * FROM $amount WHERE age = $age");
  return $query->result_array();

}
?>

and this is in my controller " home.php"

Code:
<?php
public function results()
{

  if($this->session->userdata('plan_type') == "default" && $this->session->userdata('agentID') == TRUE) {
  $age = $this->session->userdata('age');
  $amount = $this->session->userdata('amount');
  
  
  $this->load->model('results');  
  
  $data['results'] = $this->results->getGraded($amount, $age);  
  
  $this->load->view('graded/header');
  $this->load->view('graded/results',$data);
  $this->load->view('includes/footer');
  
  }
  
  else {
  
  redirect('home', 'refresh');  
  
  }
  
}
?>

When I submit the form I am receiving the following error:

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '5000 WHERE age = 41' at line 1

SELECT * FROM 5000 WHERE age = 41

Filename: /var/www/vhosts/ratecal.info/nuco2/models/results.php

Line Number: 6


What the heck am I doing wrong? I'm afraid this is just one big brain fart I am having but really can't wrap my head around what I am missing here.

Any help would be greatly appreciated.
#2

[eluser]vitoco[/eluser]
You are using $amount as table name ( 5000 in your example ) because you're putting it after "FROM" in the sql statement

Code:
SELECT * FROM $amount WHERE age = $age

I think that you want to do is something like this

Code:
SELECT
    *
FROM
    __TABLE___
WHERE
    __FIELD__ = $amount AND
    age = $age

Saludos
#3

[eluser]pickupman[/eluser]
I would suggest using the syntax:
Code:
function getGraded($amount,$age) {

  $query = $this->db->get_where($amount, array('age' => $age));  
  return $query->result_array();

This syntax is more secure as the values will be escaped. Likely your error maybe from the age not being inside single quotes possibly, or not having back ticks on the table name is it is numeric. This code should solve both issues.




Theme © iAndrew 2016 - Forum software by © MyBB