MySQL Search & Replace with WILDCARDS - Query - mysql

Is it possible to perform a MySQL search and replace while honoring wildcards?
eg:
$search = "id='%wildcard%-houselisting-rental'>";
$replace = "class='house_rentals'>";
$query = "UPDATE tables SET field = replace(field,'$search','$replace')";
$result = mysql_query($query);
I appreciate any advise on the subject
-h

I found out this wasn't possible for mysql.

Related

Is this Doctrine query SQL injection-proof?

I saw this (Symfony) Doctrine query. Is this SQL injection-proof?
$input = $_GET['input'];
$query = $connection->createQueryBuilder();
$query->select('id')->from('table')->where('name = ' . $input); // does Doctrine escape this input?
$statement = $query->execute();
var_dump($statement->fetchAll());
It is not. You have to use prepared queries with parameters. Something along thoses lines :
$input = $_GET['input'];
$query = $connection->createQueryBuilder();
$query->select('id')->from('table')->where('name = :input');
$query->setParameter('input', $input)
...

MySqlClient cannot use ':=' (Set Operator) [duplicate]

I simply want to execute the following Mysql statement
SET #a = 1;SELECT #a;
with MySql.Data.MySqlClient
[System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
$password = 'mypassword'
$sql = "SET #a = 1;SELECT #a;"
$server = 'localhost'
$port = 3306
$database = 'test'
$User = 'root'
$conn=new-object MySql.Data.MySqlClient.MySqlConnection
$connectionstring = "Server=$Server;Port=$port;Database=$DataBase;Uid=$User;Pwd=$Password;allow zero datetime=yes"
$conn.ConnectionString = $connectionstring
$conn.Open()
$cmd=new-object MySql.Data.MySqlClient.MySqlCommand($sql,$conn)
$ds=New-Object system.Data.DataSet
$da=New-Object MySql.Data.MySqlClient.MySqlDataAdapter($cmd)
$da.fill($ds)
$conn.close()
$ds.tables[0]
I get a fatal error.
When I replace $sql by either
$sql = "SELECT DATABASE();"
or
$sql = "SELECT 1;"
I get the expected result.
I found this question, but it doesn't solve my problem.
I'm trying to port SQLIse (a part of the SQLPSX project ) to the MySQL version MySQLIse.
I want to process any simple valid mysql statements.
EDIT:
I was trying to run parts of the sakila-schema.sql the mysql demo database install script which runs by something like
mysql> SOURCE
C:/temp/sakila-db/sakila-schema.sql;
I found the solution in this blog
I have to add
;Allow User Variables=True
to the connection string:
$connectionstring = "Server=$Server;Port=$port;Database=$DataBase;Uid=$User;Pwd=$Password;allow zero datetime=yes;Allow User Variables=True"
works. I tested it with version 6.3.6.0. of MySql.Data.

perl script to connect two databases at same time

I am trying to connect to 2 databases on the same instance of MySQL from 1 Perl script.
I am using this in a migration script where I am grabbing data from the original database and inserting it into the new one.
Connecting to 1 database and then trying to initiate a second connection with the same user just changes the current database to the new one.
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "mysql";
my $database1 = "db1";
my $dsn1 = "DBI:$driver:database=$database1";
my $userid = "userhead";
my $password = "pwdhead";
my $database2 = "db2";
my $dsn2 = "DBI:$driver:database=$database2";
my $dbh1 = DBI->connect($dsn1, $userid, $password ) or die $DBI::errstr;
my $dbh2 = DBI->connect($dsn2, $userid, $password ) or die $DBI::errstr;
my $sth = $dbh2->prepare("INSERT INTO Persons") $dbh1->prepare("SELECT *FROM Persons");
$sth->execute() or die $DBI::errstr;
print "Number of rows found :" + $sth->rows;
In the above example i am trying to copy from one database table to another datbase table. but i am getting error while running the script. Please help me out
At a guess, you're trying to use the same database handle to connect to both databases. If you need to operate two separate connections then you need two separate handles
This program uses the data_sources class method to discover all of the available MySQL databases and creates a connection to each of them, putting the handles in the array #dbh. You can use each element of that array as normal, for instance
my $stmt = $dbh[0]->prepare('SELECT * FROM table)
It may be that you prefer to set up the #databases array manually, or the username and password may be different for the two data sources, so some variation on this may be necessary
use strict;
use warnings 'all';
use DBI;
my $user = 'username';
my $pass = 'password';
my #databases = DBI->data_sources('mysql');
my #dbh = map { DBI->connect($_, $user, $pass) } #databases;
Update
You need to select data from the source table, fetch it one row at a time, and insert each row into the destination table
Here's an idea how that might work, but you need to adjust the number of question marks in the VALUES of the INSERT statement to match the number of columns
Note that, if you're just intending to copy the whole dataset, there aree better ways to go about this. In particular, if you have any foreign key constraints then you won't be able to add data until the table it it is dependent on is populated
#!/usr/bin/perl
use strict;
use warnings 'all';
use DBI;
my $userid = "userhead";
my $password = "pwdhead";
my ($dbase1, $dbase2) = qw/ db1 db2 /;
my $dsn1 = "DBI:mysql:database=$dbase1";
my $dsn2 = "DBI:mysql:database=$dbase2";
my $dbh1 = DBI->connect($dsn1, $userid, $password ) or die $DBI::errstr;
my $dbh2 = DBI->connect($dsn2, $userid, $password ) or die $DBI::errstr;
my $select = $dbh1->prepare("SELECT * FROM Persons");
my $insert = $dbh2->prepare("INSERT INTO Persons VALUES (?, ?, ?, ?, ?)");
$select->execute;
while ( my #row = $select->fetchrow_array ) {
$insert->execute(#row);
}
If you need to handle the columns from the source data separately then you can use named scalars instead of the array #row. Like this
while ( my ($id, $name) = $select->fetchrow_array ) {
my $lastname = '';
$insert->execute($id, $name, $lastname);
}
Plan A (especially if one-time task):
Run mysqldump on the source machine; feed the output to mysql on the target machine. This will be much faster and simpler. If you are on a Unix machine, do it with an exec() from Perl (if you like).
Plan B (especially if repeated task):
If the table is not "too big", do one SELECT to fetch all the rows into an array in Perl. Then INSERT the rows into the target machine. This can be sped up (with some effort) if you build a multi-row INSERT or create a CSV file and use LOAD DATA instead of INSERT.

How do I convert a simple bit of MySQL to pdo

I know nothing about MySQL let alone PDO and am struggling to convert something to PDO.
I have tried everything I can by copying code from other bits of the script but can't get anything to work and knowing absolutely nothing about MySQL let alone PDO does not help in fact MySQL seems a heck of a lot easier to say the least.
I want is this very simple bit of MySQL to work as PDO.
$query = " UPDATE " . $DBPrefix . "settings SET
logo = '" . $_FILES['logo']['name'] . "' ";
$system->check_mysql(mysql_query($query), $query, __LINE__, __FILE__);
$system->SETTINGS['logo'] = $_FILES['logo']['name'];
First you need to create new PDO() object. Something like this:
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
$pdo = new PDO($dsn, $user, $pass, $opt);
Next your code will transform to:
$sql = "UPDATE {$DBPrefix}settings SET logo = '{$_FILES['logo']['name']}'";
$result = $pdo->query($sql);
But this is not a good practice to just write SQL manually, wrapping and escaping all params. Better way using prepared statements, it'll wrap and escape all params automatically:
$ps = $pdo->prepare("UPDATE {$DBPrefix}settings SET logo = :logo");
$ps->execute(['logo' => $_FILES['logo']['name']]);
you should put . after db prefix:
$query = " UPDATE " . $DBPrefix . ".settings SET
logo = '" . $_FILES['logo']['name'] . "' ";
$system->check_mysql(mysql_query($query), $query, __LINE__, __FILE__);
$system->SETTINGS['logo'] = $_FILES['logo']['name'];

Mysql update with ' symbol in variable

i have mysql query like this
mysql_query("UPDATE services SET sub_service='".$subbb_service."' WHERE sub_service='".$idd."' ") or die(mysql_error());
variable $subbb_service is with symbol '. Lets say it Hello' . So it fails query couse it looks like this
mysql_query("UPDATE services SET sub_service=' Hello'' WHERE sub_service='".$idd."' ") or die(mysql_error());
Now it has double '' and it dies. Maybe anyone could help me out?
Use mysql_real_escape_string:
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));