Laravael4 db raw query using ON DUPLICATE KEY UPDATE drops error - mysql

I'm really fighting with a laravel ON DUPLICATE KEY UPDATE query I can't get it to work, so the query basically looks like
foreach ($queries as $query) {
$update_time = array('update_time' => date('Y-m-d H:i:s'));
$query = array_merge($update_time, $query);
$keysString = implode(", ", array_keys($query));
$indexes = "";
$values = "";
$updates = "";
foreach ($query as $i=>$v){
$values .= ':'.$v.',';
$updates .= $i.'="'.$v.'",';
}
//$holder = rtrim(str_repeat('?,', count($query)),',');
$updates = rtrim($updates,',');
DB::statement("INSERT INTO products ({$keysString}) VALUES ({rtrim($values,',')}) ON DUPLICATE KEY UPDATE {rtrim($updates,',')}")
}
but I get
SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters
How do I make a prepared statement in laravel4 for raw queries?

By default Laravel binds its data using ? and you are binding your data with :foo, meaning there is a mixture of the two approaches and PDO is getting sad about it.
PDO: Invalid parameter number: mixed named and positional parameters
Something like this should get you going in the right direction:
foreach ($queries as $query) {
// Add the update time without merging stuff
$query['update_time'] = date('Y-m-d H:i:s');
// How many bits of data do we have
$bindingCount = count($query);
// Same as before, just get the keys
$keyString = implode(", ", array_keys($query));
// Start off a bindings array with just the values
$bindings = array_values($query);
$updates = [];
foreach ($query as $field => $value){
$updates[] = "{$field} = ?";
$bindings[] = $value;
}
$valueString = implode(',', array_fill(0, $bindingCount, '?'));
$updateString = implode(',', $updates);
DB::statement("INSERT INTO products ({$keyString}) VALUES ({$valueString}) ON DUPLICATE KEY UPDATE {$updateString}", $bindings);
}

Related

How to retrieve composite column from Cassandra table in PHP

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(...).

Fetch 2 values using selectrow_array in Perl

I recently figured that there is a selectrow_array function to fetch values from databases. I'm getting following error when I'm using it. I wonder what is the issue here and couldn't find an alternative way to do this.
Code is:
my $db_connection = DBI->connect($dsn, $dbuser, $dbpassword ) or die $DBI::errstr;
my $sql_statement = "SELECT customer_id,quota FROM customer_call_quota WHERE quota>=1";
while (my $row = $db_connection->selectrow_array($sql_statement)) {
my ($cust_id, $quota) = #$row; #<---- error line
}
my $rc = $db_connection->disconnect ;
return "ok";
Error:
Can't use string ("value") as an ARRAY ref while "strict refs" in use at code.pl line ...
Two problems.
selectrow_array doesn't return a reference to an array. That's selectrow_arrayref.
selectrow_* only returns the first row.
Solutions:
# Wasteful
my $sth = $dbh->prepare($sql_statement);
$sth->execute();
while (my #row = $sth->fetchrow_array()) {
my ($cust_id, $quota) = #row;
...
}
or
my $sth = $dbh->prepare($sql_statement);
$sth->execute();
while (my ($cust_id, $quota) = $sth->fetchrow_array()) {
...
}
or
my $sth = $dbh->prepare($sql_statement);
$sth->execute();
while (my $row = $sth->fetch()) {
my ($cust_id, $quota) = #$row;
...
}

show tables get only the last name of table

I'm trying to show the name of table in my database. I write this code :
function affiche_liste()
{
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
$tableList = $data[0];
}
return $tableList;
}
It give to me only the last table ?
For a simple query without parameters and the SQL hard coded you can use a generic function passing the connection and SQL to the function.
The following function () returns an array containing all rows in the result set.
function queryAll($db,$query){
$sth = $db->query($query);
$result = $sth->fetchAll(PDO::FETCH_NUM);
return $result;
}
For a simple query without parameters and the SQL hard coded you can use a generic function passing the connection and SQL to the function.
The following function () returns an array containing all rows in the result set.
function queryAll($db,$query){
$sth = $db->query($query);
$result = $sth->fetchAll(PDO::FETCH_NUM);
return $result;
}
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SHOW TABLES";
$tables = queryAll($db,$query);
print_r($tables);
Each time you are looping through the results, your are overwriting the variable tableList. Instead, you need to append to an array of results.
function affiche_liste()
{
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
$tableList = array();
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
array_push($tableList, $data[0]);
}
return $tableList;
}
try this
`
function affiche_liste()
{$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
$tableList[] = $data[0];
}
return $tableList;
}
`
i hope it'll work...
here your array is overwitting every time...that's the reason you were getting the last table name....so you need to append to the existing array...

Find how many times every word is repeated in db

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);

Kohana - Insert record with ignore duplicate

How to implement "insert ignore"? using kohana orm While adding multiple records, if few of them may already exist in database using below code adding of all 100 records will be declined.
$query = DB::insert('tablename', array('column1', 'column2','column3'));
foreach ($data as $d) {
$query->values($d);
}
try {
$result = $query->execute();
} catch ( Database_Exception $e ) {
echo $e->getMessage();
}
UPDATE:
Here is how i did This, i have to insert multiple records,
$Xtransactions = "INSERT IGNORE INTO `tablename` (`tid`, `tdate`, `appid`,
`userid`, `user_ip`) VALUES";
foreach ($objSas->trecord as $trow) {
$Xtransactions .= "(".$trow->tid.",'".
date('Y-m-d H:i:s', strtotime($trow->tdate))."',".
$trow->userid.",".
$trow->Xnumber.",'".
$trow->ip."'),";
}
$Xtransactions = substr($Xtransactions , 0, -1);
try {
DB::query(Database::INSERT, $Xtransactions )->execute();
} catch ( Database_Exception $e ) {
echo $e->getMessage();
}
With query builder this is impossible, try to write a raw query.
DB::query(Database::INSERT, 'INSERT IGNORE INTO table VALUES (...)')->execute();
I usually collect such modifications in static helper class, for example
<?php defined('SYSPATH') or die('No direct script access.');
class Helper_DB_Query{
/**
* #param Database_Query_Builder_Insert $insert query thant need to be converted
* #return Database_Query converted query
*/
public static function insert_to_insert_ignore( Database_Query_Builder_Insert $insert ){
$insert = (string) $insert;
$query = preg_replace("/^INSERT(.*)$/", "INSERT IGNORE $1", $insert);
return DB::query(Database::INSERT, $query);
}
}