Wordpress - Update Database - $wpdb->prepare - php

I do have a weird problem inside my custom wordpress script. I want to update my database and I used this line of code to do it:
$update1 = $wpdb->query($wpdb->prepare("UPDATE wp_avg_rate SET avg='$raty' WHERE user_id= '$user->ID'"));
Problem was now, that my page loaded about 20 seconds so I started debbuging and I found out that $wpdb->prepare needs a second parameter. I tried this code and right now it is working:
$update1 = $wpdb->query($wpdb->prepare("UPDATE wp_avg_rate SET avg='$raty' WHERE user_id= %d'", $user->ID));
Problem is now, that in my opinion there is a ' (at the end by %d) closed but never opened so I tried these codes:
$update1 = $wpdb->query($wpdb->prepare("UPDATE wp_avg_rate SET avg='$raty' WHERE user_id= '%d'", $user->ID));
$update1 = $wpdb->query($wpdb->prepare("UPDATE wp_avg_rate SET avg='$raty' WHERE user_id= %d", $user->ID));
As soon as I am using those codes the site load is again more than 20 seconds. Can someone help me and tell me what the correct syntax for the database update is?

The correct syntax for this SQL query is:
$update1 = $wpdb->query($wpdb->prepare("UPDATE wp_avg_rate SET avg='$raty' WHERE user_id= %d", $user->ID));
prepare will replace the %d with a sanitised integer of $user->ID
The 20 second delay you are seeing must be a problem with your database, database server, or your connection to it, which we can't troubleshoot given the information provided.
Here are things you can try
First and foremost make sure that the SQL is getting generated properly. Check out Debug Bar, and the SAVE_QUERIES option for wp-config
https://codex.wordpress.org/Debugging_in_WordPress
Next Check that you can perform these queries quickly using a MySQL Client. I would recommend using the mysql command line tool if possible but PHPMyAdmin or MySQL Workbench will do the job too
Finally if the query is correct and fast when executed in a client, then you might want to check your DNS settings. I have encountered similar problems caused by the Database Server not being able to resolve the WordPress server's hostname
Please let me know how that goes!

Related

CodeIgniter adds new line characters in my query

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

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.

mysql_query Update of varchar doesn´t work with "-"

I'm trying to find out what the problem is since hours. I have a varchar(255).
works:
mysql_query("UPDATE `servers` SET `url`='quicktest' WHERE `id`=63");
doesn't work:
mysql_query("UPDATE `servers` SET `url`='quick-test' WHERE `id`=63");
What is wrong with the "-" chars that it doesn't work? I mean I can update it in phpmyadmin without problems and sometimes it even works via mysql_query. (1 of 20 cases)
About mysql_query I know that it is outdated but it is just updating internal stuff.
Update #1
I did not had this problem on an old debian 6 server but since it is on ubuntu 13.10 with maria db and php5-fpm I can´t use this script any more and I don´t get any errors.
Update #2
As it looks like it was related to either caching via the apache modules or the google pagespeed module.
Not a solution, but maybe it's worth to try:
$temp_url = mysql_real_escape_string('quick-test');
mysql_query("UPDATE `servers` SET `url`='".$temp_url."' WHERE `id`=63");

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.

PHP Mysql concurrent

I am recently coding PHP with mysql. I have a problem with concurreny with Mysql
For example , if I got a result set from mysql like
$result = $data -> where("id > 5");
and meanwhile another page submit a query like "delete table ...".
Are there any data in $result which I have already got before?
I am not sure what your question is.
But if you set $result with data from the DB and then delete the corresponding data in the DB while the PHP code is still running, it will still be in the variable. But if you do another request to the DB it will not find it anymore.

Categories