update current database table - php

I'm making a WordPress plugin and I need to update tables for the current database in a query. However, instead of writing the database name into the sql, I need some way to select it in the query so that way it will work no matter what your database's name is. This is the code I currently have:
$stmt = $conn->prepare("UPDATE `wp_plugin_development` . `wp_users` SET `user_pass` = ? WHERE `user_login` = ?") or trigger_error($mysqli->error);
$stmt->bind_param('ss', $user_password[$i], $user_login[$i]);
wp_plugin_development is my current database name, but needs to be replaced with some other way of selecting the database name. I wish I could write something like UPDATE SELECT DATABASE() but that obviously doesn't work. Maybe there's an entirely different way to code this? I still consider myself new to all this, so I'm sorry if I'm missing something obvious. Any help is greatly appreciated.

You don't need the current database name, because the connection is already established with the current database.
You need the tablename! The prefix is set when setting up wordpress. You need the prefix, because every installation is different.
The proper Wordpress way is like this:
global $wpdb;
$table_name = $wpdb->prefix . 'plugin_development';
The prefix is stored (wp_). In WP; you don't use PDO or MySqli directly, you work with the global $wpdb object.
$wpdb->update($table_name, $data, $where, $format = null, $where_format = null);
If you really need the database name, it's stored in $wpdb->dbname;.
Here are examples and the class reference:
https://codex.wordpress.org/Class_Reference/wpdb

I was using another database as the connection method (this was defined in the $conn variable). So I made a new connection to the current database using $wpdb and named it $this_db. Now I don't have to specify the database name in the query and it works like I want it to. For better context, here's the code I added/changed:
$thisServername = $wpdb->dbhost;
$thisUsername = $wpdb->dbuser;
$thisPassword = $wpdb->dbpassword;
$thisDBname = $wpdb->dbname;
$this_db = new mysqli($thisServername, $thisUsername, $thisPassword, $thisDBname);
$stmt = $this_db->prepare("UPDATE `wp_users` SET `user_pass` = ? WHERE `user_login` = ?") or trigger_error($mysqli->error);
$stmt->bind_param('ss', $user_password[$i], $user_login[$i]);
So, for solving this specific issue, this solution works. Sorry I forgot to mention using the external database. That was an important thing I left out of the question. And thank you everyone for your input.

The function database() returns the DB name - http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_database -
so you can run SELECT DATABASE(); first to get the DB name.

Related

Selecting MySQL views using $wpdb class

I am building a Wordpress site and it is connected to a MySQL database. I am using the wordpress class wpdb (https://codex.wordpress.org/Class_Reference/wpdb) to interact with the database. With that class, I am able to query TABLES of my database, but not Views.
I need to be able to select Views of my database. Is this something that is not allowed with wpdb, or is my code just wrong? Is there a way to query views the same way I can query tables using wpdb?
I have tried using the query function, as well as treating a view the same way I treat a table, but it does not work. It returns empty.
Query method:
$test = $mydb->query(
$mydb->prepare(
"
SELECT name FROM $mydb->$view_name
WHERE id = 1"
)
);
echo $test; //returns empty; should return a name
Table method:
$test = $mydb->get_var(
"select name from $view_name WHERE id = 1"
);
echo $test; //returns empty; should return a name
Any suggestions? Am I able to connect to my database using something other than $wpdb (does Wordpress allow that?).
name seems to be a reserved word in MySQL (reference). Try surrounding it with back-ticks (`) like this:
SELECT `name` FROM ...
You should be seeing some errors, do you keep an eye on the logs? Also, when you have doubts in your queries, you can simply copy the raw query and execute it into phpMyAdmin or whatever tool you are using to access your database manually

Best way to check if Joomla! 3.4.0 article already exists

I am creating articles in Joomla! programmatically using JTable.
Since I have a lot of articles that need to get synchronized periodically, I need to check each article if it already exists before inserting it (otherwise it produces errors).
What is the best way to do so?
My idea was to retrieve all articles from database and compare unique fields. But problems (blank page) occured while retreiving the articles. Here is the code:
function getExistingArticles(){
// Create a new query object.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*')->where('`a.created_by_alias`= `article_synchronizer`'); // Prepare query.
$query->from('`#___categories` AS a');
// Reset the query using newly populated query object.
$db->setQuery($query);
$articles = $db->loadObjectList(); // Execute query, return result list.
return $articles;
}
If this is the "best" way in Joomla! to check if a certain article already exists, where is the problem in this code, that results in a blank page?
Otherwise which is the best way to check if a Joomla! article with a certain content already exists?
I haven't tested your query, but I would suggest quoting column names and values using Joomla's API like so:
function getExistingArticles()
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('a.*')))
->from($db->quoteName('#__categories', 'a'))
->where($db->quoteName('a.created_by_alias') . ' = ' . $db->quote('article_synchronizer')); // Quoted query.
$db->setQuery($query);
$articles = $db->loadObjectList();
return $articles;
}
I've fixed your query a little. You were using 3 underscores when defining the table prefix (only 2 should be used). The where and from clauses were also the wrong way round.

Variable changes with no apparent reason while using class

I am using phpmydatagrid to display many tables.
To determine which table, I am using GET.
This is the class: http://www.phpclasses.org/browse/file/18544.html
The javascript part: http://www.phpclasses.org/browse/file/18559.html
This is a part of my code:
include ("phpmydatagrid.class.php");
$objGrid = new datagrid;
$getId = $_GET['id'];
$tablename = "xxx_$getId";
//Some code here...
$objGrid -> tabla($tablename); //This is how you set the table using the class
The table is shown correctly, and if I echo $objGrid->tablename I get the correct table name.
But when you try adding a new row using the interface the table name suddenly becomes "xxx_" without the id.
I looked in the class codes and there's nowhere where 'tablename' is being changed. To the query just search "INSERT INTO" in the class.
I hope I made myself clear enough, also the class file might help you understand.

User logon scripts using php

Hi I am new to PHP and Mysql. I need help with a logon on script I am currently writing. I have the script working fine. But I am wanting to add an additional requirement for logging in.
In the table I have:
user_id | username | password | first_name | department
-------------------------------------------------------
I am currently authenticating users by using just there username and passsword but I want to add another requirement of "department". There are two entries in the department column either "user" or "manager". I want to only allow access to a manager how can I add this in?
The mysql query i am using is:
$query = "SELECT * FROM users WHERE username='".mysql_real_escape_string($uname)."' AND password='".mysql_real_escape_string($passencrypt)."'";
Don't ever save pure passwords in db! You should use hashes or encryption.
Don't use mysql_* functions because they are depracated and will be removed in future. Use mysqli or PDO instead.
Also remember to bind parameters just changing mysql to mysqli doesn't make your scripts secure.
Adding roles as you mentioned it can be solved on 2 ways.
First is simple but not good to extend and second is better but needs more effort.
Add department as tinyint to DB with 1 = user, 2 = manager
PDO solution
$sth = $dbh->prepare('SELECT * FROM users WHERE username=? AND password=md5(?) AND department=?);
$sth->bindParam(1, $user, PDO::PARAM_STR);
$sth->bindParam(2, $pass, PDO::PARAM_STR);
$sth->bindParam(3, $department, PDO::PARAM_INT);
$sth->execute();
Read more about PDO http://www.php.net/manual/en/pdo.construct.php
Second solution is to use roles and resources. Here is good explanation of how to use it: http://framework.zend.com/manual/1.12/en/zend.acl.introduction.html
$query = "SELECT * FROM users WHERE username='".mysql_real_escape_string($uname)."' AND password='".mysql_real_escape_string($passencrypt)."'";
is okay then simply in php you just check
$row = mysql_fetch_array($result);
if($row['department']=="manager"){
//complete login
}else{
//logout
}
You could either check the value of DEPARTMENT in the resultset and take appropriate action, or filter it out of the query altogether. This will do that:
$query = "SELECT * FROM users WHERE department='manager' AND username='".mysql_real_escape_string($uname)."' AND password='".mysql_real_escape_string($passencrypt)."'";
But keep in mind that that means you are not making any distinction between a non-existent user, an incorrect password, or a user who is not a manager.
You just need to add an extra clause to your WHERE
$query = "SELECT * FROM users WHERE username='".mysql_real_escape_string($uname)."' AND password='".mysql_real_escape_string($passencrypt)."' AND delartment = 'manager'";
In this way only member wich have department as manager will be matched by your query
Then I would like to remember you that mysql_ functions are deprecated so i would advise you to switch to mysqli or PDO
you can do this:
if (isset($_POST['manager']))
{
$query = "SELECT * FROM users WHERE username = '$uname' AND password = '$passencrypt'";
}
elseif (isset($_POST['user'])
{...}
of course you will have to replace the three dots within the last pair of braces with whatever you want to do when it is not the manager who signs in.

Data mapper pattern and automated updates of other objects

I'm building a PHP application using the data mapper pattern to separate my DB from the domain objects. I have a mapper class that returns Site objects based on data from the DB and accepts existing Site objects to be saved back to the DB.
My problem is that in the system one (and only one) of all the sites has to be marked as the "primary" site, which means that if I set one as the primary, I'd like to be able to automatically unset the current primary.
So, something like:
$mapper = new Site_Mapper();
$site = $mapper->fetch(2);
$site->isPrimary = true;
$mapper->save($site);
Would somehow in the background automatically do this:
$mapper = new Site_Mapper();
$site = $mapper->fetch(1);
$site->isPrimary = false;
$mapper->save($site);
Question is, where should the logic for automatically updating the existing primary site go? It has to happen after the object is saved back to the DB, not before, in case the DB query fails and you're left with no site as the primary.
Cheers,
Jack
Personally I would think that it makes the most sense to place the additional update logic with the Site_Mapper class, especially considering that you're dealing with the same table / mapper in both instances. You could simply override the save($siteObj) method so that it works like this:
public function save($siteObj)
{
// Save the passed object.
$sql = "UPDATE site SET isPrimary = 1 WHERE id != ?";
$stmt = new PDO_Statement($sql);
$stmt->execute($siteObj->id);
}
Obviously you could create either a custom save() function to do this perhaps a little more smoothly or you could use an if comparison to ensure that you actually need to run the update statement.
Sounds like a job for a database trigger.
DELIMITER $$
CREATE TRIGGER test_trigger AFTER INSERT ON table
FOR EACH ROW BEGIN
IF NEW.isPrimary = 1 THEN
UPDATE table
SET isPrimary = 0
WHERE id <> NEW.id;
END IF;
END$$
DELIMITER ;

Categories