Why is this MySQL INSERT not working in CI? - php

For some reason this SQL statement is not working. Can anyone tell me why? (This is a Codeigniter site, if that matters)
Here is my Model (where my error is pointing me to)
public function edit_profile($ID, $field, $new_info)
{
$sql = "UPDATE users SET ?=? WHERE id=?";
$query = $this->db->query($sql, array($field, $new_info, $ID)); // <<<< LINE 42
return $query;
}
And this is the error I'm getting
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 ''first_name'='oooo' WHERE id='151'' at line 1
UPDATE users SET 'first_name'='oooo' WHERE id='151'
Filename: /Applications/MAMP/htdocs/MY_SITE/models/member_model.php
Line Number: 42
My table is called 'users', and I have a 'first_name' and 'id' column.
Ideas?
EDIT
Just because it seems to come up a bit I want to clarify that the variables I am passing in here have NO QUOTES OR BACKTICKS. They are being added somewhere (and it seems like the ->query method, but I cant imagine that's true? .. dunno though, cause it's my first CI project)
Here is the controller that is passing to the model...
public function profileEdit()
{
$ID = $this->the_user->id;
$field = $this->input->post('edit_field')
$field = strstr($field,'_edit', true);
$new_info = $this->input->post('new_info');
$this->load->model('Member_model');
if( $this->Member_model->edit_profile( $ID, $field, $new_info )){
echo 'success';
}
else
{
echo 'error';
}
}

i suggest use like this :
public function edit_profile($ID, $field, $new_info)
{
$sql = "UPDATE users SET $field =? WHERE id=?"; # UPDATED (remove $this->db->escape())
$query = $this->db->query($sql, array($new_info, $ID)); // <<<< LINE 42
return $query;
}
if $field is not secured you can use escape functions .
EDIT :
$this->db->escape() will add quotes around variable so you will get an error again .

Related

why it's generating query without "from tablename" in codeigntier

Here is my code.
public function get_records($event_id = null)
{
$this->db->select('a.*');
$this->db->from('attendee a');
$this->db->join('event e','e.event_id = a.attendee_event_id','left');
$this->db->join('users u','u.id = e.event_user_id','left');
if($event_id != null)
$this->db->where('a.attendee_event_id',$event_id);
if($this->ion_auth->is_agent())
{
$this->db->where('e.event_user_id', csession('user_id'));
}
else
{
$this->db->group_start();
$this->db->where('e.event_user_id', csession('user_id'));
$this->db->or_where('u.created_by', csession('user_id'));
$this->db->group_end();
}
$query = $this->db->get();
return $query->result();
}
for this code i am getting below result
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 'WHERE ( `e`.`event_user_id` = '93' OR `u`.`created_by` = '93' ) AND `a`.`atte' at line 2
SELECT * WHERE ( `e`.`event_user_id` = '93' OR `u`.`created_by` = '93' ) AND `a`.`attendee_event_id` = '2'
Filename: models/Attendee_model.php
Line Number: 85
Whenever i am passing event_id, it's not working fine.
but when I am not passing event_id, it's working fine.
I don't know what i am doing wrong here.
CI is throwing that error because you are not providing the table name in the "get()" method.
Your code
$query = $this->db->get();
Correct approach
$query = $this->db->get('main_table_name');
For a better understanding of CI Query Builder read here
$this->db->group_start();
$this->db->where('e.event_user_id', csession('user_id'));
$this->db->or_where('u.created_by', csession('user_id'));
$this->db->group_end();
I have removed above code and it started working. btw it was unnecessary code. But I coudn't find the issue with this code though.

Mistake in SQL syntax.. (bindValue?)

I am trying to create an update query and I am looping in some set stuff to a var called $str and I cant seem to get it to work.
if (is_numeric($id)) {
if (!empty($values) && !empty($table_name)) {
$str = '';
$sql = "UPDATE `$table_name` SET :update_values WHERE `$column_name` = :id";
// Its one because we dont use ID like that
$i = 1;
foreach ($values as $key => $value) {
if ($key != $column_name) {
// Exclude the last one from having a comma at the end
if ($i == count($values) - 1) {
$str .= "$key='" . $value . "'";
} else {
$str .= "$key='" . $value . "', ";
$i++;
}
}
}
$query = $this->dbh->prepare($sql);
$query->bindValue('update_values', $str, PDO::PARAM_STR);
$query->bindValue(':id', $id, PDO::PARAM_INT);
$query->execute();
return true;
} else {
return false;
}
} else{
return false;
}
}
Output:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or
access violation: 1064 You have an error in your SQL syntax; check the
manual that corresponds to your MariaDB server version for the right
syntax to use near ''note_name=\'yeet\', note_date=\'2020-02-20\',
note_desc=\'asdasdasdasdadsasdads' at line 1
Am I making any obvious mistakes?
Also for the life of me I don't know what the backslashes in front of the values mean.
In MySQL, identifiers cannot be provided as values.
References to columns must appear in the text of the SQL statement, they cannot be provided through bind parameters. This holds true for table names, column names, function names.
There is no workaround; this is a by-design restriction. There's several reasons for this. One of the most straightforward reasons is understanding how a SQL statement gets prepared, the information that is needed to come up with an execution plan, the tables and columns have to be known at prepare time (for the semantic check and privilege check. The actual values can be deferred to execution time.
Bind placeholders are for providing values, not identifiers.
With the code given, what MySQL is seeing something along the lines of
UPDATE `mytable` SET 'a string value' WHERE `id_col` = 42
And MySQL is balking at the 'a string value'.
We can (and should) use bind parameters for values.
We could dynamically generate SQL text that looks like this:
UPDATE `mytable`
SET `col_one` = :val1
, `col_two` = :val2
WHERE `id_col` = :id
and after the SQL text is prepared into statement, we can bind values:
$sth->bindValue(':val1', $value_one , PDO::PARAM_STR );
$sth->bindValue(':val2', $value_two , PDO::PARAM_STR );
$sth->bindValue(':id' , $id , PDO::PARAM_INT );
and then execute

Error in PDO Update Function

$table="menu_permission";
$field = array('permission'=>$mnuprmis);
$ob->update($table,$field,'staff_id',$stfid);
public function update($table, $fields, $wherefield, $wherefieldvalues)
{
$sql = "update $table set";
foreach ( $fields as $fieldname => $sfieldvalue )
$sql .= $fieldname."= '".$sfieldvalue."',";
$sql = substr($fldquery,0,strlen($fldquery)-1);
$sql .=" where $wherefield = '$wherefieldvalues'";
$q = $this->conn->prepare($sql);
$q->execute();
return true;
}
The error
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]:
Syntax error or access violation: 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 'where staff_id = '1'' at line 1'
in G:\xampp\htdocs\live\Billing Suryas\model\DBConfig.php:171
Stack trace: #0 G:\xampp\htdocs\live\Billing Suryas\model\DBConfig.php(171): PDOStatement->execute()
#1 G:\xampp\htdocs\live\Billing Suryas\pages\permission_pages.php(257): Connection->update('menu_permission', Array, 'staff_id', '1')
#2 {main} thrown in G:\xampp\htdocs\live\Billing Suryas\model\DBConfig.php on line 171
There is no such freaking thing as an $fldquery
$sql = substr($fldquery,0,strlen($fldquery)-1);
^^^ ^^^
Hence your query is only
$sql .=" where $wherefield = '$wherefieldvalues'";
Which results in
where staff_id = '1' // This is your COMPLETE query
That is just one of the problems and it will be fixed when you fix the typo and put in correct variable name there. However a bigger problem will be evident if you read this
How can I prevent SQL injection in PHP?
It might have had to do with the fact that you put single quotes around numeric values, which isn't necessary and might break your query since your DB might regard it as a string instead of a number.
$table="menu_permission";
$field = array('permission'=>$mnuprmis);
$ob->update($table,$field,'staff_id',$stfid);
public function update($table, $fields, $wherefield, $wherefieldvalues)
{
//
// COMPILE QUERY
$sql = "update $table set ";
$col_values_array = array();
foreach ( $fields as $fieldname => $sfieldvalue ) {
$value = is_numeric($sfieldvalue) ? $sfieldvalue : "'$sfieldvalue'";
$col_values_array[] = "$fieldname = $value";
}
$sql .= implode("," , $col_values_array);
$sql .= " where $wherefield = '$wherefieldvalues'";
//
// EXECUTE QUERY
//$q = $this->conn->prepare($sql); --> not required when not using parametrised queries
//$q->execute(); --> not required when not using parametrised queries
$this->conn->query($sql);
return true;
}
Also consider using prepared statements to be safe against SQL injection.

PDO Can't bind two attributes

I'm trying to bind a search term and a limit value to a PDO execute query, but I get error messages no matter which way I do it
public static function searchUsersByName($searchTerm, $results = null) {
//getDBConnection
if($results == null) {
$results = 5;
}
$searchTerm = '%'.$searchTerm.'%';
$query = $database->prepare("SELECT user_id, user_firstname, user_lastname
FROM users_details
WHERE user_firstname LIKE :searchTerm
OR user_lastname LIKE :searchTerm
LIMIT :results");
$query->bindParam(':searchTerm', $searchTerm, PDO::PARAM_STR);
$query->bindParam(':results', $results, PDO::PARAM_INT);
$query->execute();
$search_results = array();
foreach ($query->fetchAll() as $user) {
$search_results[$user->user_id] = new stdClass();
$search_results[$user->user_id]->user_id = $user->user_id;
$search_results[$user->user_id]->user_firstname = $user->user_firstname;
$search_results[$user->user_id]->user_lastname = $user->user_lastname;
}
return $search_results;
}
This is the error I get from this:
PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 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 "5"
It works fine if I take out the bind for LIMIT and just hardcode 5 into the SQL query, but I want to be able to change it if possible
$query->execute(array(':searchTerm' => '%'.$searchTerm.'%', ':results' => $results));
I've tried doing it this way, but of course PDO automatically puts quotes around the values its inserting via this method, and as far as I know you can't put a PDO::PARAM_INT in while using this method.
What am I doing wrong?
Could it be that $results is not an integer? The error seems like your PHP code is posting a string into the query, which would explain the error.
I am guessing this is the issue because of the following piece of code
if($results == null) {
$results = 5;
}
How is $results set in the first place? Via GET/POST? Then it might have been converted to a string.
I've tried your piece of code myself and casting it to an int fixed it for me.
$query->bindParam(':results', intval($results), PDO::PARAM_INT);

(PHP, MySQL) Function only works in 1 of 2 cases, can't find the difference

So I have this function to search entries in a MySQL database:
<?php
private function SearchContributors($search)
{
$search_pieces = explode(' ', $search);
if (count($search_pieces) == 1 )
{
$this->db->like('firstname', $search);
$this->db->or_like('lastname', $search);
$result = $this->db->get(); //the line from the error message below
}
//Other stuff for 2 and more pieces
return $result;
}
?>
I use the function on two occasions.
Case A is a user initiated search and gets the search query from the URL (domain.com/contributors/?x=paul). This works fine.
<?php
if (isset($_GET['x']))
{
$x = $_GET['x'];
$result = $this->SearchContributors($x);
}
?>
Case B is a backup for when a user enters an invalid slug name (domain.com/contributors/paul instead of domain.com/contributors/pauline-surname) and gets the search query directly:
<?php
$this->db->where('slug', $slug);
$result = $this->db->get();
if ($result->num_rows() == 0)
{
$x = str_replace('-', ' ', $slug);
$result = $this->SearchContributors($x);
}
?>
This returned an MySQL syntax 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 'WHERE firstname LIKE '%paul%' OR lastname LIKE '%paul%'' at line 2
SELECT * WHERE firstname LIKE '%paul%' OR lastname LIKE '%paul%'
Filename: /www/htdocs/w00a94ee/c/controllers/contributors.php
Line Number: 23
The function gets the very same string paul in both cases, so why doesn't it work?
//EDIT
function __construct()
{
parent::__construct();
$this->load->database('databasename');
$this->db->from('tablename');
}
You forgot to specify which table you want to select FROM.
$this->db->from('tablename');
EDIT: The problem is you are adding the from in your constructor, then you are calling:
$this->db->where('slug', $slug);
$result = $this->db->get();
before calling SearchContributors. This runs the query and resets the variables.
So, when you call SearchContributors, FROM is no longer set.
You need to put $this->db->from('tablename'); inside SearchContributors and not the constructor. It's usually a good idea to make model functions self-contained, and not require outside functions (such as __construct to call them).
You are missing get('table_name');
if (count($search_pieces) == 1 )
{
$this->db->like('firstname', $search);
$this->db->or_like('lastname', $search);
$result = $this->db->get('Your_tablename'); //-->>Here you can go
}
See the error
select * WHERE......
but where is "from Table WHERE"...??i thinks its the problem my dear
Here also you might change
$this->db->where('slug', $slug);
$result = $this->db->get('My_Table');

Categories