Am using drupal to manage my content. I want to search all my contents title and body and find how many times each word is repeated in the whole contents.
It may be by an sql query, but I have no experience with sql.
Any ideas?
This code searches the body field and ALL fields of ANY Content Types for a specific string. You can run it via command line. Say you save it as "fieldsearch.php", you can then run it as:
php fieldsearch.php "myStringForWhichToSearch"
You need to fill in your connection data and database name. It outputs the array of matching nodes but you can format that output into anything you'd like (I recommend csv).
<?php
//Set Parameters here
$env = "dev"; // Options [dev|prod] - Defaults to dev
$prodConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
$devConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
//Use the selected env settings
if($env == "prod"){
$connection = $prodConnection;
} else {
$connection = $devConnection;
}
function getTables($con, $database){
//Get the set of field tables
$sql = "SHOW TABLES FROM $database";
$result = mysqli_query($con, $sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$tables = array();
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
mysqli_free_result($result);
return $tables;
}
function getFieldTables($con,$database){
$allTables = getTables($con, $database);
$fieldTables = array();
foreach($allTables as $key => $table){
if( isFieldTable($table) ){
$fieldTables[] = $table;
}
}
//add the common tables
$fieldTables[] = "field_data_body";
$fieldTables[] = "field_data_comment_body";
return $fieldTables;
}
function isFieldTable($table){
//echo $table . "\n";
if( stripos($table, "field_data_field") !== FALSE){
return TRUE;
}
}
//Set the search term here:
if (array_key_exists(1, $argv)) {
$searchString = $argv[1];
}
else {
die('usage: php fieldsearch.php "search string"' . "\n");
}
$databaseName = "myDatabaseName";
$outArray = array();
//Connect
$con=mysqli_connect($connection['host'],$connection['user'],$connection['pass'],$databasePrefix.$databaseNum);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//getFieldTables
$fieldTables = getFieldTables($con, $databaseName);
//Query each field tables data for the string in question
foreach($fieldTables as $key => $table){
//get Field value column name
$valueCol = str_replace("field_data_field_", '', $table);
$result = mysqli_query($con,"SELECT
entity_id
FROM
$table
WHERE
field_" . $valueCol . "_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray[$table][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
}
//Add the body table
$result = mysqli_query($con,"SELECT
entity_id
FROM
field_data_body
WHERE
body_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray['field_data_body'][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
var_dump($dataArray);
Related
I have a CassandraHandler that retrieves the queries in rows
class CassandraHandler
{
private $keyspace = 'blabla'; //default is oyvent
private $cluster = NULL;
private $session = NULL;
function __construct(){
$this->cluster = \Cassandra::cluster()
->build(); // connects to localhost by default
$this->session = $this->cluster->connect($this->keyspace);
}
/**
* #return Rows
*/
public function execute($query){
$statement = new \Cassandra\SimpleStatement($query);
$result = $this->session->execute($statement);
return $result;
}
}
When I use for normal columns it's fine but I can't get my photo column in php
I created the column like this
photos frozen<set<map<text,text>>>
my json example
{{"urllarge": "1.jpg", "urlmedium": "2.jpg"},
{"urllarge": "3.jpg", "urlmedium": "4.jpg"}}
And here how can I use PHP to retrieve the composite columns?
$cassandraHandler = new CassandraHandlerClass();
$rows = $cassandraHandler->fetchLatestPosts($placeids, $limit);
foreach ($rows as $row) {
$tmp = array();
$tmp["userid"] = doubleval($row["userid"]);
$tmp["fullname"] = $row["fullname"];
$tmp["photos"] = $row["photos"] //????????
}
I know there is this documentation of the PHP driver https://github.com/datastax/php-driver
But I am a little confused.. I just need to get the json value like I get in cqlsh
You have two options to convert the composites into useable JSON:
Create a function to convert the deserialized/unmarshalled objects into JSON.
Retrieve the values from Cassandra as JSON.
Here is an example that demonstrates both options:
<?php
$KEYSPACE_NAME = "stackoverflow";
$TABLE_NAME = "retrieve_composites";
function print_rows_as_json($rows) {
foreach ($rows as $row) {
$set_count = 0;
echo "{\"photos\": [";
foreach ($photos = $row["photos"] as $photo) {
$map_count = 0;
echo "{";
foreach ($photo as $key => $value) {
echo "\"{$key}\": \"{$value}\"";
if (++$map_count < count($photo)) {
echo ", ";
}
}
echo "}";
if (++$set_count < count($photos)) {
echo ", ";
}
}
echo "]}" . PHP_EOL;
}
}
// Override default localhost contact point
$contact_points = "127.0.0.1";
if (php_sapi_name() == "cli") {
if (count($_SERVER['argv']) > 1) {
$contact_points = $_SERVER['argv'][1];
}
}
// Connect to the cluster
$cluster = Cassandra::cluster()
->withContactPoints($contact_points)
->build();
$session = $cluster->connect();
// Create the keypspace (drop if exists) and table
$session->execute("DROP KEYSPACE IF EXISTS {$KEYSPACE_NAME}");
$session->execute("CREATE KEYSPACE {$KEYSPACE_NAME} WITH replication = "
. "{ 'class': 'SimpleStrategy', 'replication_factor': 1 }"
);
$session->execute("CREATE TABLE ${KEYSPACE_NAME}.{$TABLE_NAME} ( "
. "id int PRIMARY KEY, "
. "photos frozen<set<map<text, text>>> )"
);
// Create a multiple rows to retrieve
$session->execute("INSERT INTO ${KEYSPACE_NAME}.{$TABLE_NAME} (id, photos) VALUES ( "
. "1, "
. "{{'urllage': '1.jpg', 'urlmedium': '2.jpg'}, "
. "{'urllage': '3.jpg', 'urlmedium': '4.jpg'}}"
. ")");
$session->execute("INSERT INTO ${KEYSPACE_NAME}.{$TABLE_NAME} (id, photos) VALUES ( "
. "2, "
. "{{'urllage': '21.jpg', 'urlmedium': '22.jpg'}, "
. "{'urllage': '23.jpg', 'urlmedium': '24.jpg'}}"
. ")");
// Select and print the unmarshalled data as JSON
$rows = $session->execute("SELECT photos FROM ${KEYSPACE_NAME}.{$TABLE_NAME}");
print_rows_as_json($rows);
// Select the data as JSON and print the string
$rows = $session->execute("SELECT JSON photos FROM ${KEYSPACE_NAME}.{$TABLE_NAME}");
foreach ($rows as $row) {
echo $row["[json]"] . PHP_EOL;
}
From the above example you can see that selecting the data as JSON involves less code for your application while also moving the processing onto the server. This probably the preferred choice for your application needs.
NOTE: This example is using v1.3.0 of the DataStax PHP driver which added support to pass a query strings directly to Session::execute() and Session::executeAsync(). If you are using an earlier version you will need to convert all query strings to Cassandra\Statement objects before passing to $session->execute(...).
For example
I have several profile tables, such as
music_profile
sports_profile
art_profile
All of these tables have matching names, and they all have a title column.
A second table contains alternative titles per any given profile table's row.
Their columns are essentially:
id, parent_id, parent_table, alt_title_001, alt_title_002, alt_title_003, alt_title_004, status, created, updated.
I want to
SELECT multiple column values
FROM music_profile, sports_profile, art_profile
WHERE title, alt_title_001, alt_title_002, alt_title_003, alt_title_004 are like a value
I can currently select columns using WHERE title LIKE and UNION, but I have no idea how to combine the alternate_titles table in the SELECT statement.
I've provided my current code below. The table for alternate_titles has not been implemented here.
I don't necessarily want a coded solution to this issue; I would just like a hint to get me on my way.
sub AdvancedSearchFormResults {
my $self = shift;
my $opts = ref $_[0] eq 'HASH' ? shift : {#_};
my $mode = shift;
my $order = shift;
my $limit = shift;
my #array;
my $where;
my $mode = $$opts{mode};
my $left_join_clause;
my (#where_stmt, #where_vals, #join);
if (defined $$opts{platform}) {
$where = $$opts{platform};
}
if ($$opts{'title_like'}) {
push(#where_stmt, "title like ?");
push(#where_vals, '%'.$$opts{'title_like'}.'%');
}
if ($$opts{'publisher'}) {
push(#where_stmt, "publisher = ?");
push(#where_vals, $$opts{'publisher'});
}
if ($$opts{'status'}) {
push(#where_stmt, "status = ?");
push(#where_vals, $$opts{'status'});
}
my $left_join_clause = scalar #join ? join("\n", #join) : "";
my $where_clause = #where_stmt ? "WHERE ".join(" AND ", #where_stmt) : "";
my $order_clause = length($order) ? "ORDER BY $order" : "";
my $limit_clause = length($limit) ? "LIMIT $limit" : "";
my $select_stmt;
if ($mode eq 'BUILD') {
$select_stmt = "SELECT
'$where' AS event,
ident,
title,
publisher
FROM $where
$left_join_clause
$where_clause
$order_clause
$limit_clause";
my $sth = $schema->prepare($select_stmt) or die $schema->errstr;
$sth->execute(#where_vals) or die $sth->errstr;
while (my $row = $sth->fetchrow_hashref()) {
push(#array, $row);
}
}
elsif ($mode eq 'UNION') {
my #select_stmts;
my #platforms = $self->ProfileTables();
my $total_platforms = -1;
foreach my $table (#platforms) {
$total_platforms++;
my $stmt = "(SELECT '$table' AS event,ident,title,publisher,status FROM $table $where_clause)";
push(#select_stmts, $stmt);
}
my $select_stmt .= "$select_stmts[0] UNION ALL";
$select_stmt .= join(' UNION ALL ', #select_stmts[ 1 .. 28 ]);
my #new_vals = (#where_vals, (#where_vals) x $total_platforms);
my $sth = $schema->prepare($select_stmt) or die $schema->errstr;
$sth->execute(#new_vals) or die $sth->errstr;
while (my $row = $sth->fetchrow_hashref()) {
push(#array, $row);
}
}
elsif ($mode eq 'REFRESH') {
print '
<div class="alert alert-danger" role="alert">
<strong>Please fill out at least one field.</strong>
</div>';
}
return #array;
}
A practical application of the code is below.
These variables are used as an example. This data would normally be supplied via a form.
my $title = 'Mario';
my $publisher = '';
my %params = (
title_like => $title,
publisher => $publisher,
status => 'a',
);
my #results = $results->AdvancedSearchFormResults(\%params);
print Data::Dumper::Dumper(\#results);
Dumper Results
$VAR1 = [
{
'ident' => '2109',
'title' => 'Mario Bros.',
'publisher' => 'Atari'
},
{
'ident' => '30',
'title' => 'Mario Bros.',
'publisher' => 'Atari'
},
{
'publisher' => 'Atari',
'ident' => '43',
'title' => 'Mario Bros.'
},
];
After a bit of headache and some intense googling I was able to come up with a solution.
The most basic solution to my problem is:
my #profiles = ('art', 'music', 'sports');
my #results;
my $blah;
my $sql;
foreach my $profile (#profiles) {
$sql = "SELECT
$profile.ident,
$profile.title,
$profile.status
FROM $profile
LEFT JOIN alternate_titles ON $profile.ident = alternate_titles.parent_ident
WHERE title like '%$blah%'
OR
CONCAT_WS(' ',alternate_titles.alt_title_001,alternate_titles.alt_title_002,alternate_titles.alt_title_003,alternate_titles.alt_title_004
AND alternate_titles.parent_table = '$profile'";
}
my $sth = $schema->prepare($sql) or die $schema->errstr;
$sth->execute() or die $sth->errstr;
while (my $data = $sth->fetchrow_hashref()) {
push(#results, $data);
}
This isn't immediately implementable in my code example, but this works as a great starting point.
I don't know that this is efficient, if anyone has a better solution, I'd love to see it.
I have to change an old mysql to PDO, I am working with a code its made by someone else, so I have this following code to change in PDO
The original code is
function liste($a,$b,$c)
{
$queryliste= "SELECT id,nom,prenom
FROM table";
$this->list = Connection_Base($querylistactu);
}
//Connection_Base
function Connection_Base($query)
{
$link = mysql_connect(DATABASESERVER, DATABASEUSER, DATABASEPASSWORD);
$ret = mysql_select_db(DATABASEDB, $link);
if (!$ret)
{
die("Echec de connection");
} else {
$mysql_desc = DATABASEDB;
if(!$result = mysql_query( $query))
{
return 0;
} else {
return $result;
}
mysql_close($link);
}
}
This is the part with which I have problem. I want to change it using PDO.
while( list($x,$y,$z) = mysql_fetch_row($lactu->list) )
I am proceed like this but it doesn't work
while( list($x,$y,$z) = $lactu->list->fetch(PDO::FETCH_NUM)
any ideas ?
Why don't you use PDO::FETCH_ASSOC? Check the code sample for connecting to database, executing the query, fetching all rows and iterate over the rows.
//Your query
$queryliste = "SELECT id, nom, prenom FROM table";
//Initialize pdo connection use your $name, $host, $username and $password
$pdoLink = new PDO("mysql:dbname={$name};host={$host};charset=utf8", $username, $password);
//Prepare statement
$statement = $pdoLink-> prepare($queryliste);
//Execute query
$statement -> execute();
//(1) Fetch rows using PDO::FETCH_ASSOC
$rows = $statement -> fetchAll(PDO::FETCH_ASSOC);
$statement -> closeCursor();
foreach($rows as $row) {
echo $row['id'];
echo $row['nom'];
echo $row['prenom'];
}
//(2) or you can use PDO::FETCH_NUM
$rows = $statement -> fetchAll(PDO::FETCH_NUM);
$statement -> closeCursor();
foreach($rows as list($x, $y, $z)) {
echo $x;
echo $y;
echo $z;
}
//(3) or you can rewrite the last in the same form you are using as
while((list($x, $y, $z) = $statement->fetch(PDO::FETCH_NUM))) {
echo $x;
echo $y;
echo $z;
}
$statement -> closeCursor();
I have a database with aproximately 200 tables. I want to clone a certain user-account in this database. Is this possible in mysql?
With cloning I mean to create a new user with the same 'settings' as the user with id 14.
A quick google search reveals that you in fact can do this. There is a utility called " "mysql user clone", that lets you surprisingly clone a user for mysql.
If you check out the manual I'm sure it provides you with great tips about how to use it, for instance, this quote:
EXAMPLES
To clone joe as sam and sally with passwords and logging in as root on the local machine, use this command:
$ mysqluserclone --source=root#localhost \
--destination=root#localhost \
joe#localhost sam:secret1#localhost sally:secret2#localhost
# Source on localhost: ... connected.
# Destination on localhost: ... connected.
# Cloning 2 users...
# Cloning joe#localhost to user sam:secret1#localhost
# Cloning joe#localhost to user sally:secret2#localhost
# ...done.
since it appears #Nanne's approach, mysqluserclone is EOL / not supported by Oracle, i wrote a similar utility in PHP, usage:
<?php
$db = new \PDO("mysql:host={$db_creds->dbhost};dbname={$db_creds->dbname};charset=utf8mb4;port=" . $db_creds->dbport, $db_creds->superuser_user, $db_creds->superuser_pass, array(
\PDO::ATTR_EMULATE_PREPARES => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
));
Mysqluserclone::clone_account($db, "original username", "cloned username");
and this part of the code may be of particular interest:
if (0) {
echo "the following SQLs will clone this account:\n";
echo implode("\n\n", $sqls_for_cloning) . "\n\n";
die();
}
<?php
class Mysqluserclone{
private function __construct(){
// by making this private, we ensure nobody try to instantiate us.
}
public static function clone_account(\PDO $db_connected_as_superuser, string $original_name, string $clone_name): void
{
$db = $db_connected_as_superuser;
$sqls_for_cloning = [];
$sql = "SELECT COUNT(*) FROM mysql.user WHERE User = " . $db->quote($clone_name);
if (0 !== $db->query($sql)->fetch(\PDO::FETCH_NUM)[0]) {
throw new \InvalidArgumentException("clone name already exists!");
}
$sql = "SELECT * FROM mysql.user WHERE User = " . $db->quote($original_name);
$current_user_one_for_each_host = $db->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
foreach ($current_user_one_for_each_host as $user_record) {
$user_record["User"] = $clone_name;
$sql = "INSERT INTO mysql.user SET \n";
foreach ($user_record as $name => $val) {
$sql .= self::mysql_quote_identifier($name) . " = " . self::mysql_quote_better($db, $val) . ",\n";
}
if (! empty($user_record)) {
$sql = substr($sql, 0, - strlen(",\n"));
}
$sql .= ";";
$sqls_for_cloning[] = $sql;
$sqls_for_cloning[] = "FLUSH PRIVILEGES;"; // YES this is required, otherwise you might get "grant not allowed to create accounts" errors
$grants_raw_sql = 'SHOW GRANTS FOR ' . $db->quote($original_name) . '#' . $db->quote($user_record['Host']) . ";";
try {
$grants_raw = $db->query($grants_raw_sql)->fetchAll(\PDO::FETCH_NUM);
} catch (\Throwable $ex) {
// somehow an empty grant table is a mysql error, not an empty rowset.. ignore it.
$grants_raw = [];
}
$grants_raw = array_map(function (array $arr): string {
if (count($arr) !== 1) {
throw new \LogicException("mysql layout for SHOW GRANTS has changed? investigate");
}
return $arr[0];
}, $grants_raw);
$original_name_as_identifier = self::mysql_quote_identifier($original_name);
$clone_name_as_identifier = self::mysql_quote_identifier($clone_name);
foreach ($grants_raw as $grant) {
if (false === strpos($grant, $original_name_as_identifier)) {
throw new \LogicException("original grant without original name as identifier? investigate");
}
$grant = self::str_replace_last($original_name_as_identifier, $clone_name_as_identifier, $grant);
$grant .= ";";
$sqls_for_cloning[] = $grant;
}
}
if (! empty($sqls_for_cloning)) {
$sqls_for_cloning[] = "FLUSH PRIVILEGES;";
}
if (0) {
echo "the following SQLs will clone this account:\n";
echo implode("\n\n", $sqls_for_cloning) . "\n\n";
die();
}
foreach ($sqls_for_cloning as $clone_sql) {
$db->exec($clone_sql);
}
}
private static function mysql_quote_identifier(string $identifier): string
{
return '`' . strtr($identifier, [
'`' => '``'
]) . '`';
}
private static function mysql_quote_better(\PDO $db, $value): string
{
if (is_null($value)) {
return "NULL";
}
if (is_int($value)) {
return (string) $value;
}
if (is_float($value)) {
return number_format($value, 10, '.', '');
}
if (is_bool($value)) {
return ($value ? "1" : "0");
}
return $db->quote($value);
}
private static function str_replace_last(string $search, string $replace, string $subject): string
{
$pos = strrpos($subject, $search);
if ($pos !== false) {
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
}
I am writing code in php to basically 'map' data from a mySQL database to another database. I am using the code as follows:
$results = $this->query("select PT_FS_DATA_ID from PATIENT_FLOWSHEET_DATA where
DT_LAST_UPDATED_TIME = (select top 1 DT_LAST_UPDATED_TIME from PATIENT_FLOWSHEET_DATA
order by DT_LAST_UPDATED TIME desc) group by PT_FS_DATA_ID;");
however, I am getting an error:
syntax error, unexpected T_VARIABLE, expecting T_FUNCTION
Everywhere I look this seems to be the correct syntax. Is there something I'm missing here?
I tried putting the controller in there as well $this->controllerName->query, but that didn't work either.
Full Code:
class CaExtraFlowsheetFields extends CaBase {
public $name = 'CaExtraFlowsheetFields';
/*
NOTE: This is to take all the fields in flowsheet and
maps their id's.
*/
//public $useTable = 'ANSWER_ENTRY';
public $useTable = 'PATIENT_FLOWSHEET_DATA';
public $primaryKey = 'PT_FS_DATA_ID';
protected function getPrimaryKeyValue(
$hospital_id,
$patient_id,
$admission_id = null
) {
return $patient_id;
}
//*CHANGE BEGIN*
$results = $this->query("select PT_FS_DATA_ID from PATIENT_FLOWSHEET_DATA where
DT_LAST_UPDATED_TIME = (select top 1 DT_LAST_UPDATED_TIME from PATIENT_FLOWSHEET_DATA
order by DT_LAST_UPDATED TIME desc) group by PT_FS_DATA_ID;");
protected $filedMethodMappings = array(
'Method_GO' => array(
CaBase::KEY_MAPPING_LOGIC_COMPLEXITY => CaBase::LEVEL2_COMPLEXITY,
CaBase::KEY_FIELD_LOGIC_NAME => 'wsMethod_GO',
);
//########################################################################//
//Note[]>Block[] //
//>Method that calls LookUpField for every field in flowsheet // //
//########################################################################//
public function wsMethod_GO ($params) {
foreach($results as $value){
$questionName = ''.$value;
$msg_prefix = $this->name . "::" . __FUNCTION__ . ": ". "arrivez-vouz" ;
$ret = $this->wsLookUpField($params,$questionName,$msg_prefix);
return $ret;
}
unset($value);
}
//########################################################################//
public function wsLookUpField($params,$questionName,$msg_prefix){
$arrayValues=array();
try{
$hospital_id = $params[Constants::KEY_HOSPITAL_ID];
$patient_id = $params[Constants::KEY_PATIENT_ID];
$admission_id = $params[Constants::KEY_ADMISSION_ID];
$msg_prefix = $this->name . "::" . __FUNCTION__ . ": ". "attendez-vouz: l'hopital= ".$hospital_id.
" patient= ".$patient_id." admission= ".$admission_id;
//shows info about given question name
$msg_prefix = "*!*!*!*Show me ---> ".$questionName." : ".$answer_entry_id.
" = aic: " .$answer_id_check;
$ret = array();
//now with needed fields, grab the A_NAME:
$params = array(
'conditions' => array(
$this->name . '.PID' => $patient_id,
$this->name . '.PT_FS_DATA_ID' => $questionName,
),
'order' => array(
$this->name . '.' . $this->primaryKey . ' DESC'
),
'fields' => array(
$this->name . '.FS_VALUE_TEXT',
)
);
$rs = $this->find('first', $params);
/* check to make sure $rs has received an answer from the query
and check to make sure this answer is a part of the most recent
database entries for this note */
if (false != $rs) {
try {
$msg = $msg_prefix . "Data obtained successfully."."<br>".$result;
$result = $rs;
$ret = WsResponse::getResponse_Success($msg, $result);
} catch (Exception $e) {
$msg = $msg_prefix . "Exception occurred.";
$ret = WsResponse::getResponse_Error($msg);
}
/*answer was not part of most recent database entries, meaning no
answer was given for this particular question the last time this
particular note was filled out. Message is given accordingly.*/
} else {
$msg = $msg_prefix . "/No answer given.";
$ret = WsResponse::getResponse_Error($msg);
}
} catch (Exception $e) {
$msg = $msg_prefix . "Exception occurred.";
$ret = WsResponse::getResponse_Error($msg);
}
return $ret;
}
Here is what you are doing:
class ABC {
$result = 'whatever';
}
You can't declare a variable there!
Code needs to be inside a method/function...
class ABC
{
public function wsMethod_GO ($params)
{
$result = 'whatever';
}
}