Insert/Update MySQL into longtext Column - mysql

How do I insert the following string into MySQL:
$myValue ouputs: [Hey, this is a multi text file that has special characters like this ' and this '' and this ,,"", and this ''' and this '''' and this !#$ and whatever]
But the following will not work because of special characters:
$sql = "UPDATE `mytable` SET NEWS=('$myValue') WHERE _id='1'";
I do not want to manually escape every character (like adding an ' before every ')
Update/Insert should should start at [ and end at ] (as seen in $myValue)
EDIT (mysqli)
$_myValue = mysqli_real_escape_string($myValue);
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE `mytable` SET NEWS='$_myValue' WHERE _id='1'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

From the syntax of your code I assume that php is used to submit the queries to mysql.
If you just want to escape special characters in a string variable passed to a field, then use
PDO::quote() (if you use PDO)
mysqli_real_escape_string() (if you use mysqli)
mysql_real_escape_string() (if you use mysql, although you should not)
If you are looking for a more generic solution gainst sql injection, then consider using prepared statements. See this landmark SO topic on how to prevent SQL injection in php-mysql environment.

If your using php you could look at using PDO;
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE `mytable` SET NEWS=:myValue WHERE _id=1";
$st = $conn->prepare( $sql );
$st->bindValue(":myValue", $myValue, PDO::PARAM_STR);
$st->execute();
This will input all the data stored in $myValue. I would look at sanatising the input too.

Related

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

Fetching data from database in php file

I am trying to fetch data from table. Table contains the data and query is true. Even why following query says $u and $t are not define. While condition becoming false.
I manually checked in database, it was showing results.
$url = "http://paulgraham.com/";
$user_id = "123";
$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$result = mysqli_query($con,"SELECT * FROM post_data WHERE userid =".$url." and url=".$user_id."");
while ($row = #mysqli_fetch_array($result))
{
echo "hi";
$t = $row['title'];
$u = $row['url'];
}
echo "title is : $t";
echo "url is : $u";
Giving your SQL query :
"SELECT * FROM post_data WHERE userid =".$url." and url=".$user_id.""
You can see you are mixing url and userid... Change to :
"SELECT * FROM post_data WHERE userid =".$user_id." and url=".$url.""
Also define your $t and $u variables before your loop in case you have no record.
Next time, try to var_dump your generated query to test it.
If you were able to see the errors the DBMS is reporting back to PHP then you'd probably be able to work out what's wrong with the code.
Before the 'while' loop try...
print mysql_error();
(the obvious reason it's failing is that strings mut be quoted in SQL, and you've got the parameters the wrong way around)

MySQL concatenation and Illegal mix of collations error

I keep getting an error using MySQL 5.5.27 when trying to concatenate some values. I've searched and seen a bunch of charset answers (which admittedly is a TAD over my head), but I've converted all my tables to Charset utf8-unicode-ci and still get the error.
Surely there is a way to concatenate these values, but I just don't know how. I'm an Oracle guy that is relatively new to MySQL.
Here is the SQL line:
concat(pl.last_name,'-',format(money,0))
I get:
#1270 - Illegal mix of collations (latin1_swedish_ci,IMPLICIT), (utf8_unicode_ci,COERCIBLE), (utf8_unicode_ci,COERCIBLE) for operation 'concat'
Any ideas?
If money is indeed a number inside a VARCHAR you could use cast.
Try this:
concat_ws(pl.last_name,'-',cast(money AS unsigned)); // This is with decimals.
concat(`pl.last_name,'-',substring_index(money,',',1)) // Without decimals. If you use . i.e. the American currency notation you can substitute , with an .
Edit
Your should first try: concat(pl.last_name,'-',format(money,0));
This a very basic php code you could use.
<?php
function selecting_data(){
$host = "host";
$user = "username";
$password = "password";
$database = "database";
$charset = "utf8";
$link = mysqli_connect($host, $user, $password, $database);
mysqli_set_charset($charset, $link);
IF (!$link) {
echo('Unable to connect to the database!');
} ELSE {
$query = "SELECT lastname, format(money,0) FROM mytable"; //Select query
$result = mysqli_query($link, $query);
while ($rows = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo $rows['lastname']."<br>".$rows['money'] ;
}
}
mysqli_close($link);
}
?>
<html>
<head><title>title</title></head>
<body>
<?PHP echo selecting_data(); ?>
</body>
</html>

mysql 5.0 UPDATE syntax

I have been trying to get this code to update, and it just will not work. I've been re-reading it and looking at other examples for hours and need some help to get this to work. It is a basic UPDATE script for a membership table in mysql database. I have mysql version 5.0.91. Nothing I have tried is working. When uploaded and tested in browser, returns echo "update query failed" I bolded the part where it is failing. I just can't find out why. When I check mysqladmin, the table is not updated.
$host="mysqlhost"; // Host name
$username="mysqlusername"; // Mysql username
$password="mysqlpassword"; // Mysql password
$db_name="mydbname"; // Database name
$tbl_name="brothers"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$mymname=$_POST['mymname'];
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$myconfirmpassword=$_POST['myconfirmpassword'];
$mysnumber=$_POST['mysnumber'];
$myemail=$_POST['myemail'];
if ($mypassword !== $myconfirmpassword) {
die ("passwords do not match. Try again!");
if (isset($_COOKIE['fname'])) {
$myfname = ($_COOKIE['fname']);
}
else {
die('could not find cookie fname');
}
if (isset($_COOKIE['lname'])) {
$mylname = ($_COOKIE['lname']);
}
else {
die('could not find cookie lname');
}
$sql="SELECT * FROM $tbl_name WHERE fname='$myfname' AND lname='$mylname'";
$result=mysql_query($sql)or die("no sql");
while($row = mysql_fetch_array($result))
{
$fname=$row['fname'];
if (!$fname) {
die('variable not received');
}
$lname=$row['lname'];
$position=$row['position'];
$committee=$row['committee'];}
if($mypassword==$myconfirmpassword) {
$query= "UPDATE brothers
SET `mname`='$mymname' WHERE `fname` ='$fname'";
$chechresult= mysql_query($query) or die (mysql_error());
if (!$checkresult) echo 'update query failed';
elseif ($checkresults) {
echo'update query success';
setcookie('position', $position, time()+86400,'/');
setcookie('committee', $committee, time()+86400,'/');
$headsuccess=header( "location:done_registration.php");
$headsuccess;
if (!$headsuccess) {
die('Could not redirect success registration'); }
}
}
else{
$headlogin=header( "location:error_registration.php");
$headlogin;
if (!$headlogin) {
die('Could not redirect registration error'); }
}
$chechresult= mysql_query($query) or die (mysql_error());
if (!$checkresult) echo 'update query failed';
you misspelled "k" with "h" in "$chechresult="
Try to print $query string that contains the UPDATE order and after execute it in mysql console.
You've misspelled $chechresult - should be $checkresult; also, $fname should be $myfname!
It is probably worth echoing out $query to the screen, and trying that directly in your database - either on your console or in phpMyAdmin. Since $fname is empty (wrong var) your WHERE clause is wrong; at a guess it is affecting zero rows, and so is executing correctly.
Bear in mind that you have some SQL injection security issues in this code - make sure you escape your values before adding them to a query. Better yet, if you upgrade to PDO, you can use parameterisation, which will do the escaping for you.

I was looking to see if someone could tell me how secure this is

I am writing a code that will check 2 different tables to determine the privileges the user will have. The code looks like this:
$query1 = ("SELECT 1 FROM `customers` WHERE `Email` = '$email' AND `Password` = '$password'");
$query2 = ("SELECT 1 FROM `admins` WHERE `Email` = '$email' AND `Password` = '$password'");
$result1 = mysql_query($query1) or die(mysql_error());
$result2 = mysql_query($query2) or die(mysql_error());
if (mysql_num_rows($result1) == 1) {
// Log user in as a Customer
exit;
} else if (mysql_num_rows($result2) == 1) {
// Log user in as an Admin.
exit;
} else {
// Direct user to registration page.
}
Can anyone look at this and tell me if there would be any security risk by doing it this way? Thank you in advance for your help!
Firstly you have a change that your code is only known by you.
Secondly you have to check the input data. email and password area is not safety. You should prevent SQL injection. Otherwise your code is not secure.
By the way i'm offering you IP restricted login for admins. I'm using this. And it is more secure.
One big problem here is that the code is vulnerable for sql injections.
Which basicly means that the user could put code in the email or password form to bypass the check you have here.
A start would be to perform the following to your input BEFORE you use them in your query:
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
Though, the mysql library is not recommended by php, rather read about prepared statements in pdo here: http://www.php.net/manual/en/ref.pdo-mysql.php
But you can try the mysql_real_escape_string to have a first security measure against sql injections.
This is insecure if for example my password was
OR 1=1
I get access. Use mysql prepared statements
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("SELECT 1 FROM customers WHERE Email = (?) AND Password = (?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("ss", $email, $password)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
?>