insert value txt file into mysql laravel 6 - mysql

how can I insert value from my input file.txt like this to MySQL, these [example image] (https://i.stack.imgur.com/v16fi.png).
and I just need atm_id, name_atm, ip, and status agent_connection
my code is like
` $data = $request->file('file');
$filetmp = $data->getRealPath();
$filedata = file_get_contents($filetmp);
$lines = explode("\n", $filedata);
$lines=array_slice($lines,
array_keys(
array_filter($lines,
function($item){
return strpos($item,'PAR') ;
}))[0]
);
$arrays = array_map(function($array) {
$columns = ['atm_id', 'name_atm', 'ip', 'agent_connection',];
return array_combine($columns, array_map('trim', $array));
}, array_chunk($lines, 5));
dd($arrays);`
I expect I can insert just
atm_id = AT8502 atm_name = example ip = 10.51.7.50 agent_connection = complete
as much as data on txt file.

Related

How to update table in redbeanphp

Here is my function Insert.
What should i write after findOne to UPDATE the table. If field name exist update all other fields.
function insert_data_score($name, $clickcountscore, $levelofitems, $bonuscounter, $date, $timeofcasinobutton, $timeofcasinovideo){
$repeatChecker = R:: findOne('clicker', 'name = ?', array ($name));
if (isset($repeatChecker))
// ????????
return " User $name exist";
$scoreboard = R::xdispense( 'clicker' );
$scoreboard->name = $name;
$scoreboard->clickcountscore = $clickcountscore;
$scoreboard->levelofitems = $levelofitems;
$scoreboard->bonuscounter = $bonuscounter;
$scoreboard->date = $date;
$scoreboard->timeofcasinobutton = $timeofcasinobutton;
R::store($scoreboard);
return "User: $name, created";
$repeatChecker->clickcountscore = $clickcountscore;
$repeatChecker->levelofitems = $levelofitems;
$repeatChecker->bonuscounter = $bonuscounter;
$repeatChecker->date = $date;
$repeatChecker->timeofcasinobutton = $timeofcasinobutton;
$repeatChecker->timeofcasinovideo = $timeofcasinovideo;
R::store($repeatChecker);
return " User $name Updated";
all wokrs if add this code after "if"

Import CSV in Mysql does not work

I like to write a csv import / update to my Mysql database, but it isnt working. I get no error messages.
Can anybody help me to find the error or whats wrong with my script please.
// set local variables
$connect = mysql_connect("localhost","root","") or die('Could not connect: ' . mysql_error());
$handle = fopen("imptest.csv", "r");
// connect to mysql and select database or exit
mysql_select_db("shoptest1", $connect);
while($data = fgetcsv($handle, 30000, ';')) //Jede Zeile durchgehen
{
$Product_ID=$data[0];
$field=$data[1];
$query = 'SELECT Product_ID FROM testprod';
if (!$result = mysql_query($query)) {
continue;
} if ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
// entry exists update
$query = "UPDATE ps_product_lang SET custom_field ='$field' WHERE id_product = '$Product_ID'";
mysql_query($query);
if (mysql_affected_rows() <= 0) {
echo "kein update";
// no rows where affected by update query
}
} else {
echo "kein eintrag";
// entry doesn't exist continue or insert...
}
mysql_free_result($result);
}
fclose($handle);
mysql_close($connect);
?>
The queries you are performing:
SELECT Product_ID FROM testprod
UPDATE nl_product_lang SET custom_field = ? WHERE Product_ID = ?
are suitable to detect whether a product exists and then either UPDATE or INSERT. For only an UPDATE, the SELECT doesn't matter, as there won't be an entry WHERE Product_ID NOT IN (SELECT Product_ID FROM testprod) - if you have a foreign key.
Here's an example of how to do this using PDO.
list( $SQLDSN, $SQLUSER, $SQLPASS ) = [ 'mysql:dbname=shoptest1', 'root', '' ];
$db = new PDO( $SQLDSN, $SQLUSER, $SQLPASS, [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
] );
$ids = $db->query( "SELECT Product_ID from testprod" )->fetchAll( \PDO::FETCH_COLUMN, 0 );
while ( list( $Product_ID, $field ) = fgetcsv(...) )
if ( in_array( $Product_ID, $ids ) )
query( $db, "UPDATE ps_product_lang SET custom_field = ? WHERE Product_ID = ?",
[ $field, $Product_ID ]
);
else
trigger_warning( "unknown product $Product_ID" );
function query( $db, $sql, $args = null ) {
$sth = $db->prepare( $sql );
$sth->execute( $sql );
return $sth;
}

SQL UPDATE Not Updating

After uploading a csv file, I am trying to insert its contents into my database table. I have this query:
$connect = mysql_connect("localhost","root","");
mysql_select_db("dbtest",$connect);
//get the file
$handle = fopen($filename,"r");
do {
if (isset($data[0])) {
$data0 = mysql_real_escape_string($data[0]); //rcode
$data1 = mysql_real_escape_string($data[1]); //pcode
$data2 = mysql_real_escape_string($data[2]); //mcode
$data3 = mysql_real_escape_string($data[3]); //bcode
$data4 = mysql_real_escape_string($data[4]); //ecode
$data5 = mysql_real_escape_string($data[5]); //filetype
$data6 = mysql_real_escape_string($data[6]); //rec_count
$data7 = mysql_real_escape_string($data[7]); //gen_count
$data8 = mysql_real_escape_string($data[8]); //qc_count
$data9 = mysql_real_escape_string($data[9]); //be_count
$data10 = mysql_real_escape_string($data[10]); //trn_count
$query = "INSERT INTO tbltest(rcode,pcode,mcode,bcode,ecode,filetype,rec_count,
gen_count,qc_count,be_count,trn_count) VALUES ('$data0','$data1','$data2',
'$data3', '$data4', '$data5', '$data6', '$data7', '$data8', '$data9', '$data10')
ON DUPLICATE KEY UPDATE rec_count=values(rec_count),gen_count=values(gen_count),
qc_count=values(qc_count), be_count=values(be_count), trn_count=values(trn_count)";
mysql_query ($query,$connect) ;
}
} while ($data = fgetcsv($handle,1000,"|"));
And it's working neatly but then as the database was re-structured, I just then need to update the database table as rcode to filetype has values already and I just need to insert values of rec_count to trn_count. So my first query INSERT INTO ... ON DUPLICATE KEY UPDATE has been change to UPDATE only. And so I did this:
$query = "UPDATE tbltest SET (rec_count='$data6', gen_count = '$data7',
qc_count = '$data8', be_count = '$data9', trn_count= '$data10') WHERE
(rcode = '$data0', pcode = '$data1', mcode = '$data2', bcode = '$data3',
ecode = '$data4', filetype = '$data5')";
My problem now is that, my UPDATE seems to be not working as it doesn't update the database table. Bu when I did this;
$query = "UPDATE tbltest SET rcode = '5'";
The database is being updated. When I tried echo $query;, the echo responds the correct data (from the csv). I just cannot figure why it doesn't insert these data into the database. Kindly help. Thanks
Your SQL syntax is incorrect. The statement should read something like
UPDATE tbltest
SET rec_count='...', gen_count = '...', ...
WHERE rcode = '...' AND pcode = '...' AND ...
See MySQL UPDATE syntax.

Zend db update value not being set

I'm not sure what's missing with this update call, here's my code:
$table = new Application_Model_DbTable_ProductContaminant();
$db = $table->getAdapter();
$db->getProfiler()->setEnabled(true);
$data = array('value' => '999');
$where[] = $db->quoteInto('product_id = ?', $q['product_id']);
$where[] = $db->quoteInto('contaminant_id = ?', $k);
$table->update($data, $where);
print $db->getProfiler()->getLastQueryProfile()->getQuery();
And the profiler output is:
UPDATE `product_contaminants` SET `value` = ? WHERE (product_id = '4802') AND (contaminant_id = 69)
Why isn't 'value' being populated??
Value isn't populated because getQuery will only return a prepared statement with parameter placeholders. If you want the parameters used when it updates try this:
$db->getProfiler()->getLastQueryProfile()->getQueryParams()
More info here.

Problem with DBD and mysql in perl

Please I am having problem tracking down the problem with this code I have been trying for hours . it gives me the error DBD::mysql::st fetchrow_hashref failed: fetch() without execute() at line 15
sub Split_Into_Words
{
#### Connection parameters ############################
my $dsn = "dbi:mysql:malware:localhost:3306";
my $user = 'root';
my $passwd = 'sxxxs';
########################################################
my $domain ;
my $countDir = 0 ;
my $file = shift ;
my $labelID = (split(/[.]/ , $file))[1] ; ### Split and get the middle value since format is temporay.
#### Query String ############################################################################
my $InsertIntoHostTable_QS = "INSERT INTO TB_host(HostName , UrlID , ExtID) Values (? , ? , ? ) ; ";
my $InsertIntoDomainTable_QS = "INSERT IGNORE INTO TB_Domain(Domain) values (?) ;" ;
my $InsertIntoArgVal_QS = "INSERT INTO TB_Arg_Value(Arg, URL_ID) VALUES (? , ? ) ; " ;
my $InsertIntoDirectory_QS = "INSERT INTO TB_Directory(DIRNAME , DEPTH , URLID) VALUES (? , ? , ? )" ;
my $InsertIntoExtension_QS = "INSERT IGNORE INTO TB_Extension (Extension) values ( ? ) ; ";
my $InsertIntoExtensionNULL_QS = "INSERT IGNORE INTO TB_Extension (ID , Extension) values (? , ? ) ; ";
my $SelectString = " Select URL , ID from TB_URL where LabelID = '" . $labelID."';";
my $InsertIntoFileName_QS = "INSERT IGNORE INTO TB_FileName( filename) VALUES (?) ; " ;
###################################################################################################
my $DBIConnect = DBI->connect($dsn , $user , $passwd) or die("Cannot connect to datadbase $DBI::errstr\n");
print ("Splitting Into Words \n");
######Initialization of a default DB value #################
my $sth = $DBIConnect->prepare( $InsertIntoExtensionNULL_QS);
$sth->execute(1 , 'null') or die("Error Executing the Insertion" . $sth->errstr );
$sth->finish();
#############################################################
$sth = $DBIConnect ->prepare($SelectString);
sleep(10);
open (FH , '<' , $file); # Open file to be read from disk
my $i = 0;
$sth->execute() or die("Error Executing the Insertion" . $sth->errstr );
->line 15 while(my $hash_ref = $sth->fetchrow_hashref )
{
my $extensionID = "1";
my $intialURL = $hash_ref->{URL} ;
my $initialID = $hash_ref->{ID};
}
}
I'm not sure if this is the issue, but you may not need the finish after the insert. From the DBI doc:
Indicate that no more data will be fetched from this statement handle
before it is either executed again or destroyed. You almost certainly
do not need to call this method.
Adding calls to finish after loop that fetches all rows is a common
mistake, don't do it, it can mask genuine problems like uncaught fetch
errors.
If that is the problem, you may want to create a second statement handler for the select call.
Apart from the annoyingly long SQL variable names, $SelectString should contain a "?", in case $labelID contains something that could break the query or cause an injection.
prepare() doesn't absolutely require a "?", but if execute has parameters, then there must be a matching number of "?" in the query string.
First $sth->finish() is not needed because the query is an insert and doesn't return any rows.
Second 'die' should be "Error executing query", because it executing $SelectString
Note SQL convention is to write all in uppercase, and for extra safety enclose field names in backticks. Queries do not end with semicolon. Also note that "my" variables are local to that between braces, { } so that my variables in the while loop will be unavailable afterwards.
Suggest formatting thus:
sub Split_Into_Words {
#### Connection parameters ############################
my $dsn = "dbi:mysql:malware:localhost:3306";
my $user = 'root';
my $passwd = 'sxxxs';
########################################################
my $domain ;
my $countDir = 0 ;
my $file = shift ;
my $labelID = (split(/[.]/ , $file))[1] ; ### Split and get the middle value since format is temporary.
#### Query String ############################################################################
my $InsertIntoHostTable_QS = "INSERT INTO `TB_host` (`HostName`,`UrlID`,`ExtID`) VALUES (?,?,?)";
my $InsertIntoDomainTable_QS = "INSERT IGNORE INTO `TB_Domain` (`Domain`) VALUES (?)";
my $InsertIntoArgVal_QS = "INSERT INTO `TB_Arg_Value` (`Arg`,`URL_ID`) VALUES (?,?)";.
my $InsertIntoDirectory_QS = "INSERT INTO `TB_Directory` (`DIRNAME`,`DEPTH`,`URLID`) VALUES (?,?,?)";
my $InsertIntoExtension_QS = "INSERT IGNORE INTO `TB_Extension` (`Extension`) VALUES (?)";
my $InsertIntoExtensionNULL_QS= "INSERT IGNORE INTO `TB_Extension` (`ID`,`Extension`) VALUES (?,?)";
my $SelectString = "SELECT `URL`,`ID` FROM `TB_URL` WHERE `LabelID`=?";
my $InsertIntoFileName_QS = "INSERT IGNORE INTO `TB_FileName` (`filename`) VALUES (?)";
###################################################################################################
my $DBIConnect = DBI->connect($dsn , $user , $passwd) or die("Cannot connect to datadbase $DBI::errstr\n");
print ("Splitting Into Words \n");
######Initialization of a default DB value #################
my $sth = $DBIConnect->prepare( $InsertIntoExtensionNULL_QS);
$sth->execute(1 , 'null') or die("Error executing the Insertion: " . $sth->errstr );
# $sth->finish(); # not needed because it's an insert
#############################################################
$sth = $DBIConnect->prepare($SelectString);
sleep(10);
open (FH , "<$file"); # Open file to be read from disk
my $i = 0;
$sth->execute($labelID) or die("Error executing query: " . $sth->errstr );
while(my $hash_ref = $sth->fetchrow_hashref ) {
my $extensionID = "1";
my $intialURL = $hash_ref->{URL};
my $initialID = $hash_ref->{ID};
}