inserting special chracters into mysql using perl - mysql

hi i am very new to perl..
I have a temp_data.txt file like this
Id Comments
--------------------------------
1 this is a 'comment'
2 special comment
3 user comment 'user'
-----------------------------------
open (MYFILE, 'temp_data.txt');
while (<MYFILE>) {
if($_=~/^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)/)
{
$id=$1;
$comment = $2;
}
while(<MYFILE>)
{
$line=$_;
if($line=~/^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)/)
{
seek(MYFILE, -length($_), 1);
last;
}
else
{ if($_=~/\s*(.*)/)
{
$comment .=$1;
}
}
}
my $queryString = "INSERT INTO Headline (id,comment) VALUES ('$id', ' $comment')";
$sth = $dbh->prepare($queryString);
$sth->execute() or die $DBI::errstr;
$sth->finish();
}
but while inserting into data base if it encounters a special character throwing a error like this.
DBD::mysql::st execute failed: 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 'comment')' at line 1 at head.pl line 1.
can anyone help me?
thanks in advance

Maybe, the data, you are inserting has special symbols. Use parametrized queries for this (it will protect you from SQL injection):
my $queryString = "INSERT INTO Headline (id,comment) VALUES (?, ?)";
$sth = $dbh->prepare($queryString);
$sth->execute($id, $comment) or die $DBI::errstr;
$sth->finish();

Related

I have an SQL syntax error when inputing data

I'm a beginner programmer and I'm getting a problem that I cannot seem to overcome. I predict it's a small syntax error but I don't know.
The code I'm using is the following:
<?php
$x=$_POST['firstname'];
$y=$_POST['lastname'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname="db1";
//Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "INSERT INTO 'user' ('fname', 'lname') VALUES ('$x','$y')";
if ($conn->query($sql) === TRUE) {
echo "New record created succesfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Once I press submit to input the data the following error comes up:
Connected successfullyError: INSERT INTO 'user' ('fname', 'lname') VALUES ('rty','rty')
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''user' ('fname', 'lname') VALUES ('rty','rty')' at line 1
Any help? Thanks in advance.
update your query replace single quote(') from table name and column name with (`), Like
$sql = "INSERT INTO `user` (`fname`, `lname`) VALUES ('$x','$y')";

SQL error text giving me a different value that the actual value

This is the line of code that is causing the error:
$result = $mysqli->query("SELECT * FROM 'accounts'.'users' WHERE email='$email' AND hash='$hash' AND active='0'") or die($mysqli->error);
and this is the error that shows:
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 ''accounts'.'users' WHERE email='testemail#email.com' AND hash='76dc611d6eba' at line 1
However, if I print the value of hash I get this "76dc611d6ebaafc66cc0879c71b5db5c" the value that I want to search with and the value that is stored in the database. I am not sure if it is just being shortened for the error message of if something else is happening.
Try changing from ' (apostrophe) to ` (backtick) or simply removed the single quotes from db/table name, so your query looks like this:
SELECT * FROM `accounts`.`users` WHERE email='$email' AND hash='$hash' AND active='0'
Try removing quotes around database and table name
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$result = $mysqli->query("SELECT * FROM accounts.users WHERE email='$email' AND hash='$hash' AND active='0'") or die($mysqli->error);

Script gives database error on just one system

I am a VOIP administrator and I have script for updating directory database in Perl which was purchased from vendor before I was employed here.
The script is working fine on all of the servers except for one.
#!/usr/bin/perl
use lib "/opt/asterisk/lib/";
use DBI;
use Asterisk::config;
sub trim($);
# database information
$db="kesc";
$host="sip-ho.kesc.com.pk";
$userid="foo";
$passwd="bar";
$connectionInfo="dbi:mysql:$db;$host";
$hubname = "";
# make connection to database
$dbh = DBI->connect($connectionInfo,$userid,$passwd);
# Perl trim function to remove whitespace from the start and end of the string
sub trim($)
{
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
my $rc = new Asterisk::config (file=>'/etc/asterisk/sip.conf',keep_resource_array=>0);
#list = $rc->fetch_sections_list();
$n = 1;
foreach (#list)
{
if ($_ ne "general") {
$entry = $rc->fetch_keys_hashref(section=>$_);
while ( my ($key, #value) = each(%$entry) )
{
if ($key eq "callerid") {
#vars = split('<',$value[0][0]);
$query = "insert into directory (extension,name,hub) values (" . trim($_) . ", '" . trim($vars[0]) . "', '$hubname') ON DUPLICATE KEY UPDATE hub='$hubname'";
$sth = $dbh->prepare($query);
$sth->execute();
}
}
}
$n++;
}
Now I get below mentioned error when executing it.
DBD::mysql::st execute failed: 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 's Office', '') ON DUPLICATE KEY UPDATE hub=''' at line 1 at ./directory line 39.
I have also replaced it from other server with same MySQL version where it works perfectly.
Please guide me.
Thank you for the code. It is as I suspected; you really shouldn't insert values directly into an SQL statement
Change line 37, 38, and 39 to this and it should work for you
$query = 'INSERT INTO directory (extension, name, hub) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE hub = ?';
$sth = $dbh->prepare($query);
$sth->execute( trim($_), trim($vars[0]), $hubname, $hubname );
Beware that the same problem is likely to exist elsewhere in the code base, so it really should be completely reviewed

Why do I get this SQL syntax error? - Syntax error or access violation: 1064

Why do I get this error: SQLSTATE[42000]: Syntax error or access violation: 1064 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 '' at line 1?
<?php
include'model.php';
global $db;
try {
$sql ='SELECT accounts.username '
. 'FROM accounts '
. 'WHERE accounts.username = '
.$_POST[username];
$stmt = $db->prepare($sql);
$stmt->execute();
$navList = $stmt->fetchAll();
$stmt->closeCursor();
header('location: ./view_cms.php');
} catch (PDOException $exc) {
echo $exc->getMessage();
// header('location: ./view_error.php');
exit;
}
?>
Because you need to wrap strings in single quotes in the WHERE clause. You also need to access $_POST entries with a quoted string key:
$sql = "SELECT accounts.username ".
"FROM accounts ".
"WHERE accounts.username = '".$_POST["username"]."'";
Plus, this is the reason why PHP based web software has a bad reputation. Sanitize your inputs, for heaven's sake!! Your prepare statement doesn't do anything as you're not using parameters (your statement is not a prepared statement).

What is wrong with my SQL syntax (regarding quotes or maybe something else)

Originally I got this error
Error: 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 '' at line 1
but I narrowed it down to this block of code
$query = "SELECT Priority FROM mathhw WHERE MHID=$row";
echo $query;
$querycon = mysqli_query($con,$query);
while($row = mysqli_fetch_row($querycon))
{
$priority = $row[0];
echo $priority;
}
if($priority==0)
{
$sql="UPDATE mathhw SET Priority = 1 WHERE MHID=$row";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
header("Location: math.php");
}
else if($priority == 1)
{
$sql="UPDATE mathhw SET Priority = 0 WHERE MHID=$row";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
header("Location: math.php");
}
I did some trial and error and it seemed like the WHERE condition is giving me trouble. I hard-coded it, and I took it out completely and it did what I wanted it to do. I think it is problem with my quotes? I don't think I'm supposed to put quotes around numerical values but I think variables are a different case. Can someone help me out.
From the block of code you have here, the error is being thrown in one or the other of the UPDATE queries because you are reusing $row in those queries after having set it to either an array of strings or NULL from the fourth line in your code:
while($row = mysqli_fetch_row($querycon))
...
See http://www.php.net/manual/en/mysqli-result.fetch-row.php.
Then, you're reusing it here without modification.
...
$sql="UPDATE mathhw SET Priority = 1 WHERE MHID=$row";
Given the syntax error ending with near '' at line 1, your SELECT probably returned nothing, set
$row to NULL and then replaced $row with "" in your query.
A quick tip that really helped me with MySQLi is the following function:
http://www.php.net/manual/en/mysqli.real-escape-string.php
Take a look at the example, using the procedural style, like your code above:
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");
$city = "'s Hertogenbosch";
/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
printf("Error: %s\n", mysqli_sqlstate($link));
}
$city = mysqli_real_escape_string($link, $city);
/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
printf("%d Row inserted.\n", mysqli_affected_rows($link));
}
mysqli_close($link);
?>
One last note: in your WHERE clause, what you have is only correct if MHID is not a string typed column. If MHID is a varchar, for example, you would need to quote the $row as '$row', like so:
$sql="UPDATE mathhw SET Priority = 1 WHERE MHID='$row'";
That's when the mysqli_real_escape_string() function becomes REALLY useful.