CodeIgniter adds new line characters in my query - php

I wanted to update a column in my database table, the update should just add a numeric value to the existing one.
But this time around, I'm writing the query with CodeIgniter Query builder, the issue is that when I run the script, CodeIgniter throws an Sql Exception below:
"message": "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 '11:01:37\nWHERE `user_id` = '26'' at line 1"
As you can see, it added a new line character to the query string.
The PHP code below is the query in CodeIgniter
$userModel->set('reputations', 'reputations+10', false)
->where('user_id', $user_id)
->update();
One thing I noticed is that if I removed the false (the third parameter) which tells CodeIgniter not to escape the column name, there won't be any error, instead '0' will be updated at reputation column.
I don't know what the problem might be, I could have moved on by writing a custom query, but, I wanted to be sure that I'm not doing something wrong.
P.S: custom one will look like this:
UPDATE users
SET reputations = reputations + 10 WHERE user_id = $user_id
Note: in the above error message you might be wondering where the digits in the error came from i.e
'11:01:37 in '11:01:37\nWHERE user_id
It is the value of a column in my table which is also updating along side reputation column.
Thanks amigos.

Could it be your code editor generating the newline?
Anyways, one fast way to avoid the problem is to use codeigniter query method:
$userModel->query("UPDATE `users` SET `reputations` = reputations + 10 WHERE `user_id` = $user_id)
Not the cleanest solution but it makes sure it works! :)
Mattia

Related

Receiving MySQL Error in PHPMyAdmin

BACKGROUND: I am using PHPMyAdmin tool to run MySQL queries. MySQL version is 5.1.55. I have been using MySQL and this PHPMyAdmin tool for about 7 years and have never seen this error. I am trying to do a simple update query changing ne to gb (column = team, table = info). When I use PHPMyAdmin to try to make the changes,
I get the error message:
UPDATE `pickem`.`info` SET `team` = 'gb' WHERE CONVERT(`info`.`team` USING utf8) = \'ne\'.
QUESTION: What is going wrong here? What is the CONVERT Using UTF8 message coming from. How can I get this to just update the fields I want? I have tried to type the SQL code in myself ex: update info set team ="gb" where team = "ne" , but that does not work either. I get the error message:
There seems to be an error in your SQL query. The MySQL server error output below, if there is any, may also help you in diagnosing the problem
ERROR: Unknown Punctuation String # 22
STR: =\
SQL: update info set team =\"gb\" where team = \"ne\"
It seems the system is putting the slashes in there and it is not letting me do this simple update query.
I appreciate any advice on how to fix this.
Thanks!
You are using phpMyAdmin, right? Try using HeidiSQL.
Also check your PHP version, gpc_magic_quotes is already removed at PHP 5.4.0
I tried running your code on phpMyAdmin, removed the backslashes at \'ne\' and its running fine.
Try running a simple update query in HeidiSQL and check if the problem exists.
UPDATE `pickem`.`info` SET `team` = 'gb'
If it runs fine, modify it like
UPDATE `pickem`.`info` SET `team` = 'gb' WHERE `team` = 'ne'
Additional sidenote - check the encoding and data types. You might have overlooked something...
If your query runs fine on HeidiSQL, you can safely assume that something is wrong with your phpMyAdmin installation/configuration
EDIT:
Are the values you are providing contain '\' inside them? If so, you have to do it like
UPDATE `pickem`.`info` SET `team` = 'gb\\'
EDIT 2:
For the meantime, try to use this to solve your problem temporarily.
UPDATE `pickem`.`info` SET `team` = CONCAT('en') WHERE `team` = CONCAT('gb')
EDIT 3:
If all else fails, you probably should get this or this. Since you are on PHP 5.3, I am afraid to say that the gpc_magic_quotes option might have been enabled by your hosting provider. Contact them.

PHP / MySQL query stopped working for no apparent reason

I've got a page that alters a large quantity of variables in my MySQL database, and so far they've all worked great, but now all of the queries inside of a single logic-gate have stopped working for no apparent reason.
I've confirmed the following:
- The variable posted and used in the "if" statement of the gate is as it was intended
- The logic gate is triggered as intended (I can echo stuff and etc inside of it).
- The database connection is established, I am successfully running queries of various types before and after this logic gate on the same connection variable.
- The connection user has ALL PRIVILEDGES enabled, the aforementioned queries surrounding this logic gate are using similar functions successfully.
Here's the logic gate:
if (!empty($_POST["addqual"])){
$coladqual = $_POST["addqual"];
$sqlf = "ALTER TABLE users ADD UNIQUE ('$coladqual') INT( 2 ) NOT NULL";
$conn->query($sqlf);
$sqlc = "INSERT INTO competencebonus (competence,bonus)
VALUES ($coladqual,0)";
$conn->query($sqlc);
}
I've tried multiple alterations, but they don't seem to execute no matter what I do. I've got at least 20 other queries in other logic gates before and after these two and there seems to be virtually no difference between them, apart from these two just not working at all.
EDIT - Here's the error (Thanks to all of you who provided me with the error report syntax)
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 ''TestAA') INT( 2 ) NOT NULL UNIQUE' at line 1
What strikes me as odd is that only the closing parenthesis is around the post input (TestAA). Is it supposed to have both or neither?
I tried changing the syntax and got the following error:
Duplicate entry '0' for key 'TestAB'
The syntax was:
$sqlf = "ALTER TABLE users ADD `$coladqual` INT( 2 ) NOT NULL UNIQUE";
FINAL EDIT:
Made it work. Deleted the "NOT NULL" statement as recommended by Jeff Pucket II. Somehow this combined with the deletion of the parenthesis and use of backticks instead of apostrophe made the thing work.
Thanks for those of you who had the patience to help me with this.
It looks like you're trying to alter an existing table with a unique not null column. I would expect this to fail if any rows already exist in the table, unless your engine imputes zero. Even then this would fail if there were more than one record because of the unique constraint. Also make sure that the column name being added doesn't already exist.
To get the error using MySQLi, try:
$result = $conn->query($sqlf) or die($conn->error);
The 'unique' constraint should go at the end of your query
$sqlf = "ALTER TABLE users ADD ('$coladqual') INT( 2 ) NOT NULL UNIQUE";
Error checking depends on what flavor of MySQL you're running

MySQL, PHP and failing UPDATE Command

I am experiencing something so basic, yet so annoying that I thought I had to put it out to the wider community to save my sanity.
I am using a table within a database to store some very basic data. There is only two columns, Id and Campaign. I only want to use a single row of the table, however, campaign will be updated at various points. I have set up the table as follows:
$sql = "CREATE TABLE IF NOT EXISTS TestCampaign(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
Campaign CHAR(20))";
Initially I write to the table to insert a null CHAR in campaign:
$sql = "INSERT INTO TestCampaign (Campaign) VALUES ('None')";
The based on a specific text field being filled in on an html form followed by a submit button press I intended to do the update of the campaign field:
$sql = "UPDATE TestCampaign SET Campaign = '$Test' WHERE id = '1'";
$Test is the POSTED campaign name from the form. Unfortunately although the INSERT works fine the UPDATE doesn't. I have checked the permissions and I have ALL on this database. I have also checked the syntax with various sites and it seems that it is fine.
Interestingly I do not get an error when I echo:
echo " ".mysqli_error($con);
I'm sure I have made some basic error somewhere but I have been looking at it for so long and changing the syntax that I can't seem to spot it.
Any help would be appreciated.
UPDATE:
I have played around with the code and it seems as though the UPDATE code does work, however, It only works when it is the next line of code after the INSERT. In fact I have found that it works as long as it is not where I need it to be. I have it placed in 'if' statement that is run only on a specific button press on the form:
if(isset($_POST['TestID']))
{
Some Code;
$sql = "UPDATE TestCampaign SET Campaign = '$Test' WHERE id = '1'";
Some More Code;
}
I have checked the rest of the code in the 'if' statement and it seems solid.
Is this odd behaviour or have I missed something?
SOLVED
Finally found out what the problem was, it ended up that when exiting the first 'if' statement as expected the html form code was revisited which must have closed the connection to the database, when the button was pressed to run the second 'if' statement there was a connection to MySQL but no connection to the database I needed access to. A quick fix to re-connect and all works fine.
$sql = "UPDATE TestCampaign SET Campaign = '$Test' WHERE id = 1";
Is the only thing I think is wrong... What do you get with :
Select * from TestCampaign
have you set up any triggers based on this table name? After update, before update triggers may prevent you from storing the required data on the table.
Also, MySQL may use 0 as id value if you don't specify the value of the id at sending insert command. Are you sure the value of your id is 1 in the record you want to update? If you have run insert statements before on your table, the id may be a larger number than 1, because of the MySQL indices (I guess this may be the problem).
I don't know how exactly PHP statements are processed when sending them to MySQL, but I would recommend you to use PDO statements, the PHP syntax would look something like this:
$sql = $pdo->prepare("UPDATE TestCampaign SET Campaign = ? WHERE id = ?");
$sql->bindParam(1, $Test);
$sql->bindParam(2, 1);
$sql->execute();
Tutorial: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
I would also echo your $Test variable to check what is stored in it.
Hope it helps...
Finally found out what the problem was, it ended up that when exiting the first 'if' statement as expected the html form code was revisited which must have closed the connection to the database, when the button was pressed to run the second 'if' statement there was a connection to MySQL but no connection to the database I needed access to. A quick fix to re-connect and all works fine.

Stumped on why MySQL won't accept my query?

Okay, so I'm currently using mysqli_real_escape_string to escape my SQL queries before sending them to MySQL via PHP. Yet, for some reason my queries aren't processing, and when I outputted the MySQL query and pasted it in to PHPMyAdmin, it gave the following error:
#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 ind={A$RTkAIqah0J1N$Fqymnud9s5PwnWw2wC.Y02oDo4H3W8QJPoJ$6$KK8UearuUCDH$FQg' at line 1
Now, the following is my query:
INSERT INTO `db`.table(`colheader`) VALUES ('{\"hey\":[\"Hello world\",\"7\\/9\\/2013\"]}') WHERE ind='$6$RTkAIqah0J1N$Fqymnud9s5PwnWw2wC.Y02oDo4H3W8QJPoJ$6$KK8UearuUCDH$FQgSnLHIlkBOtDTzu9AuZIZTr6GS4Rzr.iW11041994'
Now, I know that the string assigned to 'ind' has some issues, but I tried putting a slash before every period and every dollar sign and it still doesn't work. I tried putting the whole thing in double quotes, even brackets. Nothing. Could anyone point out what I'm clearly missing? I've looked at the documentation and can't seem to find anything. Thank you in advance!!
WHERE serves to filter which records will be affected or retrieved by your query, and INSERT servers to append a whole new record to a table.
An INSERT can never affect existing records, therefore its nonsense to have a WHERE clause. INSERT does not support WHERE.
If you are trying to edit the value of a field on an existing record, use UPDATE instead.
Take a look at the MySQL Reference Manual for details about its usage.
if your trying to make an update to the specified index use
UPDATE `db`.table SET `colheader` = '{\"hey\":[\"Hello world\",\"7\\/9\\/2013\"]}' WHERE ind='$6$RTkAIqah0J1N$Fqymnud9s5PwnWw2wC.Y02oDo4H3W8QJPoJ$6$KK8UearuUCDH$FQgSnLHIlkBOtDTzu9AuZIZTr6GS4Rzr.iW11041994'

Problem with MySQL query to recordset - possibly caused by move from MySQL 4 to MySQL 5

I have a website with a sales and wanted page, which uses a query to return all of the sales & wanted ads into a recordset. It's been working for 4-5years without incident, but suddenly stopped working on Friday. My ISP tell me they have implemented v5 of MySQL, which seems to have caused the problem.
The query is below:
$query = "select * from $table order by uidno desc limit $from,$max_results";
It's executed via the following command
$recordset = mysql_query($query);
if($recordset == false)
{
echo("Could not retrieve comment. Please try later<br>");
echo("060211<br>");
return;
It's no longer able to load the comments into the recordset. Also the statement to populate the table is no longer populating the fields in the table correctly, though a new row is being created.
The statement is below:
$inputdata = "INSERT INTO $table(date,name,email,suggestion) values('$today','$inputname','$email','$suggestion')";
And it is executed via:
$outcome = mysql_query($inputdata);
The structure of the table is as follows:
uidno int(11) extra=AUTO_INCREMENT Null=no default = none
date date default 0000-00-00
Name varchar(60)
Email varchar (60) Null=yes Default = NULL
Suggestion blob attrbutes=binary null=no
Please help - I don't understand what changes I need to make to the syntax to make these queries compatible with MYSQL v5.
Update:
I added the echo mysql_error(); and it appears to output the following:
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 '-10,10' at line 1
So this indicates an error in the syntax - but I've no idea what the error is.
http://dev.mysql.com/doc/refman/5.0/en/select.html
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).
Column, index, stored routine, and
event names are not case sensitive on
any platform, nor are column aliases
so your lowercase column names in code and upper case column names in mysql structure should not be the problem.

Categories