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
Related
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
I'm wondering if there's an easy way to check if an INSERT statement triggers a conflict due to a unique index on a MySQL field while performing the INSERT.
For example, say I'm adding a user to a database, and username is a unique index:
$sql = new MySQLi(...);
$res = $sql->query('INSERT INTO `users` (`username`) VALUES ("john_galt");');
A user named john_galt already exists, so the INSERT won't be performed. But how can I best respond to the user with a meaningful error (i.e. A user with that username already exists; please choose a unique name.)?
I thought of a couple things, like checking if insert_id is set -- which it shouldn't be if the query generated an error. But that error could be anything.
Similarly, I could check to see if $sql->error is not empty, except, again, that could be anything as well -- a syntax error, or a malformatted value, or whatever. Obviously I'm not going to print out the actual MySQL error for the end user.
The two solutions I can think of are:
Before running the INSERT, run a SELECT TRUE FROM ``users`` WHERE ``username`` = "john_galt"; to see if the username already exists in the database, but I feel like I added a unique constraint to the field so that I wouldn't have to do this -- kinda defeats the purpose otherwise.
strpos($sql->error, 'Duplicate entry') === 0 -- seems horribly hackish.
Is there a better method for determining this using PHP's MySQLi class?
You can use errno to get the returned error code and use that, for example:
if($sql->errno === 1062) {
//do something
}
Here's a list of error codes for MySQL 5.5: http://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
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.
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.
I've inherited a project which we are trying to migrate to MySQL 5 from MySQL 4.0(!) and from myISAM to InnoDB. Queries are now falling down because they are being constructed using an ADODB connection's ->qstr() on all parameters, including ints. Where no value is provided I end up with:
INSERT INTO tablename VALUES ('', 'stuff'...)
where the first column is an auto_increment. This causes an error (fair enough since '' isn't an int). Is there a switch in MySQL to make it behave as it used to (I assume it just silently converted to 0?)
Edit:
I just ran a few tests and what I wrote below won't help you at all. The error is because of the wrong datatype, and the SQL setting I suggested doesn't change that. I'll leave this answer here though, since it might be helpful to someone else.
Firstly, double check that the column really is auto increment - a couple of times I've had CREATE TABLE files where the fact that a column is auto_increment was sadly missing.
The other thing which might help is to check that NO_AUTO_VALUE_ON_ZERO is not turned on.
SET SQL_MODE='' should turn it off.