Escape Character issues - php

I generally understand the idea behind escaping quotes using backslashes and alternatively using backslashes to escape so that you can have backslashes in your strings and so forth, but I've run in to a problem trying to pass a query through odbc_exec() and using a table-valued function and I just cannot seem to get it to stop giving me
SQL error: [Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark after the character string '0000005'.
This is what it looks like when I hard code the variables:
$query = 'SELECT '.$csvCriteria.", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('1','1','northbound','0006009','00000050370A2P000004','00060041270B2P000070','1')";
This works fine. Note that $csvCriteria hasn't given me any problems. This is what I want it to look like:
$query = 'SELECT '.$csvCriteria.", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('".$stepNum."', '".$segMarker."', '".$prevDirection."', '".$rdNoA."', '".$re_1."', '".$re_2."', '".$directionA."')";
However I keep getting errors around $re_1 and $re_2 (the error I've put in at the top of this).
I've tried multiple variations of what I think may work, such as:
$query = 'SELECT '.$csvCriteria.", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('".$stepNum."','".$segMarker."','".$prevDirection."','".$rdNoA.'\',\''.$re_1.'\',\'00060091100B1P000030\',\'1\')';
But I am neither expertly proficient at this, nor do I know if I'm missing something blatantly obvious. Just absolutely stuck and need a hand!

I can not reproduce your error:
The SQL in question is:
SELECT csvcriteria,
googstep,
segment,
prevailingdirection
FROM jselectorcsvcreator('1', '1', 'northbound', '0006009',
'00000050370A2P000004', '00060041270B2P000070', '1');
Placing the data in variables such as:
$csvCriteria = 'csvCriteria';
$stepNum = 1;
$segMarker = 1;
$prevDirection = 'northbound';
$rdNoA = '0006009';
$re_1 = '00000050370A2P000004';
$re_2 = '00060041270B2P000070';
$directionA = 1;
Using the first line of code, which works and using the one that doesn't work both return the exact same thing:
$correct = 'SELECT ' . $csvCriteria . ", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('1','1','northbound','0006009','00000050370A2P000004','00060041270B2P000070','1')";
$query = 'SELECT ' . $csvCriteria . ", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('" . $stepNum . "','" . $segMarker . "','" . $prevDirection . "','" . $rdNoA . "','" . $re_1 . "','" . $re_2 . "','" . $directionA . "')";
echo $correct . "\n";
echo $query . "\n";
var_dump($correct === $query);
The response is (CodePad):
SELECT csvCriteria, googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('1','1','northbound','0006009','00000050370A2P000004','00060041270B2P000070','1')
SELECT csvCriteria, googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('1','1','northbound','0006009','00000050370A2P000004','00060041270B2P000070','1')
bool(true)
My guess is that $csvCriteria or any of the variables at hand have errors.
I would highly recommend looking at the echoed query of $query in an SQL Formatter (Select MS ACCESS)

$query = 'SELECT '.$csvCriteria.", .....
should be
$query = 'SELECT '.$csvCriteria.', ......

Try using
$query = "SELECT $csvCriteria, googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('$stepNum','$segMarker','$prevDirection','$rdNoA','$re_1','00060091100B1P000030','1')";
This is much simpler without need of all the escapes.

As it turns out I was attempting to pass a string that looked like this "0000000\000X00X0\0000000" and it wasn't working so well. I decided to use stripslashes() so I could pass the variable more easily and work with it once it was in SQL. Turns out stripslashes() doesn't work like that. I used str_replace() instead and it now works fine.

Related

PHP MySQL Update Set query with Multiple columns

I've tried this query with both commas and "AND" statements as pictured below. I get a syntax error
Something went wrong.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 'are available 24/7 by phone and email to answer any questions and to assist you ' at line 1
every time I try this query:
$sql = mysql_query("UPDATE general
SET bookabandheading = $_POST[bookabandheading
AND bookaband = $_POST[bookaband]
AND contactus = $_POST[contactus]
AND aboutuslisten = $_POST[aboutuslisten]
AND contactusheading = $_POST[contactusheading]
AND nightclubsheading = $_POST[nightclubsheading]
AND acousticheading = $_POST[acousticheading]
AND schoolsheading = $_POST[schoolsheading]
AND privateheading = $_POST[privateheading]
AND concertsheading = $_POST[concertsheading]
AND festivalsheading = $_POST[festivalsheading]
AND submissions = $_POST[submissions]
AND interns = $_POST[interns]
AND managementbio = $_POST[managementbio]
AND latestnews = $_POST[latestnews]
AND artistofthemonth = $_POST[artistofthemonth]
AND artistofthemonthphoto = $_POST[artistofthemonthphoto]
AND artistofthemonthid = $_POST[artistofthemonthid]
AND listentoourartists = $_POST[listentoourartists]
AND musicianswanted = $_POST[musicianswanted]
AND aboutus = $_POST[aboutus]
AND bshowcases = $_POST[bshowcases]
AND bandavails = $_POST[bandavails]");
The query worked in a different database on another VPS, but I just migrated servers and it no longer works. Any help is greatly appeciated!
While the main problem is that you missed the closing bracket after bookamandheading, still I would like to advise you to refactor this request for example like this:
$keys = array("bookabandheading", "bookaband", "contactus", "aboutuslisten",
"contactusheading", "nightclubsheading", "acousticheading",
"schoolsheading", "privateheading", "concertsheading",
"festivalsheading", "submissions", "interns", "managementbio",
"latestnews", "artistofthemonth", "artistofthemonthphoto",
"artistofthemonthid", "listentoourartists", "musicianswanted",
"aboutus", "bshowcases", "bandavails");
$set = array();
foreach ($keys as $key) {
$set[] = sprintf(" %s = '%s' ", $key, mysql_escape_string($_POST[$key]));
}
$sql = mysql_query("UPDATE general SET " . implode(", ", $set));
It is much easier to maintain and also a bit more secure by escaping the input.
Update: add where statement example
$where = array();
$where[] = sprintf(" some_string = '%s' ", mysql_escape_string($some_string));
$where[] = sprintf(" some_integer = %d ", $some_integer);
$where = " WHERE " . implode(" AND ", $where);
$sql = mysql_query("UPDATE general SET " . implode(", ", $set) . " " . $where);
I see 3 things wrong with this:
Raw POST data in your query - at the very least user mysql_real_escape_string
The parameters look like strings so should have quotes around them
There's no WHERE option, so you'll update every row in that table
You have a few errors:
Syntax error. Change
$_POST[bookabandheading to $_POST[bookabandheading]
This is also incredibly prone to SQL injections. You should be using mysqli, but if you are set on mysql (which is deprecated as of 5.5.0), you should escape each $_POST variable using mysql_real_escape_string().
Each $_POST variable needs to bee parameterized using quotes a well. So, an example:
$_POST['bookabandheading'] (do this for all $_POST variables)
$_POST[bookabandheading
change to
$_POST[bookabandheading]

Escaping for insert to MySql

I have a php page that uses mysql_real_escape_string() to escape content that contains single quotes. I believe it is using utf-8 (but I am not sure). When I insert some content, I get the following mysql warning (and it adds a ? instead of ' in the content):
Incorrect string value: '\x92t ...
Here is an example of my php:
$link = ConnectToServer($theIntranet, $theUser, $thePW);
$theTagToFind = 'ac';
$theTagToUse = 'trc';
$database = '{databaseName}';
$theQuery = "SELECT * FROM {$database}.templates
WHERE content like '%{" . $theTagToFind . ":%'";
$updates = fopen('001_intranet_change' . strtoupper($theTagToFind) . 'to' . strtoupper($theTagToUse) . '.sql', 'w+');
$rollback = fopen('001_intranet_change' . strtoupper($theTagToUse) . 'backto' . strtoupper($theTagToFind) . '.sql', 'w+');
$theResultHandle = mysql_query($theQuery, $link);
$comment = "--Update All $theTagToFind tags to $theTagToUse tags in $database --";
fwrite($updates, $comment . "\r\n\r\n");
fwrite($rollback, "--Rollback - Convert all $theTagToUse tags back to $theTagToFind tags --\r\n\r\n");
mysql_set_charset('latin1');
while (($data = mysql_fetch_assoc($theResultHandle)) != false)
{
$rb_content = $data['content'];
$data['content'] = preg_replace("/{" . $theTagToFind . ":/", "{" . $theTagToUse . ":", $data['content']);
$theResult[] = $data;
$update_script = "\r\n
Update $database.templates
SET content = '" . mysql_real_escape_string($data['content']) . "'
WHERE _id = " .$data['_id'] . ";";
$rollback_script = "\r\n
UPDATE $database.templates
SET content = '" . mysql_real_escape_string($rb_content) . "'
WHERE _id = " . $data['_id'] . ";";;
fwrite($updates, $update_script);
fwrite($rollback, $rollback_script);
}
fclose ($updates);
fclose($rollback);
print_r($theResult);
and $data['content'] could equal something like:
"Hello,
Please remember to contact the doctor's office at......"
here you go
mysql_set_charset('utf8');
you have to be sure that charset in your table definition also set to utf8
Are you sure your server is configured correctly and magic quotes are turned off? These can have the effect of double escaping values.
You can test this by looking at the $_POST data to see if it's been modified from what you'd expect. If so, see if you can fix the setting in php.ini.
As a note, you should not be using mysql_query in new code. It's dangerous, deprecated, and will be removed in future versions of PHP. Using SQL placeholders is the safest and easiest way to do escaping.
In your short example here it looks like you've forgotten to escape $data['_id'] which means it's a possible SQL injection bug. Even one mistake can have severe consequences, so never, ever put unescaped data into a query string.

search a string with spaces in sql with php

I need to search a string in mysql with php. I get an error related to the spaces in the string. I an not fimilar with regex, I am not sure it that is my only choice.
example:
$ex="This and That";
$sql = 'SELECT
some_ID
FROM ' . atable. ' WHERE ' . strings. ' LIKE ' . $ex. ' AND visable=' . '1';
after executing I get an error like:
"near 'That AND visable=1' at line x"
so its probably not picking up the first two words, any suggestions?
Thanks in advance.
You are missing quotes around the string. They need to be encapsulated entirely for the query to execute properly.
Change this:
LIKE ' . $ex. ' AND
To this:
LIKE "' . $ex. '" AND
On a side note, make sure you are protecting your self against SQL injections AND make sure your query is properly escaped.

Session variable is not working in MySQL statement

I am trying to use session variable($_SESSION['asc_id'], which holds some value like "AS0027001") in an SQL statement, but it is not working.
When I hardcode the value, it is providing results.
Can anyone please correct me.
MySQL query which is not working
$asc_id = $_SESSION['asc_id'];
$rs = mysql_query('select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = "$asc_id"
and lname_fname_dob like "' .
mysql_real_escape_string($_REQUEST['term']) .
'%" order by lname_fname_dob asc limit 0,10', $dblink);
Mysql query which is working
$rs = mysql_query('select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = "AS0027001" and lname_fname_dob like "' .
mysql_real_escape_string($_REQUEST['term']) .
'%" order by lname_fname_dob asc limit 0,10', $dblink);
Variable substitution only works within double quoted strings, not single quoted ones. In other words, you should do;
$rs = mysql_query("select .... and asc_id = '$asc_id' and ... limit 0,10", $dblink);
Btw, you did make sure the value doesn't include any characters that may lead to SQL injection, right? Otherwise you should use mysql_real_escape_string to make sure before inserting it into a query.
When you print the strings, it will be clear. When the question is reformatted to leave the SQL readable, the problem is clear. (The first rule for debugging SQL statements is "print the string". A second rule, that makes it easier to comply with the first, is always put the SQL statements into a string which you pass to the SQL function.)
You use the . notation to embed the request term in the string; you don't use that to embed the $asc_id into the string. You should also use mysql_real_escape_string() on the session ID value to prevent SQL injection.
First print the variable $asc_id . If it displays nothing, session is unavailable . In that case you missed session_start() in top of the current executing page .
From the SQL query, you cannot replace the value of a variable inside single quoted string .
Use . symbol for mixing string value with variable or use double quoted string . I prefer first one .
For troubleshooting , simplest method is printing variable values. From the result , you will understand what is missing .
Thanks
Try this. from the comment you added, I modified it like this
session_start(); //add this if you did not do it yet
$asc_id = $_SESSION['asc_id'];
$rs = mysql_query("select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = '$asc_id'
and lname_fname_dob like '".
mysql_real_escape_string($_REQUEST['term']) .
"%' order by lname_fname_dob asc limit 0,10", $dblink);

Insert statement with CodeIgniter -- so confused

I'm doing well with CodeIgniter. I can do SELECT statements on my MySQL database with no problems at all. But, now I'm trying to do an INSERT statement.
Note that I have not tried an UPDATE statement yet.
After reading the docs, I'm so confused.
This is what I have:
contacts.php:
function add() {
//echo "<pre>";print_r($_POST);
$this->load->model('Contacts_model');
$this->Contacts_model->insertContact($_POST);
}
contacts_model.php:
function insertContact($_POST) {
//echo "<pre>";print_r($_POST);
$title = $_POST['title']; // I can echo this here. It works
$f_name = $_POST['f_name']; // I can echo this here. It works
$sql = "INSERT INTO contacts (title,f_name) " .
"VALUES (" .
$this->db->escape($title) .
"," .
$this->db->escape($f_name) .
")";
$this->$db->query($sql);
}
I've read about Active Record, but if that's what is messing me up, then I still don't realize what I'm doing wrong. All of the examples look exactly like mine.
Help?
EDIT
$sql = "INSERT INTO contacts (title,f_name) VALUES ('$this->db->escape($title)','$this->db->escape($f_name)'";
$this->$db->query($sql);
I've also tried it like this. And many other variants. It doesn't seem to be my syntax... I think.
Your query is fine, only reason that why query is not being executed is that you are using this:
$this->$db->query($sql);
there is nothing like $db, just use this:
$this->db->query($sql);
I'm sure this is the problem, but if it is not then please kindly post the error what it is giving. Thanks.
Hope this helps.
You missed the quote character:
$title = $this->db->escape($title);
$fname = $this->db->escape($f_name)
$sql = "INSERT INTO contacts (title,f_name) " .
"VALUES ('{$title}', '{$fname}')";
$this->db->query($sql);
BTW, What the hell with the $_POST variable? It's one of SuperGlobal variable. You don't have to transfer it in parameter. You can always safely call it anywhere in your script.
Another note, since you use CodeIgniter, you better check out the Input class library and use it for all your input need.
Why send $_POST? Use $this->input->post("param_name") and in your instance "$this->load->model('Contacts_model');" in my practice i use "$this->load->model('Contacts_model','instance',[true or false]);" the last parameter is optional (to connect with the DB if you don't use autoload option).
Use this:
function insertContact() {
$title = $this->input->post("title");
$f_name = $this->input->post("f_name");
$sql = "INSERT INTO contacts (title,f_name) " .
"VALUES ('" . $this->db->escape($title) . "','".$this->db->escape($f_name) ."')";
$this->$db->query($sql);
}
DON'T USE $_POST! (And use the Active Record read the user guide)

Categories