Let's say I have these two variables
$number = 1;
$word = "one";
and I want to use them in a pg_query.
This is what I've got:
$result = pg_query($con, 'UPDATE a SET z = ARRAY[{$number}] WHERE word = {pg_escape_literal($word)}');
But it doesn't work..
To use string interpolation, you have to use double quotes:
$x = 3;
"This works: $x" // This works: 3
'This does not: $x'; // This does not: $x
You also can't interpolate function calls into strings like you're attempting with {pg_escape_literal($word)}. You'll need to escape the variable before interpolating it into the string:
$word_esc = pg_escape_literal($word);
$result = pg_query(
$con,
"UPDATE a SET z = ARRAY[$number] WHERE word = $word_esc"
);
You could also use sprintf:
$result = pg_query(
$con,
sprintf(
"update a set z=ARRAY[%d] where word = %s",
$number,
pg_escape_literal($word)
)
);
But the best and safest is to use pg_query_params function, as you don't escape any parameter. And it is very easy to forget and expose your site to SQL-injection attacks.
$result = pg_query_params(
'update a set z=ARRAY[$1] where word = $2',
array($number,$word)
)
Use double instead of single quotes: Double quoted strings expand variables into their values.
Related
how to use preg_replace in MySQL query.
"SELECT * FROM video_master WHERE preg_replace( '/\s+- /', ' ', trim($title))"
You need use like this
$pattern = "/\s+- /";
$title= preg_replace($pattern,'',$string);
$query = " SELECT * FROM video_master WHERE column = '$title';";
I think you can use sprintf:
$pattern = "/\s+- /";
$query = sprintf("SELECT * FROM video_master WHERE column = '%s';", preg_replace($pattern,'',$string));
sprintf is always good for MySQL queries in PHP, you avoid create the incorrect dinamic queries, also I recommend you to use mysql_real_escape_string function, this function scapes the special characters of MySQL like apostrophe.
$pattern = "/\s+- /";
$query = sprintf("SELECT * FROM video_master WHERE column = '%s';", mysql_scape_real_string(preg_replace($pattern,'',$string)));
With this function and sprintf, you reduce the risk of a bad behavior or SQL injection attack in your application.
I hope this information helps you.
Good luck.
Is this the right way to escape a string just in case or I can insert string like this without additional escaping?
$filenamefordb = preg_replace('/[^A-Za-z0-9а-яА-Я_\.\-]/u', '', $filenamefordb);
$query = "INSERT INTO file SET filename='$filenamefordb";
I don't use mysqli_escape because I also need name without any quotes in another place
Why don't you escape the string using PDO?
<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Complex string */
$string = "Co'mpl''ex \"st'\"ring";
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>
This will output
Unquoted string: Co'mpl''ex "st'"ring
Quoted string: 'Co''mpl''''ex "st''"ring'
Reference:
http://php.net/manual/it/pdo.quote.php
you can escape it with a generic php function:
$filenamefordb = mysql_escape_string ($filenamefordb);
$query = "INSERT INTO file SET filename='$filenamefordb";
I have a form which is a select multiple input which POSTs values like this: option1,option2,option3 etc..
How is the best way to convert this to 'option1','option2','option3' etc...
Currenty I'm doing this, but it feels wrong??
$variable=explode(",", $variable);
$variable=implode("','", $variable);
The reason why I'm doing this is because I want to use the form select multiple inputs in a SQL Query using IN.
SELECT * FROM TABLE WHERE some_column IN ('$variable')
You can wrap whatever code in a function to make the "feels wrong" feeling disapear. E.g.:
function buildSqlInClauseFromCsv($csv)
{
return "in ('" . str_replace(",", "','", $csv) . "') ";
}
If $variable = "option1,option2,option3"
you can use:
"SELECT * FROM TABLE WHERE FIND_IN_SET(some_column, '$variable')"
Here is what I used:
WHERE column IN ('".str_replace(",", "','", $_GET[stringlist])."')
we know that implode converts array to string,we need to provide the separator and then array as shown below, here we have (coma ,) as a separator.
Implode breaks each element of an array with the given separator,I have conceited '(single quotes) with the separator.
$arr = array();
$arr[] = "raam";
$arr[] = "laxman";
$arr[] = "Bharat";
$arr[] = "Arjun";
$arr[] = "Dhavel";
var_dump($arr);
$str = "'".implode("','", $arr)."'";
echo $str;
output: 'raam','laxman','Bharat','Arjun','Dhavel'
There is only one correct way to escape strings for SQL - use the function provided by the database api to escape strings for SQL. While mysyl_* provides mysql_real_escape_string():
$choices = explode(",", $variable);
foreach($choices as &$choice)
$choice = "'".mysql_real_escape_string($choice)."'";
$choices = implode(",", $choices);
PDO provides a method that will add quotes at the same time:
$choices = explode(",", $variable);
foreach($choices as &$choice)
$choice = $pdoDb->quote($choice);
$choices = implode(",", $choices);
Note that PDO::prepare doesn't really work here
I am using php eval() function, below are my statements:
$uid = 8;
$str = 'SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid';
eval("\$str = \"$str\"");
die("$str");
//$query = $_SGLOBAL['db']->query($str);
//$result = $_SGLOBAL['db']->fetch_array($query);
The output is: SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid
That's to say the varibale $uid did not passed.
How to pass a variable into the evaluated string.
Thanks.
According to php manual: http://php.net/manual/en/function.eval.php
The code will be executed in the scope of the code calling eval().
Thus any variables defined or changed in the eval() call will remain
visible after it terminates.
So, if the variable you need is defined in the scope where you calleval(), everything should work as expected.
You can use this too, but it makes no sense and it's the wrong logic for using eval
Example 1:
<?php
$uid = 8;
$OUTPUT = '<?php $str = "SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid"; ?>';
eval(" ?> $OUTPUT <?php ");
echo $str;
exit;
?>
Example 2:
<?php
$uid = 8;
$str = '<?php $str = "SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid"; ?>';
eval(" ?> $str <?php ");
echo $str;
exit;
?>
you can't insert varuiable into single-quotet strings directly. try this:
$str = "SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid"; // double-quotet
or this:
$str = 'SELECT COUNT(*) FROM uchome_blog WHERE uid='.$uid; // string-concatenation
Variable substitution only works in double quoted strings.
Try this:
$uid = 8;
$str = "SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid"; # variable gets substituted here
eval("\$str = \"$str\"");
die("$str");
I think variable substitution is something that happens at parse time - it is not done recursively, so in your eval, the contents of $str is pasted into the string, but that isn't done a second time for the contents of $uid inside $str.
You are missing a semicolon.
Try this:
eval("\$str = \"$str\";");
I have a string of characters separated by many hashes (#). I need to get the individual words in between the hashes on php. here's what my code looks like:
$sql = "SELECT attribute_type.at_name,attribute_type.at_id FROM attribute_type
WHERE attribute_type.prodType_id = $pt_id
AND attribute_type.at_id NOT IN (SELECT at_id
FROM attribute_type
WHERE attribute_type.at_name = 'Product')";
while($items. strpos("#")>0){
// add the selected AT in every loop to be excluded
// .
// here tokens from $items are stored individually in
// $selectedAT (whose value changes in every loop/cycle)
//
// add to the current sql statement the values $at_id and $searchparam
$sql = $sql . "AND attribute_type.at_id NOT IN
(SELECT at_id FROM attribute_type
WHERE attribute_type.at_name = '$selectedAT')";
}
$dbcon = new DatabaseManager();
$rs = $dbcon->runQuery($sql);
explode creates an array by splitting a string on a given token
$words = explode("#", $items);
Now if you need to take these words you extracted from the string and use them to compare to some column in a SQL query...
$sql = "SELECT ... WHERE column IN ('" . implode("', '", $words) . "')";
You should not need to build a query in a loop as you are doing once you have the words in an array.
Even if you did want to do it that way, you don't want to create a subquery for every word when you could just OR the words together in one subquery.
Try strtok. Example paste:
$string = "This is\tan example\nstring";
$tok = strtok($string, " \n\t");
while ($tok !== false) {
echo "Word=$tok<br />";
$tok = strtok(" \n\t");
}
Do not use split as suggested in another answer (which has now been updated). It uses old POSIX regulat expressions and it's deprecated.
To split a string, use $words = explode('#', $items); which does not use a regular expression but a plain string.
Docref: http://php.net/explode