I have the following code, but it doesn't work. I think it might be because the method was removed? Not sure what the new way to do it is though. I'm on wordpress.
<php?
mysql_query ("UPDATE $wpdb->users
SET access_key = $newAccessKey
WHERE ID = $currentUserID");
?>
That don't work.
users is the table nome.
Advice??
This script is to be run on a page on php.
First you start with wrong syntax to start PHP script '
Now you should check the type of access_key if it is integer than you wrote right and if it is varchar or text then you should write with ''. For this your query is below.
mysql_query ("UPDATE $wpdb->users
SET access_key = '$newAccessKey'
WHERE ID = $currentUserID");
I hope you will get solution.
use single quote for string vars and be sure for sanitize $wpdb->users use concat
mysql_query ("UPDATE " . $wpdb->users .
" SET access_key = '$newAccessKey'
WHERE ID = $currentUserID");
The reason why it doesn't work for you can be a number of things. You can find it out by enabling error reporting (ini_set('display_errors', true); error_level(E_ALL);) and checking for mysql errors (echo mysql_error();).
Second, if it wasn't a typo when you were writing the question:
<php? doesn't start PHP code. It should be <?php, the way you wrote it it is ignored both by the server and the browser because it is an illegal tag and the code inbetween isn't executed at all.
Apart from that, $wpdb brings its own update() function that you can use:
$wpdb->update(
$wpdb->users,
array( 'access_key' => $newAccessKey ),
array( 'ID' => $currentUserID ),
array(
'%s' // if $newAccessKey is a string
// '%d' // if $newAccessKey is an integer
),
array( '%d' )
);
That way you don't have to worry about the database connection or deprecated functions.
Related
I have been using a hook in the Advanced Custom Fields plugin (load_field) which loads objects from a table in my database to an ACF select field. The table ('wp_new_royalsliders') is created by the RoyalSlider image slider plugin so i use the hook to populate a select field with the slider names.
This function has worked fine for a long time but recently stopped working - I think after updating core to 4.8.2:
add_filter('acf/load_field/name=media_gallery_slider', 'my_acf_royalslider_choices');
function my_acf_royalslider_choices($field){
$field['choices'] = array();
global $wpdb;
$query = $wpdb->prepare('SELECT * FROM %1$s ORDER BY ID ASC', 'wp_new_royalsliders');
$results = $wpdb->get_results($query);
if(!empty($results)) :
foreach($results as $result) :
$value = $result->id;
$label = $result->name;
$field['choices'][ $value ] = $label;
endforeach;
endif;
return $field;
}
When I turn debugging on I get an error:
WordPress database error: [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 '%1$s ORDER BY ID ASC' at line 1]
SELECT * FROM %1$s ORDER BY ID ASC
When you pass in a hardcoded string value, you don't need placeholders, you can just use
$query = $wpdb->prepare('SELECT * FROM wp_new_royalsliders ORDER BY ID ASC');
If you want to get fancy and portable, you might opt for
$query = $wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'new_royalsliders ORDER BY ID ASC');
So it would work on other prefixes, too, but that might not be necessary if this is a very custom thing that's not going to make it into any other site.
It appears that others have noted the removal of that possibility too, see this request.
Update: as $wpdb->prepare() expects a second parameter (since its job is to escape variable inputs for use in SQL), it might complain. Solution: get rid of it and give your SQL directly to get_results:
$results = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'new_royalsliders ORDER BY ID ASC');
I'm new to cakephp2 and mysql and I want to create a mysql query to update the data with a id that has been passed in.I'm a very slow learner so I would want some help.
$this->User->updateAll(
array(
'User.checked_count' => '`User`.`checked_count` + 1',
'User.modified' => "'" . date('Y-m-d H:i:s') . "'"
),
array(
'User.username' => $username,
)
);
PS. How to get the results from the query above and use foreach loop? It doesn't work, so Im having a little trouble with it .
In cakePhp 2.x you can do it like that:
1) Below is simple update using save() function, where you pass id as reference and cake automatically updates the table when id is set else will insert the data in new row:
$this->User->id = $Id;
$this->User->save($this->request->data);
2) If you want one or more records in a single call to get updated use updateAll() function:
$this->User->updateAll(
array('User.checked_count' => $count),
array('User.id ' => $userId)
);
Try this code
$this->User->id = $passedId;
$this->User->save($this->data);
In above code If user_id is present then It update user data other wise it save userData.
Quick background:
CRUD plugin
WP 3.5
Creating this plugin for my personal knowledge - I'm sure one already exists.
Variables echo out ok.
The create portion of plugin needed 3 hours of research to get the query to work. Tried everything in codex, a handful of answers from Stack Overflow until something worked.
Problem:
Updating a row in a custom table.
This query will work in SQL ->
UPDATE wp_current_issue SET issue_year=9999, issue_month=29 WHERE issue_id=17;
Tried:
global $wpdb;
$wpdb->update(CURRENT_ISSUE_TABLE,
array(
'issue_year' => $issue_year,
'issue_month' => $issue_month
),
array('issue_id' => $issue_edit_id),
array('%d','%d'),
array('%d'));
As well as: (with and without backticks around column names)
global $wpdb;
$sql = $wpdb->prepare("UPDATE wp_current_issue SET issue_year=".$issue_year.", issue_month=".$issue_month." WHERE issue_id=".$issue_edit_id);
$wpdb->query($sql);
Now the funny thing is, I went through the same thing with the INSERT INTO statement. Tried everything. Only thing that would work is this:
global $wpdb;
$sql = $wpdb->prepare(
"INSERT INTO `".CURRENT_ISSUE_TABLE."` (`issue_path`,`issue_img_path`,`issue_year`,`issue_month`) VALUES (%s,%s,%d,%d)", $fileName_issue, $fileName_img, $issue_year, $issue_month);
$wpdb->query($sql);
Anyone know how I could rewrite this query for an update statement?
Assuming I understood your problem correctly if you want to rewrite that insert into an update then just use
$sql = $wpdb->prepare(
"UPDATE `".CURRENT_ISSUE_TABLE."` SET `issue_path` = %s, `issue_img_path` = %s, `issue_year` = %s, `issue_month` = %s
WHERE issue_id = %i", $fileName_issue, $fileName_img, $issue_year, $issue_month, $issue_edit_id);
The rest is the same.
I'm trying to retrieve content using two items in the URL. Here is the php/symfony code that should do it:
$em = $this->getDoctrine()->getEntityManager();
$repository = $this->getDoctrine()
->getRepository('ShoutMainBundle:Content');
$query = $repository->createQueryBuilder('p')
->where('p.slug > :slug')
->andWhere('p.subtocontentid > :parent')
->setParameters(array(
'slug' => $slug,
'parent' => $page
))
->getQuery();
$content = $query->getSingleResult();
However, when this code is executed it returns the following error:
No result was found for query although at least one row was expected.
I have done some tests, and the data held in the $slug and $page variables hold the correct information. I have also tested the MySQL query and the query brings up the desired result, which confuses me further.
Have I missed something?
As it was answered here
You are getting this error because you are using the
getSingleResult() method. it generates an Exception if it can't find
even a single result. you can use the getOneOrNullResult() instead
to get a NULL if there isn't any result from the query.
Query#getSingleResult(): Retrieves a single object. If the result
contains more than one object, an NonUniqueResultException is thrown.
If the result contains no objects, an NoResultException is thrown. The
pure/mixed distinction does not apply.
No result was found for query although at least one row was expected.
Another reason could be:
You did this
$query = $this->getEntityManager()
->createQuery('
SELECT u FROM MyBundle:User u
WHERE u.email = :email')
->setParameter('email', $email);
return $query->getSingleResult();
Instead of this
$query = $this->getEntityManager()
->createQuery('
SELECT u FROM MyBundle:User u
WHERE u.email = :email')
->setParameter('email', $email);
$query->setMaxResults(1);
return $query->getResult();
Don't you want to use "=" instead of ">" ?
If you've got this message because used
$content = $query->getSingleResult();
you can just replace it with the row below
$content = $query->getOneOrNullResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) ?? 0;
$data = array (
'next' => "NOW() + 5",
'interval' => $dom["USER"][0]["STATUSES_COUNT"][0]["data"],
'good' => $good,
'tries' => $p->tries + 1
);
$where = $service->getAdapter()->quoteInto('id = ?', $p->id);
$service->update($data, $where);
to insert something to a database using PHP on zend and mySQL.
The "next" => "NOW()" wont work. I could put the CURRENT_TIMESTAMP as default value, but what i actually want is to insert the timestamp refering this moment, plus some time.
I could rewrite some parts of the program to use pure php dates(instade of pure mySQL dates). Dont know what is best, or what should i do. Do you know how i could make this update work with mySQL doing the timing?
I solved it with the next statement, very usefull:
'next' => new Zend_Db_Expr('TIMESTAMPADD(MINUTE,1,NOW())'),