mysql syntax error: mysql not allowing certain characters to be processed - mysql-error-1064

Am one step away from reading from a file and writing the data to a table in my database. Everything works correctly except when writing to the table in my database. This is the error message i get:
could not load. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'm not following you so that I can follow you back ♡ )')' at line 1
This is my code:
$sql = mysql_connect("localhost", "root","root");
mysql_select_db("Tweet_Corpora");
if(!$sql){
die("could not connect: " . mysql_error());
}
$file = fopen("/Applications/MAMP/bin/mamp/uploads/corpus/set_2.txt","r") or exit("Unable to open file!");
while(!feof($file)){
$string = fgets($file);
$arr = (explode("\t", $string));
$test = "INSERT INTO Display (tweet_id, raw_tweet) VALUES ('mysql_real_escape_string($arr[0])','mysql_real_escape_string($arr[1])')";
$result = mysql_query($test);
if(!$result){
die("could not load. " . mysql_error());
}
}
What do i do? please help. Thank you in advance.

Here is the working code with a bit of twist:
$sql = mysql_connect("localhost", "root","root");
mysql_select_db("Tweet_Corpora");
if(!$sql){
die("could not connect: " . mysql_error());
}
$file = fopen("/Applications/MAMP/bin/mamp/uploads/corpus/set_2.txt","r") or exit("Unable to open file!");
while(!feof($file)){
$string = fgets($file);
$arr = (explode("\t", $string));
$idd= mysql_real_escape_string($arr[0]);
$tweet=mysql_real_escape_string($arr[1]);
$test = "INSERT INTO Display (tweet_id, raw_tweet) VALUES ('".$idd."','".$tweet."')";
$result = mysql_query($test);
if(!$result){
die("could not load. " . mysql_error());
}
}

Related

Execute oracle sql query in PERL script while loop

I am trying to execute an oracle sql query in while loop of a PERL script as follows --
my $dbh = DBI->connect( 'dbi:Oracle:'.$dbname,
$dbusername,
$pass,
{ PrintError => 0,
RaiseError => 1
}
) || die "Erreur lors de la connexion: $DBI::errstr";
print ("Connexion à la base de données $dbname avec $dbusername OK \n");
$requete = "select distinct to_char(date_appli,'yyyymmdd') from DATE_APPLI ".
"where frequence = 'Q' and actif = 1";
$sth_sql = $dbh->prepare($requete);
$sth_sql->execute();
#row=$sth_sql->fetchrow_array;
$datesitu=#row[0];
$sth_sql->finish;
print "La date de situation est $datesitu \n";
# SQL to get validation script and table names
$requete = "select SCRIPT_NAME, table_name from fdf_scripts";
$sth_sql = $dbh->prepare($requete);
$sth_sql->execute();
$sth_sql->bind_columns(undef, \$script_name, \$table_name);
while ($sth_sql->fetch()) {
$script_sql="$sql_path\\"."FDF_Test_scripts\\".$script_name.".sql"; #validation script path
$script_log="$log_path\\".$script_name.".log"; #log files path
$rep_file_name="$sql_path\\"."FDF_Test_scripts\\".$table_name.".sql"; #reports SQL path
$csv_file="$sql_path\\"."FDF_Test_scripts\\".$table_name.".csv"; #report CSV path
#Load data into validation tables using validation scripts
$CmdText="sqlplus -s $connect \#$script_sql $script_log";
print "Inserting data into table : $table_name \n";
#system ("$CmdText");
$col_sql = "select COLUMN_NAME from all_tab_cols where TABLE_NAME = upper(\'$table_name\')\n";
print "$col_sql\n";
$sth_sql = $dbh->prepare($col_sql);
$sth_sql->execute();
$sth_sql->bind_columns(undef, \$COLUMN_NAME);
while ($sth_sql->fetch()) {
print "$COLUMN_NAME\n";
}
if (open (my $fh, '<:encoding(UTF-8)', $script_log)){
while (my $line = <$fh>){
if ($line=~m/\bERROR\b/){
print "Error While Loading $table_name table Please Check log file for errors at: $script_log \n";
}
}
}
else {
warn "Could open file: $script_log \n"
}
}
in above code i am fetching table names from a table and then looping them to get the column names of each table which is present in that table.
The code got executed for one iteration of inner while loop but throw error for next iteration as below --
DBD::Oracle::st fetch failed: ERROR no statement executing (perhaps you need to call execute first) [for Statement "select COLUMN_N\
AME from all_tab_cols where TABLE_NAME = upper('FDF_Bond_validation_results')
I am not proficient in PERL and just started to using this and not sure how can i overcome this problem.
Please let me know if more information is required.
In the loop, the line $sth_sql = $dbh->prepare($col_sql); overwrite the content of the $sth_sql variable. The second time the loop run, the content of $sth_sql isn't the same and the statement that overwrote it has already been exhausted (trying to fetch from it again is what causes the error).
To correct this issue you should either use a different name for the second $sth_sql variable or simply declare the second $sth_sql variable with my to keep it inside the loop (see perldoc -f my).
Note: This solution has been identified by JGNI in the comment of the question. My role has only be to summarize the issue to provide a proper answer to this question.

Laravel chained jobs as array not working. Attempt to assign property of non-object

I'm trying to loop over multiple servers that need to run 1 at a time using Laravel's withChain. The first job completes just fine but the data I'm passing within the chained jobs gives me the
Attempt to assign property of non-object
When I log out the initial dispatched data it looks just like the constructed data in my array so I'm not sure what I'm doing wrong.
$new_jobs_array = [];
foreach ($this->wasRequest->nodes->sortByDesc('pivot.node_type') as $node) {
if ($node->pivot->node_type != 'WAS_DMGR')
{
$snode = strtolower($node->hostname);
$shortname = strtok($snode, '.');
$fileName = strtolower($mnemonic).'_'.$shortname.'_'.$reqId.'.json';
$sourceJsonPath = base_path() . "/json/was/" . $fileName;
$new_job = 'new BootStrapWasNode('. $node .', '. $this->wasRequest .', '.$sourceJsonPath.')';
array_push($new_jobs_array, $new_job);
} else {
$dmgr_node = $node;
}
}
//Log::info($new_jobs_array);
$dmgr_node_sname = strtok($this->wasRequest->nodes->where('pivot.node_type', 'WAS_DMGR')->pluck('hostname')[0], '.');
$fileName = strtolower($mnemonic).'_'.$dmgr_node_sname.'_'.$reqId.'.json';
$sourceJsonPath = base_path() . "/json/was/" . $fileName;
$this->wasRequest->status = 'Bootstrapping Nodes';
$this->wasRequest->save();
//Log::info("DMGR-------------------".$dmgr_node.", ".$this->wasRequest.", ".$sourceJsonPath);
BootStrapWasNode::withChain($new_jobs_array)->dispatch($dmgr_node, $this->wasRequest, $sourceJsonPath);
I can attach the log view if needed but there is a lot of data for each node. The issue is with the $new_nodes_array, the initial dispatch($dmgr_node,$this->wasRequest,$sourceJsonPath) completes without issue.
Was able to figure out the issue.
This line was incorrect
$new_job = 'new BootStrapWasNode('. $node .', '. $this->wasRequest .','.$sourceJsonPath.')';
It should be
$new_job = new BootStrapWasNode($node, $this->wasRequest, $sourceJsonPath);

How do i split each row using powershell

I'm trying to insert an table from 1 database to another (rows) using powershell. I already know how to get the data out but when i try to insert it into a new table I get an error that the string is too long (I think it means that i am trying to put all the data into an new row). I already searched the web for an answer. The only thing I could find is a command -split but then i need something to split with and the data is only numbers.
below you will find the script.
$query = “SELECT ZAMNIEUW.MACHINENAME FROM ZAMNIEUW WHERE MACHINENAME not in (SELECT PATCHGROEPEN.MACHINENAME FROM PATCHGROEPEN ) "
$command = $con.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$table = new-object “System.Data.DataTable”
$table.Load($result)
$format = #{Expression={$_.WAARDE_PCNAME};Label=”ID”;width=20}
echo $table.MACHINENAME
$table| foreach {
$qu= " INSERT into TESTZEN (MACHINENAME) VALUES('$table')"
$cmd = $con.CreateCommand()
$cmd.CommandText = $qu
$cmd.ExecuteNonQuery() |out-null
}
apperantly oracle does use something to split each row (;)
the code below
$query = “SELECT ZAMNIEUW.MACHINENAME FROM ZAMNIEUW WHERE MACHINENAME not in (SELECT PATCHGROEPEN.MACHINENAME FROM PATCHGROEPEN ) "
$command = $con.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$table = new-object “System.Data.DataTable”
$table.Load($result)
$format = #{Expression={$_.WAARDE_PCNAME};Label=”ID”;width=20}
$tables =echo $table.MACHINENAME
$tables| foreach {
$tables = $_ -split ';'
$qu= " INSERT into TESTZEN (MACHINENAME) VALUES('$tables')"
$cmd = $con.CreateCommand()
$cmd.CommandText = $qu
$cmd.ExecuteNonQuery() |out-null
}

preg_match issue: Delimiter must not be alphanumeric or backslash

I know this issue has been discussed in different questions but the answers people have given don't seem to work on my end. I'm dealing with the following problem:
if ( (preg_match($suspect, $lowmsg) )
|| (preg_match($suspect, strtolower($_POST['name'])))
|| (preg_match($suspect, strtolower($_POST['email']))))
Now, people have been saying that if I put "/" in front and behind quotes like so '/email/' that this would solve the problem. I tried putting the / for email and name but it still brought me back to the same delimiter error.
I also get a final error of: Warning: Cannot modify header information - headers already sent by (my website's send.php:43) on line 61. Does this have anything to do with it or is this just an error as a result of the earlier error?
Here's the entire code for interested parties:
<?php
if(($_POST['email']=="")||($_POST['name']=="")||($_POST['message']==""))
{
echo "<html><body><p>The following fields are <strong>required</strong>.</p><ul>";
if($_POST['name'] == ""){ echo "<li>Name</li>"; }
if($_POST['email'] == ""){ echo "<li>Email</li>"; }
if($_POST['message'] == ""){ echo "<li>Message</li>"; }
echo "</ul><p>Please use your browser's back button to complete the form.</p></body></html>";
}
else
{
$message = "";
$message .= "Name: " . htmlspecialchars($_POST['name'], ENT_QUOTES) . "<br>\n";
$message .= "Email: " . htmlspecialchars($_POST['email'], ENT_QUOTES) . "<br>\n";
$message .= "Message: " . htmlspecialchars($_POST['message'], ENT_QUOTES) . "<br>\n";
$subject = htmlspecialchars($_POST['subject'], ENT_QUOTES);
$pagelink = htmlspecialchars($_POST['pagelink'], ENT_QUOTES);
$repemail = htmlspecialchars($_POST['repemail'], ENT_QUOTES);
$injection_strings = array ( "content-type:","charset=","mime-version:","multipart/mixed","bcc:","cc:");
foreach($injection_strings as $suspect)
{
if((preg_match($suspect, $lowmsg)) || (preg_match($suspect, strtolower($_POST['/name/']))) || (preg_match($suspect, strtolower($_POST['/email/']))))
{
die ( 'Illegal Input. Go back and try again. Your message has not been sent.' );
}
}
$headers = "MIME-Version: 1.0\r\nContent-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: \"" . $_POST['/name/'] . "\" <" . $_POST['/email/'] . ">\r\n";
$headers .= "Reply-To: " . $_POST['/email/'] . "\r\n\r\n";
mail($repemail, $subject, $message, $headers);
header("Location: " . $pagelink . "");
}
?>
You can try other delimiters, such as / # ~
see regexp.reference.delimiters
Hope that helps.
EDIT: you do not need to do backslash inside $_POST
Use $_POST['name'] instead of $_POST['/name/']
EDIT: try
preg_match("/".$suspect."/i", strtolower($_POST['name']);
However, I dont think you would find any of your $injection_strings inside post name. You may need to rethink how you are searching. "content_type" is not going to match "text/html" with your current statement. You'd need to try other regex like
preg_match("/".$suspect."(.*)/i", strtolower($_POST['name'], $output);
So that it would $output[0], your "suspect" variable. I'm not sure if thats what you are looking for, but maybe sending you to the right track.
EDIT: Here.
If you want to look at say "cc:" and find what email it is, use this.
preg_match("/cc:(.*)/i",'cc:'.$_POST['email'],$output);
$output[0]; would equal your email.
To be compatible with your foreach loop, you may want to change it too,
switch this below code within your "if statements"
preg_match("/".$suspect."(.*)/i",$suspect.$_POST['email'])

Magento, 1 db field not saved

I have a problem with one field of the DB. With this code:
$expireMonth = Mage::getStoreConfig('points_options/config_points/expiration_period', Mage::app()->getStore()->getId());
if (!is_null($expireMonth) && ($expireMonth > 0)) {
$expireDate = date("Y-m-d H:i:s", strtotime("+" . $expireMonth . " month"));
} else {
$expireDate = NULL;
}
//die($expireDate);
//store in points history table
$this->_pointsModel->setCustomerId($this->_customer->getId())
->setOrdersId('welcome')
->setPointsPending($pointsForNewCustomer)
->setPointsComment(Mage::helper('points')->__('welcome points'))
->setDateAdded(date('Y-m-d H:i:s'))
->setPointsStatus(2)//confirmed
->setPointsType('WE')
->setStoreId(Mage::app()->getStore()->getId())
->setExpireDate($expireDate)
->save();
Every field is saved in the table, except for expire_date. If I uncomment the die($expireData), I see the correct value, something like 2012-01-13 13:21:12. The field is defined as:
`expire_date` datetime NULL
Any thoughts?
edit: The solution is:
$expireDate = date("Y-m-d H:i:s", strtotime("+" . $expireMonth . " months"));
Check out the "s" in my strtotime expression.
I know many attributes allow for some sort of formatting before writing and after reading. Have you tried setting the value as a unix timestamp instead?

Resources