I have the following line of code :
mysql_query("SELECT name FROM details WHERE md5(name) = '".md5($input_name)."'");
This query works just fine , however , when i change the query to the following :
mysql_query("SELECT name FROM details WHERE salt(name) = '".salt($input_name)."'");
The query doesn't seem to work.
The salt function is as follows :
function salt ($name) {
global $salt;
return $salt.$name;
}
where $salt is a global variable ( an md5 hash)
Why doesn't the second query work ?
MySQL has no access to functions you define in PHP. You can only use functions that MySQL defines in a MySQL query, or functions that you have written in SQL. You'll have to rethink what you're doing and express it in a way that does not require MySQL to use PHP functions.
Functions in PHP and functions in MySQL is two seperate things.
When sending MySQL queries, MySQL will be responsible for parsing the string you are sending. And MySQL doesn't know of any of the PHP code you made - and vice versa.
Wouldnt this be easily done by:
$saltinput = salt($input_name)
mysql_query("SELECT name FROM details WHERE salt(name) = '$salitinput'");
Related
I need to execute two SQL statements together because connection_id() in the first statement will be used in the Mysql view wp_statistics_benchmarks.
Without the connection_id(), the wp_statistics_benchmarks is an empty view. The following SQL works fine and get results:
replace into wp_params (`view_name` , `param1_val`, `connection_id`)
values ('benchmarks', 484 , connection_id())
;
select * from wp_statistic_benchmarks;
But, to work with wordpress, the following code doesn't work:
$mysqli = new mysqli(.....);
$results = $this->_wpdb->query("
replace into wp_params (`view_name`, `param1_val`, `connection_id`)
values ('benchmarks', $connected_from, $mysqli->thread_id);
select * FROM `wp_statistic_benchmarks`;"
);
How can I convert these two mysql codes into Wordpress wpdb queries?
Use the wpdb object twice.
$this->_wpdb->query('replace into ...');
$rows = $this->_wpdb->get_results('select ...')
Let me put it another way, select * from wp_stat ... and replace into wp_params ... from your original "mysql codes" are separate statements without any relation to each other.
You think that you need to run them in sequence, whereas in fact you can have a cup of coffee or even travel around the earth in between those replace into and select statements and they would still do the same thing. If that is not the case, then your question lacks information necessary to provide a good answer because wp_params is not a standard table in wordpress and neither is the view. I don't think you understand your problem.
Besides, running them as I suggest is equivalent with your "mysql codes". Moreover, $wpdb->query returns the number of affected rows or false, so you will never be able to run a select statement with $wpdb->query() to retrieve a set of tuples.
How can I convert these two mysql codes into Wordpress wpdb queries?
You can't. That's because you're using wpdb and it only supports one query per ->query() call. However, if you're using Mysqli with wpdb, you can use the multi_query() method of it with wpdb. Here is how:
To use multiple queries, you need to ensure that wpdb uses Mysqli (e.g. define the USE_EXT_MYSQL constant as FALSE in your Wordpress config).
Then you can obtain the mysqli instance from the wpdb object, either with reflection or a helper class/module:
abstract class wpdb_dbh extends wpdb
{
static function from(wpdb $wpdb) {
return $wpdb->dbh;
}
}
Mysqli is then available without creating a new instance:
$mysqli = wpdb_dbh::from($this->_wpdb);
As this is a valid Mysqli instance you can run multi query.
But just obtaining the same Mysqli instance as wpdb uses it probably the most important thing here as otherwise your open an additional connection with new mysqli(...) which you need to prevent.
Additionally take care that $mysqli->thread_id is a fitting replacement to connection_id() following the same formatting/encoding. You should be able to use connection_id() directly anyway, so I actually see not much reason to access the thread_id member, but it's perhaps only because you tried some alternatives and I'm just over-cautious.
The ';' query delimiter is purely an SQL shell convenience and is not a part of the MySQL dialect so you're correct that your code doesn't work.
Here's the actual replacement code:
$mysqli = new mysqli(.....);
$this->_wpdb->query(
"replace into wp_params
(`view_name`, `param1_val`, `connection_id`)
values ('benchmarks', $connected_from, $mysqli->thread_id)");
$results = $this->_wpdb->query("select * FROM `wp_statistic_benchmarks`");
This is the same as Ярослав's answer above.
Update:
If your code is still not working you might have to enable persistent connections in Wordpress.
Update 2:
There was a missing space between in the second query's select statement and the * shorthand all columns selector. Interestingly this may or may not cause an issue for you, it doesn't seem to bother my MySQL 5.5 command line shell.
If I understand your requirements (and I do not know wordpress), you are inserting a row to wp_params with a column called connection_id. I would assume that this value will be unique on the table. I would be tempted to add an integer autoincrement id field to the table and then get the value of that (last insert id). Then use this id in a WHERE clause when selecting from the view.
I am currently updating a section of code that uses mysql currently the escape string is structured like this: $product_name = mysql_real_escape_string(trim($_POST['product_name'])); and works fine.
My issue is when I change the above string to $product_name = mysqli_real_escape_string($database, (trim($_POST['product_name']))); and declare the following: $database = $this->load->database(); above it I get the error that its NULL
How do I escape a string with CI?
CodeIgniter user manual wrote the following.
Beyond simplicity, a major benefit to using the Active Record features is that it allows you >to create database independent applications, since the query syntax is generated by each >database adapter. It also allows for safer queries, since the values are escaped >automatically by the system.
You can use Input class in your controller.
$this->load->model('mymodel');
$something = $this->input->post('something');
$results = $this->mymodel->mymethod($something);
In your model
$this->db->insert('mytable', $data);
You use
$this->db->query("select ?",array("value"));
Where each ? In thee select is the variable you want escaped
I'm planning on developing a CMS using PHP and MySQL that utilises MySQL stored procedures to perform prepared statement queries to my MySQL database. It's been a long time since I developed in PHP (back in the procedural days) so I'm going to try and implement this system using the new OOP structure of PHP. Before I do that, I need to get to grips with the simple issue of returning the output parameter of my MySQL stored procedure to a simple php page. This is simply a test so that I can get the syntax correct before developing my first php class so the initial code posted here is procedural.
First, there is my stored procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS `text_development`.`get_user`$$
CREATE PROCEDURE `text_development`.`get_user`
(
IN userId INT,
OUT user_name VARCHAR(100)
)
BEGIN
SELECT username
INTO user_name
FROM user
WHERE user_id = userId;
END $$
DELIMITER ;
Then there is my two php files:
<?php
//db_config.php
$mysqli_host = "localhost";
$mysqli_user = "root"; //I'm not stupid enough to use this in development
$mysqli_pass = "root"; //before anyone comments about the root usage
$mysqli_db = "text_development";
?>
<?php
//index.php
require('incl/db_config.php');
$dbConnection = new Mysqli($mysqli_host, $mysqli_user, $mysqli_pass, $mysqli_db) or die(mysql_error());
print '<h1>Stored Procedure Retrieval Test</h1>';
$id = 1;
$return = '';
$result = $dbConnection->query( 'CALL get_user($id,$return)');
print $result;
?>
My problem arises with the index.php page. It doesn't actually seem to return anything. When executing the stored procedure in PHPMyAdmin the username test is returned when I pass in the user id of 1 however nothing is returned to the screen when calling the function in php. I've also tried printing $return as well but this just returns an empty string (as I define in the code above). I've tried using this online tutorial but the solutions there do not seem to work :
http://www.joeyrivera.com/2009/using-mysql-stored-procedures-with-php-mysqlmysqlipdo/
Does anyone know what I'm doing wrong here and why the return parameter of this stored procedure is not being printed to the screen?
Firstly, you refer to a tutorial on PDO, but you use Mysqli.
Second: convert:
$result = $dbConnection->query( 'CALL get_user($id,$return)');
to (notice the double quotes, and the #return`):
$result = $dbConnection->query( "CALL get_user({$id},#return)");
and then, later, do:
$result = $dbConnection->query( 'SELECT #return');
If the SP is a SELECT, then you do it they you wrote it.
Reason is, the SP does not return to PHP anything, it returns the value into the MySQL variable (#return)(scop is in MySQL), so you need to query this variable in a separate call. If it was a call to a simple select SP, then it would return values as any other select statement.
$result = $myDB->Execute($query) or die(GetDbError($myDB->ErrorMsg()));
Lets say i wanna remove adodb form my script:
$result = $myDB->mysql_fetch_assoc($query) or die(GetDbError($myDB->ErrorMsg()));
It would be correct or not ?
No, it's not correct - mysql_fetch_assoc is a function, not a method - and you would not even have a $myDB object.
I'd also suggest using PDO instead of the plain mysql/mysqli functions.
If $myDB is an adodb object, then $result is an ADORecordSet object. You should fetch (or getAssoc()) on that $result. You're using adodb in order to avoid developing PHP code in a more abstract way, without using particular database engine functions. Then, if you need to move to another database system, you'll need to make minor changes to statements.
$array = $result->FetchRow();
How would i use code igniters active records to insert/update/select data from a database using mysql's built in aes encrypt/decrypt functions?
I know i could just use the normal sql query, but i'd like to use active records ideally.
Thanks
If you use the code provided previously:
$this->db->set('password',"AES_ENCRYPT('{$data['password']}','my_key')",FALSE);
you should still escape the password before passing it into db->set
use:
$pass = $this->db->escape($data['password']);
That way if the password contains special chars it won't kill the query
You can still use AES_Encrypt if you turn off escaping for that particular clause by passing FALSE as the last parameter:
$pass = $this->db->escape($data['password']);
$this->db->set('password', "AES_ENCRYPT('{$pass}','my_key')", FALSE);
Also point you to the CI built-in Encryption Class, and an article on considering 1-way encryption.