Replacing a string with pdo on MySQL - mysql

I want to replace a string but I use PDO. Whatever I have tried is not working. Have you ever replaced a mysql string by using PDO connection?
Here is an example which is not working.
try
{
$image = $_POST['data1'];
$id= $_POST['data2'];
$insert = "UPDATE myTable SET images=REPLACE(images,':image','') where id = :id";
$insertStmt = $conn->prepare($insert);
$insertStmt->bindValue(":image", $image);
$insertStmt->bindValue(":id", $id);
$insertStmt->execute();
echo "success";
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}

write :image instead of ':image'
$insert = "UPDATE myTable SET images=REPLACE(images,:image,'') where id = :id";

Related

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;
...
}

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

Get Btc transaction hash and send to mysql

Hello since yesterday i am trying to get the transaction hash on blockchain send many api and send to mysql but it dont works. i put to insert at mysql $txid but it give wrong results as per example "2147483647" i really thanks for any help. Below is my code.
<p>$guid="***********";
$firstpassword="**********";
$secondpassword="**************";
$amounta="3599";
$amountb="2000";
$amountc="2000";
$addressa="********";
$addressb="***********";
$addressc="******";
$recipients=urlencode('{
"'.$addressa.'": '.$amounta.',
"'.$addressb.'": '.$amountb.',
"'.$addressc.'": '.$amountc.'
}');
$json_url =
"https://blockchain.info/pt/merchant/$guid/sendmany?password=******&second_password=********&recipients=$recipients&note=********";
$json_data = file_get_contents($json_url);
$json_feed = json_decode($json_data);
$message = $json_feed->message;
$txid = $json_feed->tx_hash;
$tx = "$txid";
$servername = "localhost";
$username = "******";
$password = "*******";
$dbname = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$<font color="#FF0000">sql = "INSERT INTO payments (user_id, transaction_hash,
payment, date)
VALUES ('5331', '$txid', '4', now())";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;<br>
}
$conn->close();
?>
Lol, sorry that scrypt work very well, the problem i a set the table as INT 11, so i changed it to vachar 255 and its works well.
Thanks

change MySQL to PDO

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

Perl and DBI - Load array Problem

I am new to Perl and need some help.
In Mysql I have a table with a todo-List filled up.
At the beginning of my script, I want to add these values to "my %todo"
But I can't figure out how to do this...
Any idea?
OK, let's play martian rover though I'd rather see the code.
Do you use warnings; use strict? If not, do it. If yes, are there any warnings or errors?
If you put a print "while\n"; into your while loop, how many while's will you get on screen? How many records are there in the table?
If you use DBI, turn on exceptions: $dbh->RaiseError(1); ($dbh is you database handle here) before any operations with DB.
I don't understand why you ask for "load array" and specify a hash %todo, but if you want to read a table into memory once, you should look at the $dbh->selectall_arrayref() method.
Added: See if this get you started:
my $dsn = '...';
my $user = '...';
my $password = '...';
my $dbh = DBI->connect( $dsn, $user, $password, { RaiseError => 1, AutoCommit => 0 } );
my $sql = 'SELECT ... FROM Todo';
my %todo = ();
if (0) {
my $sth = $dbh->prepare( $sql );
$sth->execute();
while (my $aref = $sth->fetchrow_arrayref()) {
$todo{ $aref->[ 0 ] } = $aref->[ 1 ];
}
$sth->finish();
} else {
my $aref = $dbh->selectall_arrayref($sql);
for (#$aref) {
$todo{ $_->[ 0 ] } = $_->[ 1 ];
}
}
for (keys( %todo )) {
print $_, "\n", $todo{ $_ }, "\n\n";
}
my $rc = $dbh->disconnect();
use strict;
use warnings;
my $dbh = $dbh->connect;
$dbh->{RaiseError} = 1;
my $sth = $dbh->prepare(q/select id, to_do from to_do_table/);
$sth->execute;
my %todo;
while(my ($id, $to_do) = $sth->fetchrow) {
$todo{$index_column} = $to_do;
}
$dbh->disconnect;