Loop in database using perl - mysql

I need to extract each character from the input (input are numbers) and check it against my database, if the number is present the corresponding rows will be printed. But in my code the loop doesn't work and only the first character is printed.
use dbi;
my $seq=<stdin>;
my $r=my$seq;
my $db="hnf1a";
my $user="root";
my $password="";
my $host="localhost";
my $dbh = DBI->connect("DBI:mysql:database=$db:$host",$user,$password);
my #w= split(//, $r);
print #w;
foreach my $b(#w)
{
my $sth=$dbh -> prepare("select an,ano from mody having ano = '$b' ");
my $rv=$sth->execute();
while (my #row =$sth->fetchrow_array())
{
print #row;
}
}
my $rc=my $sth->finish;
}
print "database closed";`

Database:
mysql> select * from mody;
+----+---------+------+
| id | an | ano |
+----+---------+------+
| 1 | 123 | 456 |
| 2 | abc | 567 |
| 3 | hello | 5 |
| 4 | world | 5 |
| 5 | goodbye | 6 |
+----+---------+------+
5 rows in set (0.00 sec)
Code:
use strict;
use warnings;
use 5.020;
use autodie;
use Data::Dumper;
use DBI;
my $dsn = 'dbi:MariaDB:database=my_db;host=localhost';
my $dbh = DBI->connect($dsn, 'root', '');
my $sth = $dbh->prepare('SELECT an,ano FROM mody where ano = ?');
my $input = "56";
my #numbers = split //, $input;
for my $number(#numbers) {
say "rows matching input <$number>:";
$sth->execute($number);
while(my #data = $sth->fetchrow_array) {
say "\t#data";
}
};
Output:
rows matching input <5>:
hello 5
world 5
rows matching input <6>:
goodbye 6

Related

Export data from SQL to CSV with modified format

Suppose I have a table in SQL named 'myTable'. It contains 3 columns; 'id', 'lat' and 'lng'
| id | lat | lng |
|------+--------+--------|
| 1 | 1.11 | 1.22 |
| 2 | 2.11 | 2.22 |
| 3 | 3.11 | 3.22 |
| 4 | 4.11 | 4.22 |
| .... | .... | .... |
I want to export it to CSV. I expect the result become like this in the CSV file :
| | A | B | C | D | ....
------+-----+------+--------+------+--------
| 1 | 1.11 | 2.11 | 3.11 | 4.11 | .... //contains 'lat'
| 2 | 1.22 | 2.22 | 3.22 | 4.22 | .... //contains 'lng'
Can you help me? I'm using PHP. Thanks a lot.
This might actually be something which would be best handled in your PHP script, rather than in MySQL. Assuming your are using mysqli, you could try something like this:
$sql = "SELECT id, lat, lng FROM yourTable ORDER BY id";
$result = $conn->query($sql);
$row1 = NULL;
$row2 = NULL;
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($row1 != NULL) {
$row1 .= ",";
$row2 .= ",";
}
$row1 .= $row["lat"];
$row2 .= $row["lng"];
}
}
At the end of the loop in the above script, $row1 and $row2 should contain the first two rows of the output file you expect. The only steps missing might be the header, if you want that, and also the details of how to write a string to a text file.

how to tokenize string in record to be row

I have the data in a database table named term like this :
---------------------------------------
id_term | keyword |
------- | -----------------------------
1 | how to make search engine |
2 | application engineering |
3 | android application example |
--------------------------------------
then I want it to be like this table :
----------------------------------
| id_term | keyword |
----------------------------------
1 | how |
1 | to |
1 | Make |
1 | search |
1 | engine |
2 | application |
2 | engineering |
3 | example |
3 | application |
3 | android |
----------------------------------
I've tried googling to find references to split the string, but still have not found the appropriate expectations. In an experiment that I've done using substring_index results I could actually like this:
---------------------------------------
id_term | keyword |
------- | -------------------------------
1 | how to make search engine |
1 | how to make search engine |
1 | how to make search engine |
--------------------------------------
there anything you can help me or has the solution of my problem? mysql code that I try something like this:
select term.id_kata, SUBSTRING_INDEX (SUBSTRING_INDEX (term.keyword, ',', term.id_kata), ',', -1) keyword term from inner join keyword_doc on CHAR_LENGTH (term.keyword) -CHAR_LENGTH (REPLACE (term.keyword , ',', ''))> = term.id_kata-1 ORDER BY `term`.`keyword` DESC
I've tried googling for approximately 5 hours to find a solution, but have not found until I was confused to be asked where. there any ideas or can help provide a solution?
The solution for it problem is please take 'BETWEEN' in SQL SYNTAX. this code 100% work for it problem :
<?php
#connection
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'pasword';
$dbname = 'yourdatabasename';
error_reporting(E_ALL ^ E_DEPRECATED);
mysql_connect($dbhost,$dbuser,$dbpass) or die(mysqli_error('cannot connect to the server'));
mysql_select_db($dbname) or die(mysqli('database selection problem'));
$frequency = array();
$datastring = 'SELECT id_term,keyword FROM data_token WHERE id_term BETWEEN 1 AND 3';
mysql_select_db('yourdatabasename');
$calldata = mysql_query($datastring);
while($takedata = mysql_fetch_array($calldata,MYSQL_ASSOC))
{
$array = explode("\n",$takedata['keyword']);
foreach ($array as $index => $keyword)
{
if(! array_key_exists($keyword,$frequency))
{
$frequency[$keyword] = 1;
}
else
{
$frequency[$keyword] = $frequency[$keyword] + 1;
}
}
$document = $takedata['id_term'];
foreach ($frequency as $term => $tf)
{
$sqlInput = "INSERT INTO yourtablename (id_term,keyword,frequency) VALUES ('$dokumen','{$term}', {$tf})";
mysql_query($sqlInput);
}
}
?>

Get distinct values from a comma-delimited column and insert in another table in mysql

I have a column in a MySQL table that consists of comma-separated values in a column and there various duplicate values in the same column. data look like below-
select id,category_ids from tableName;
+---------+-----------------------+
| id | category_ids |
+---------+-----------------------+
| 1062810 | 4,7,2,2,2,2,4,7 |
| 1062812 | 4 |
| 1062814 | 7,7,7,7,7,7,7,7 |
| 1062850 | 2,2,2,2,2,2,2,2,2,2,2 |
| 1063294 | 6,6,6,6,6,6,6,6,6,6,6 |
and Out put should be
+---------+-----------------------+
| id | category_ids |
+---------+-----------------------+
| 1062810 | 4,7,2 |
| 1062812 | 4 |
| 1062814 | 7 |
| 1062850 | 2 |
| 1063294 | 6 |
Please help me out I'm new to mysql
Try this:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select id,category_ids from tableName";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row["id"];
$category_ids = array_unique(explode(',',$row["category_ids"]));
$update_sql = "update tableName category_ids='".implode($category_ids,',')."' where id = ".$id ;
$res = $conn->query($update_sql,$conn);
echo "Update ID-".$id." Category ids:" .$row["category_ids"]. " Into " . implode($category_ids,','). "<br>";
}
} else {
echo "No data in your table";
}
$conn->close();

Why does SELECT FOR UPDATE works only within a transaction?

I think I am confused with the SELECT FOR UPDATE construct.
Example:
mysql> select * from employees2;
+-------+----------+--------+-----------+
| EmpId | EmpName | DeptId | EmpSalary |
+-------+----------+--------+-----------+
| 1 | John | 1 | 5000.00 |
| 2 | Albert | 1 | 4500.00 |
| 3 | Crain | 2 | 6000.00 |
| 4 | Micheal | 2 | 5000.00 |
| 5 | David | NULL | 34.00 |
| 6 | Kelly | NULL | 457.00 |
| 7 | Rudy | 1 | 879.00 |
| 8 | Smith | 2 | 7878.00 |
| 9 | Karsen | 5 | 878.00 |
| 10 | Stringer | 5 | 345.00 |
| 11 | Cheryl | NULL | NULL |
+-------+----------+--------+-----------+
11 rows in set (0.00 sec)
I do the following in a script:
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
my $dbh = DBI->connect('dbi:mysql:testdb','root','1234', {'RaiseError' => 1, 'AutoCommit' => 0}) or die "Connection Error: $DBI::errstr\n";
my $sql = "select * from employees2 where EmpId IN (2,10) for update";
my $sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
while (my #row = $sth->fetchrow_array) {
print "#row\n";
}
sleep(9000);
$dbh->commit;
I also in parallel a console and connect to the database.
So I run the script first and then in another session I do:
mysql> select * from employees2 where EmpId IN (10) for update;
The second select blocks as it refers to the same row.
This blocks either I do:
mysql> set autocommit = 0;
mysql> begin;
mysql> select * from employees2 where EmpId IN (10) for update;
mysql> commit;
or just
mysql> select * from employees2 where EmpId IN (10) for update;
So it blocks irrelevant if it is in a transaction or not.
Now if I change the script as:
my $dbh = DBI->connect('dbi:mysql:practice','root','') or die "Connection Error: $DBI::errstr\n";
I.e the script does not run within a transaction the second session does not block!
Why does it block only if the script runs within a transaction?
According to the documentation:
Locking of rows for update using SELECT FOR UPDATE only applies when autocommit is disabled (either by beginning transaction with START TRANSACTION or by setting autocommit to 0. If autocommit is enabled, the rows matching the specification are not locked.
In other words, if you don't execute your first SELECT FOR UPDATE inside a transaction, no rows are locked.

how to fetch multiple rows with same field value from a mysql database using php

|touser| fromuser | msg |
| A | B | hi |
| A | B | hello |
| C | D | bye |
| C | E | hey |
when i use following query in mysql workbench it shows the desired result that is all the rows with given name:
select * from db.table1 where touser in ('A');
output:
|touser| fromuser | msg |
| A | B | hi |
| A | B | hello |
but when i pass query from php commands the resultant array contains only first record
<?php
//connection establishing commands
$sql="select * from db.table1 where touser in ('A')";
$result=mysqli_query($link, $sql);
$data=mysqli_fetch_array($result,MYSQLI_NUM);
print_r($data);
//other stuff;
?>
output:
Array ( [0] => A [1] => B [2] => Hi )
am I missing something in the php commands?
You're PHP is simply returning the first row of the MySQL result set.
You'll want to replace $data=mysqli_fetch_array($result,MYSQLI_NUM);
with
while ($data = mysqli_fetch_array($result, MYSQLI_NUM)) {
print_r($data);
}
Which will iterate over each row of the result set. In other words, the mysqli_fetch_array function doesn't fetch the entire result set as an array, it simply returns a single row, and then moves the row "pointer" to the next row.