REGEX for selecting multiple value in string - mysql

I need an sql select statement to retrieve 04:30 and test.zip from this string:
{"TIME":"04:30","DATE":"11\/25\/2013","FILENAME":["test.zip"]}

use this \[(.*?)\]
it return value between [ and ]
and for 04:30 use TIME":(.*?),
it return value after "TIME":

Can't you just decode it and use PHP? (assuming you can't change the way it's stored in the db)
<?php
$str = '{"TIME":"04:30","DATE":"11/25/2013","FILENAME":["test.zip"]}';
$o = json_decode($str);
$time = $o->TIME;
$file = $o->FILENAME[0];
var_dump($time); //"04:30"
var_dump($file); //"test.zip"
Regex replaces etc in MySQL require a UDF (user-defined function) mysql-udf-regexp
If none of the above are viable solutions (change DB structure, do it with PHP, use a MySQL UDF), you'll need to get creative. It would require a known, static format of that string, but you could replace some parts and substring others. For example:
SELECT SUBSTRING(REPLACE(`column_name`,'{"TIME":"',''),1,5) AS `time` FROM `table_name`
File is more complex, this example assuming only one filename in the array
SELECT REPLACE(SUBSTRING(`column_name`,LOCATE('"FILENAME":["',`column_name`)+13),'"]}','') AS `file` FROM `table_name`
Those two field selections get 04:30 and test.zip respectively (you can of course use those functions in the same statement, rather than separately like I have, by comma separating them)

Related

Is it possible to insert sql query in php array value?

for($count = 0; $count < count($_POST["item_sub_category"]); $count++)
{
$data = array(
':item_sub_category_id'
=> SELECT r_name FROM Repair where r_id = $_POST["item_sub_category"][$count]
);
$query = "INSERT INTO Repairlog (description,visitID) VALUES (:item_sub_category_id,'1')";
$statement = $connect->prepare($query);
$statement->execute($data);
}
As far as concerns, your code won't work. The SQL query that you are passing as a parameter will simply be interpreted as a string.
You could avoid the need for a loop by taking advantage of the INSERT INTO ... SELECT ... syntax. The idea is to generate an IN clause that contains all values that are in the array, and then run a single query to insert all records at once.
Consider:
$in = str_repeat('?,', count($_POST["item_sub_category"]) - 1) . '?';
$query = "INSERT INTO Repairlog (description,visitID) SELECT r_name, 1 FROM Repair WHERE r_id IN ($in)";
$statement = $connect->prepare($query);
$statement->execute($_POST["item_sub_category"]);
Note: it is likely that visitID is an integer and not a string; if so, then it is better not to surround the value with single quotes (I removed them in the above code).
TLDR; No.
Your question can be re-framed as: Can I write SQL code in php. The answer is NO. You can write the SQL code within a String type variable (or parameter) in php.
This is a general rule for any programming language, you cannot have multiple languages within the same file, as the language parser will not be able understand which syntax is that.
In order to embed a different language in another language, you need some kind of separator that will define when the new language or special type will start and when it will end.

Perl / DBI query doesn't preserve integer values for JSON output

I can't get this Perl code to return true integer values for integers in the table. The MySQL table columns are correctly specified as integers, yet the JSON output here wraps all query values in quotes. How can I correctly preserve data-types (esp. integers and boolean values) as specified?
use strict;
use warnings;
use DBI;
use JSON;
my $sth = "SELECT id, name, age FROM table";
my $data = $dbh->selectall_arrayref($sth, {Slice => {}});
my $response = encode_json($data);
print $response;
## outputs: {"id":"1","name":"Joe Blodge","age":"42"}
What am I doing wrong here? How can I get this to output the correctly formatted JSON:
{"id":1,"name":"Joe Blodge","age":42}
DBD::mysql returns all results as strings (see https://github.com/perl5-dbi/DBD-mysql/issues/253). Normally Perl doesn't care, encoding to JSON is one of the few times when it matters. You can either use Cpanel::JSON::XS::Type to provide type declarations for your JSON structure:
use Cpanel::JSON::XS;
use Cpanel::JSON::XS::Type;
my $response = encode_json($data, {id => JSON_TYPE_INT, name => JSON_TYPE_STRING, age => JSON_TYPE_INT});
or you can go through and numify the appropriate elements before JSON encoding.
$data->{$_} += 0 for qw(id age);
It is possible to check the type (as indicated by MySQL) of each returned column, if you construct and execute your query using a statement handle then the type will be available as an array in $sth->{TYPE}, but this is pretty complex and may not be reliable.

MySQL: SQL to insert rows using a string of ids

I need to insert ~150 simple rows (an id, and a static status of 'discard'). I have a string of the ids:
'123', '234r', '345', '456xyz'...
What's the simplest way to insert rows using this string of ids?
It seems like maybe there's some way to split the string on commas and... create a temp table to ...? I don't know - it just seems like this is the kind of thing that MySQL often manages to pull off in some cool, expedient way.
An example how to do create an INSERT statement with a few lines of PHP:
<?php
// copy your string of ids into this variable
$input = "'123', '234r', '345', '456xyz'";
// modify next line to get your desired filename
$filename = 'insert.sql'
// modify next line to your table name
$insert_statement = "INSERT INTO your_table_name (id, status) VALUES \n" .
'(' . implode(", 'discard')\n(", explode(', ', $input)) . ", 'discard');\n";
file_put_contents($filename, $insert_statement);
?>
Note
This is for this special use case. If the string of ids contains some special characters like single quotes, then this simple approach will fail.
The one way is to create CSV file with appropriate records and upload it at once to mysql.
Please follow this tutorial: http://www.mysqltutorial.org/import-csv-file-mysql-table/

Getting the max row character length in a query using Perl DBI Mysql

Using: Perl v5.10.1, MySQL 5.5.15, DBI.
I need to deliver end users output from a database via email. They do not want this as an attachment, but in the body.
I'd like to deliver the data in an ascii table and am having issues determining if DBI has built in functions to do this (output similar to querying MySQL from the command line).
Or If I can determine the longest row character length I can use that to build the table. I have a way to get the max item length in an array, but I can't wrap my head around doing it with the query results.
my $spacer_length = (reverse sort { $a <=> $b } map { length($_) } #array)[0];
Assuming a generic DBI loop, you could do something like this:
use List::Util qw(max);
...
my #output;
my $max;
while (my #foo = $dbi->fetchrow_array) {
$max = max($max // (), map length, #foo);
push #output, \#foo; # save data for email attachment
}
Using the "defined-or" operator // to avoid an undef warning and possible contamination in case of negative values.
I'm not sure exactly what you're asking for, but if you're looking for the "max row character length" for a given column of a query result, you can do that with SQL:
SELECT MAX(CHAR_LENGTH(col1)) FROM t1
or if you want all of the rows sorted by the length of the values of col1:
SELECT col1,col2 from t1 ORDER BY CHAR_LENGTH(col1) DESC
you can execute these queries using DBI like this:
# $mysql is your DBI connection info
my $query = $mysql->prepare("SELECT col1,col2 from t1 ORDER BY CHAR_LENGTH(col1) DESC");
$query->execute();
and then iterate through the result rows:
while ( my #result = $query->fetchrow_array ) {
my ($col1,$col2) = #result;
# do stuff with the values
}
and you can print the values as you wish, including like the output from the command line mysql client.

CodeIgniter - implode/query binding causing unwanted string

I have the following query attempting an update in CodeIgniter:
$sql = "UPDATE fanout.manual_data
SET call_leader_id = ?
WHERE id IN (?)";
$q = $this->db->query($sql, array($leaderID, implode(", ", $empIDs)));
The implode is creating a string of all the IDs in my array. However, that is resulting in the query looking like:
UPDATE fanout.manual_data SET call_leader_id = '55993' WHERE id IN ('57232, 0097726, 0076034');
When what I need is:
UPDATE fanout.manual_data SET call_leader_id = '55993' WHERE id IN (57232, 0097726, 0076034);
Only difference, is the single quotes surrounding the string of IDs. Is this something I need to do myself and skip over CI's query bindings (http://codeigniter.com/user_guide/database/queries.html) or is something CI can handle and I'm just missing a step?
Thanks.
I don't think you can skip that behavior. You're technically passing a string, so CI interprets it as such and simply surrounds it with quotes.
I think you're better off simply concatenating the $empIDs by hand (e.g. using a foreach loop), escaping them with $this->db->escape() in case you wanna be sure.