How to use plain SQL in Kohana 3.x - sql

I dont want to rely on all those ORM/Querybuilder etc. tools in Kohana 3.x. I just want do use plain old SQL to Insert a new row in my table of my MySQL Database.
How can I do that?

You can use DB::query($type, $sql) method to create Database_Query object:
$sql = "INSERT INTO table(column1, column2) VALUES(:value1, :value2)";
$result = DB::query(Database::INSERT, $sql)->bind(':value1', $val1)->bind(':value2', $val2)->execute();
echo $result[0]; // last_insert_id
echo $result[1]; // total rows inserted
More info

Related

Wordpress post update code is not working

I want to update a topic with a post id in Wordpress and add it to the end of the post. However, I could not run the code below. Can you help?
wp_update_post(['ID' => $posts->ID,"post_content" => "concat_ws(' ',post_content, 'SECOND')"]);
Normally, this process is done over sql with concat. But I want to use it with php.
The version that works with sql;
update test_user set descrip = concat_ws(' ',descrip, 'SECOND') where Id=2
but I want to run it with php, not sql. How should the first code be?
You can use braces or concatenation operator .
echo "qwe{$a}rty"; // qwe12345rty, using braces
echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used
Also, it much better to use WP_Post class than modify data in tables directly.
Your WP instance can use some db caching layer, or some hooks for posts updating. This functionality can be
potentially broken if you work with tables directly.
$post = get_post( 123 );
$post->post_content = $post->post_content . "Some other content";
wp_update_post( $post );

Wordpress How to retrieve results from database using $wpdb

I have a table of values and I would like a user to choose a row from the list with a drop-down menu in a WordPress page and have values from various columns populated in the same WordPress page.
I am trying to learn how to use the $wpdb class in WordPress to do this, I am trying to understand first how to write something that will be displayed in the user's browser, but I think I might be missing some critical parts:
What I have done is to create a table called 'wp_axleaa' in my WordPress database. I am trying to query this table and the only result I get printed is “Array”
I wrote a plugin as follows:
<?php
/**
* #package Trying to Connect
* #version 1.6
*/
/*
Plugin Name: Trying to Connect
Plugin URI:
Description: Connecting to DB with $wpdb
Author: Paul J
Version: 1.0
Author URI:
*/
function tc_info() {
global $display;
global $wpdb;
$display = $wpdb->get_results(
'
SELECT *
FROM $wpdb->wp_axleaa
');
print $display;
}
add_shortcode('showinfo','tc_info');
?>
Then I put the shortcode [showinfo] into my WordPress site, and when I view the page then it just shows “Array”. If I add a WHERE clause to the SQL statement, then I get an error message on the page.
I am very new to WordPress and writing PHP and would really appreciate any help, I'm sorry if this is a long-winded question...
Thanks very much,
That's because get_results() returns an array. You may want to modify your code like this:
function tc_info()
{
global $wpdb;
$output = '';
$sql = 'SELECT * FROM $wpdb->wp_axleaa';
$rows = $wpdb->get_results( $sql );
if ( $rows ) {
foreach ( $rows as $row ){
$output .= $row[0];
}
}
print $output;
}
Your problem is not exactly retrieving the database info. First, Shortcode values should be returned. Not printed or echoed. Second, you need to do something with the array you're receiving from the DB query.
To have a nicely formatted display of the array contents, instead of print $display;, use:
return '<pre>' . print_r( $display, true ) . '<pre>';
If you want fast progress in learning, you'll need to consult the documentation frequently:
http://codex.wordpress.org/Class_Reference/wpdb
http://php.net/manual/en/function.print-r.php

Remove html entities from a databases

Due to errors of my predecessors a (MySQL) database I would like to use contains a lot of HTML entities (e.g. € instead of €).
As the database should contain raw data (a database shouldn't have anything to do with HTML) I want to remove them from the DB and store it in proper UTF8, the collocation is already that.
What would be a good way to fix this? The only thing I can think of is to write a PHP script that gets all the data, runs it through html_entity_decode() and writes it back. It's doable since it's a one-time-operation and the DB is only about 100MB large, but it's still less than optimal.
Any ideas?
Since no-one could provide a satisfying SQL-only solution, I solved it with a script similar to this one.
Note that it only works if all the tables you use it on have a primary key, but this will usually be the case
<?php
// Specify which columns need to be de-entitiezed
$affected = array(
'table1' => array('column1', 'column2'),
'table2' => array('column1', 'column2'),
);
// Make database connection
$db = new PDO("mysql:dbname=yourdb;host=yourhost", "user", "pass");
foreach($affected as $table => $columns){
// Start a transaction for each table
$db->beginTransaction();
// Find the table primary key. PHP5.4 syntax!
$pk = $db->query("SHOW INDEX FROM " . $table . " WHERE Key_name = 'PRIMARY'")->fetch()[0];
foreach($columns as $column){
// Construct a prepared statement for this column
$ps = $db->prepare("UPDATE " . $table . " SET " . $column . " . = ? WHERE " . $pk . " = ?");
// Go through all rows
foreach( $db->query("SELECT " . $column . ", " . $pk . " FROM " . $table) as $row){
$row[0] = html_entity_decode($row[0]); // Actual processing
$ps->execute($row);
}
}
// Everything went well for this table, commit
$db->commit();
}
?>
I tnink u need to create a mysql procedure. (with SELECT loop and update replace) REPLACE(TextString, '&apos;','"') ;
Depending on the database (Oracle, MySql, etc) and whether you can take it offline you might be able to export all the DDL and data as a large SQL script (containing INSERTs for all the tables). Then you could do a standard search/replace using sed:
sed -i 's/€/€/g' script.sql
then drop the database or truncate the tables and recreate it using the script.
Ultimately I think you are going to have to resort to PHP at some stage, converting a lot of these entites in SQL is going to invole a huge amount of desicion logic.
However, One approach I can think of if you must use SQL, is to create a user defined function, that esentially has a huge case statement in (Or lots of if/then's) :
http://dev.mysql.com/doc/refman/5.0/en/case-statement.html
Then you should simply be able to do something like:
SELECT col1,col2,col3,mtuserdecodefunction(column-with-entities-in) FROM mytable
Which should in theory return you a cleaned table.

Zend Framework output ready prepared statement

How to output sql statement right before it's launched?
To check all placed data inside prepared statement.
Zend_Db doesn't have a mechanism itself to output the sql statements that it generates. What you can do is modify the public method "query" in Zend/Db/Adapter/Abstract.php(line 445 in 1.10.6) to output the $sql local variable. The query method is called by both the update and insert methods.
There is actually a way to output the SQL it generates
$select = $db->select()->from('elements')
->where('id = ?', $this->_Id);
$sql = $select->__toString();
echo $sql;
You can also use:
echo (string) $select;

Using Raw SQL with Doctrine

I have some extremely complex queries that I need to use to generate a report in my application. I'm using symfony as my framework and doctrine as my ORM.
My question is this:
What is the best way to pass in highly-complex sql queries directly to Doctrine without converting them to the Doctrine Query Language? I've been reading about the Raw_SQL extension but it appears that you still need to pass the query in sections (like from()). Is there anything for just dumping in a bunch of raw sql commands?
$q = Doctrine_Manager::getInstance()->getCurrentConnection();
$result = $q->execute(" -- RAW SQL HERE -- ");
See the Doctrine API documentation for different execution methods.
Yes. You can get a database handle from Doctrine using the following code:
$pdo = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh();
and then execute your SQL as follows:
$query = "SELECT * FROM table WHERE param1 = :param1 AND param2 = :param2";
$stmt = $pdo->prepare($query);
$params = array(
"param1" => "value1",
"param2" => "value2"
);
$stmt->execute($params);
$results = $stmt->fetchAll();
You can use bound variables as in the above example.
Note that Doctrine won't automatically hydrate your results nicely into record objects etc, so you'll need to deal with the results being returned as an array, consisting of one array per row returned (key-value as column-value).
I'm not sure what do you mean saying raw SQL, but you coud execute traditional SQL queries this way:
...
// $this->_displayPortabilityWarning();
$conn = Doctrine_Manager::connection();
$pdo = $conn->execute($sql);
$pdo->setFetchMode(Doctrine_Core::FETCH_ASSOC);
$result = $pdo->fetchAll();
...
The following method is not necsessary, but it shows a good practice.
protected function _displayPortabilityWarning($engine = 'pgsql')
{
$conn = Doctrine_Manager::connection();
$driver = $conn->getDriverName();
if (strtolower($engine) != strtolower($driver)) {
trigger_error('Here we have possible database portability issue. This code was tested on ' . $engine . ' but you are trying to run it on ' . $driver, E_USER_NOTICE);
}
}
You can also use Doctrine_RawSql(); to create raw SQL queries which will hydrate to doctrine objects.
It should be noted, that Doctrine2 uses PDO as a base, thus I would recommend using prepared statements over plain old execute.
Example:
$db = Doctrine_Manager::getInstance()->getCurrentConnection();
$query = $db->prepare("SELECT `someField` FROM `someTable` WHERE `field` = :value");
$query->execute(array('value' => 'someValue'));
Symfony insert raw sql using doctrine.
This in version Symfoney 1.3
$q = Doctrine_Manager::getInstance()->getCurrentConnection();
$result = $q->execute($query);