I use str_replace and does not work properly.
I have a QueryString I want to replace some of the words with the amount of input, but the str_replace method does not work and does not change anything.
$inputdata = json_decode(file_get_contents('php://input'), true);
$query2 = $inputdata["QueryString"] . $where . " ORDER BY " .$inputdata["DataRequest"]["Sort"][0]["field"]." " .$inputdata["DataRequest"]["Sort"][0]["dir"]. " LIMIT ".$inputdata["DataRequest"][take]." OFFSET " .$inputdata["DataRequest"][offset];
for ($x = 0; $x < count($parameters); $x++) {
$query2 = str_replace($inputdata["parameters"][$x][key],$inputdata["parameters"][$x][value],$query2);
}
query2return :
" SELECT Members.*, HouseholdAdmin.AdminCode FROM Members JOIN HouseholdAdmin ON Members.HouseholdAdminId=HouseholdAdmin.HouseholdAdminId WHERE MemberId =%MemberId "
str_replace($inputdata["parameters"][$x][key],$inputdata["parameters"][$x][value],$query2); not work
$query2 = str_replace('%MemberId','2',$query2); not work.
$query2 = str_replace('SELECT','dsdfsdfsdf',$query2); not work.
$query2 = str_replace('anyThing','anyThing',$query2); not work.
,....
It does not matter which words I enter & replace in str_replace, nothing works.
$query2 = str_replace($inputdata["parameters"][$x][key],$inputdata["parameters"][$x][key],$query2);
$query2 = str_replace('%MemberId','2',$query2);
$query2 = str_replace('SELECT','dsdfsdfsdf',$query2);
$query2 = str_replace('anyThing','anyThing',$query2);
Related
I'm working on a search query and i hit a little bump... So as you see in the code below, i'm adding values to a array to execute it later in the script, but it's not really working... So when i var_dumped all of this, it returned like it is supposed to but the :q was not changed to the value which was entered in the link.
$query = "SELECT * FROM articles";
$columnsQuery = [];
$values = [];
if(isset($_GET['q']) && !empty($_GET['q']))
{
$columnsQuery[] = " WHERE MATCH (title) AGAINST (':q' IN NATURAL LANGUAGE MODE)";
$values[":q"] = $_GET['q'];
}
$fullQuery = $query . implode(" ", $columnsQuery)
. " ORDER BY id DESC"
. " LIMIT {$paginator->getLimitSQL()}";
$getArticles = $db->prepare($fullQuery)->execute($values);
$query = "SELECT * FROM articles";
$columnsQuery = [];
$values = [];
if(isset($_GET['q']) && !empty($_GET['q']))
{
$columnsQuery[] = " WHERE MATCH (title) AGAINST (':q' IN NATURAL LANGUAGE MODE)";
$values["q"] = $_GET['q']; // TRY WITHOUT COLON
}
$fullQuery = $query . implode(" ", $columnsQuery)
. " ORDER BY id DESC"
. " LIMIT {$paginator->getLimitSQL()}";
$getArticles = $db->prepare($fullQuery)->execute($values);
You should not use colon in the place of $values["q"] = $_GET['q'];
$query = "SELECT * FROM articles";
$columnsQuery = [];
$values = [];
if(isset($_GET['q']) && !empty($_GET['q']))
{
$columnsQuery[] = " WHERE MATCH (title) AGAINST (':q' IN NATURAL LANGUAGE MODE)";
$values["q"] = $_GET['q']; // TRY WITHOUT COLON
}
$fullQuery = $query . implode(" ", $columnsQuery)
. " ORDER BY id DESC"
. " LIMIT {$paginator->getLimitSQL()}";
$getArticles = $db->prepare($fullQuery)->execute($values);
$query = "SELECT * FROM articles";
$values = array();
if(!empty($_GET['q'])) {
$query .= " WHERE MATCH (title) AGAINST (q IN NATURAL LANGUAGE MODE)";
$db->bindParam(':q', $_GET['q']);
}
$fullQuery = $query . " ORDER BY id DESC" . " LIMIT {$paginator->getLimitSQL()}"
$getArticles = $db->prepare($fullQuery)->execute();
So after a while i figured it out, You're not supposed to use parameters while binding in the query, and like #Poiz pointed out i shouldnt use colons in the array either
Thx to everyone who tried helping :)
I have created an editable database to help me automate weekly member updates. There are 9 values that each member updates each week, these are controlled by $_POST submit to secondary php.
From that php, the post values are set as php var, then used to UPDATE sql db.
mysql_select_db("web_footy1") or die(mysql_error());
// The SQL statement is built
$strSQL = "UPDATE Round_6 SET ";
$strSQL = $strSQL . "Game1= '$Game1', ";
$strSQL = $strSQL . "Game2= '$Game2', ";
$strSQL = $strSQL . "Game3= '$Game3', ";
$strSQL = $strSQL . "Game4= '$Game4', ";
$strSQL = $strSQL . "Game5= '$Game5', ";
$strSQL = $strSQL . "Game6= '$Game6', ";
$strSQL = $strSQL . "Game7= '$Game7', ";
$strSQL = $strSQL . "Game8= '$Game8', ";
$strSQL = $strSQL . "Game9= '$Game9' ";
$strSQL = $strSQL . "WHERE Member = '$Member' ";
// The SQL statement is executed
mysql_query($strSQL) or die(mysql_error()) ;
Yes, i am aware this is subject to SQL injection, it is a private site so security can wait atm
The problem is that all values are update at same time, and to update one, you need to re enter all otherwise they are replaced with empty value.
So my question in twofold.
A) What is the cleanest way to be able to control each variable separately,
B) Can i, and if so, how to use isset($GameX) to control which queries are executed.
Eg
IF (isset($Game1)) {UPDATE Round6 SET Game1='$Game1' WHERE Member='$Member'} ;
Please keep in mind, 3 weeks ago i knew nothing about coding, and have crash coursed in html, php and sql in that time... Cheers
I really really really can't recommend enough that you FIX your SQL injection.
Having said that, you can programatically add conditions to your UPDATE clause.
An example might be the following snippet:
<?php
$Game3 = "things";
$Game5 = "stuff";
$Game6 = "awesome";
$Member = 'ben';
$update_parts = array();
for ($game_counter = 1; $game_counter < 10; $game_counter++) {
$variable_name = "Game" . $game_counter;
if ( isset($$variable_name) ) { // This is like isset($Game1)
$update_parts[] = "Game" . $game_counter . " = '" . $$variable_name . "'";
}
}
if ( sizeof($update_parts) > 0 ) {
$strSQL = "UPDATE Round_6 SET ";
$strSQL .= implode(", ", $update_parts);
$strSQL .= " WHERE Member = '$Member'";
echo $strSQL;
}
I've put in a couple of variables up the top there. This yields the following SQL:
UPDATE Round_6 SET Game3 = 'things',
Game5 = 'stuff', Game6 = 'awesome' WHERE Member = 'ben'
EDIT: If you want to use PDO, you need the Query and the Parameters separated. In my example below, I'm putting the Query parameters in
$conn = new PDO("mysql:host=localhost;dbname=database;","username","password"); // Your Connection String
$update_parts = array();
$query_params = array();
for ($game_counter = 1; $game_counter < 10; $game_counter++) {
$variable_name = "Game" . $game_counter;
if ( isset($$variable_name) ) { // This is like isset($Game1)
$update_parts[] = "Game" . $game_counter . " = ?";
$query_params[] = $$variable_name;
}
}
if ( sizeof($update_parts) > 0 ) {
$strSQL = "UPDATE Round_6 SET ";
$strSQL .= implode(", ", $update_parts);
$strSQL .= " WHERE Member = ?";
$query_params[] = $Member;
// Here is where you'd run the update
$stmt = $conn->prepare($strSQL);
$stmt->execute($query_params); // Notice I'm passing in the parameters separately
}
I am setting a variable that contains an array as a constraint to a SELECT sql statement. However the constraint seems only to apply to one piece of data in the array. Why is this?
Code below:
<?php
include 'connection.php';
$Date = $_POST['date'];
$Unavail = 0;
$Avail = 0;
$Availid = 0;
$low = 99999;
$query = "SELECT username FROM daysoff WHERE date = '$Date'";
$dayresult = mysql_query($query);
while($request = mysql_fetch_array($dayresult)) {
$Unavail = $request;
echo "<span>" . $Unavail['username'] . " is unavailable.</br>";
}
$query1 = "SELECT Username, name, work_stats FROM freelance WHERE Username != '$Unavail[username]'";
$dayresult1 = mysql_query($query1);
while($request1 = mysql_fetch_array($dayresult1)) {
echo "<span>" . $request1['name'] . " is available.</br>";
if ($request1['work_stats']<=$low) {
$low = $request1['work_stats'];
$Availid = $request1['name'];
}}
echo "<span>" . $Availid . " is available on " . $_POST['date'] . " and is on workstat level " . $low . ".</span></br>";
?>
The output shows two names in the first echo but then shows one of those names as available in the second echo (these echos are only in place as part of my testing),
Many Thanks
The first query can have multiple results.
SELECT username FROM daysoff WHERE date = '$Date'
Let's say if gives two rows: Dave and John.
You're only keeping the last record so it will seem like Dave is available.
You should probably do something like:
$query = "SELECT username FROM daysoff WHERE date = '$Date'";
$dayresult = mysql_query($query);
$unavailable_users = array();
while($request = mysql_fetch_array($dayresult)) {
$unavailable_users[] = $request["username"];
echo "<span>" . $Unavail['username'] . " is unavailable.</br>";
}
$query1 = "SELECT Username, name, work_stats FROM freelance
WHERE NOT Username IN ('" . implode("','", $unavailable_users) . "')";
// etc
Or in one go with a LEFT JOIN:
SELECT `Username`, `name`, `work_stats`
FROM `freelance`
LEFT JOIN `daysoff` ON `freelance`.`Username` = `daysoff`.`username`
AND `daysoff`.`date` = '$Date'
WHERE
`daysoff`.`username` IS NULL
This query is not returning any result as there seems to be an issue with the sql.
$sql = "select region_description from $DB_Table where region_id='".$region_id."' and region_status =(1)";
$res = mysql_query($sql,$con) or die(mysql_error());
$result = "( ";
$row = mysql_fetch_array($res);
$result .= "\"" . $row["region_description"] . "\"";
while($row = mysql_fetch_array($res))
{
echo "<br /> In!";
$result .= " , \"" . $row["region_description"] . "\"";
}
$result .= " )";
mysql_close($con);
if ($result)
{
return $result;
}
else
{
return 0;
}
region_id is passed as 1.
I do have a record in the DB that fits the query criteria but no rows are returned when executed. I beleive the issue is in this part ,
region_id='".$region_id."'
so on using the gettype function in my php it turns out that the datatype of region_id is string not int and thus the failure of the query to function as my datatype in my tableis int. what would be the way to get parameter passed to be considered as an int in php. url below
GetRegions.php?region_id=1
Thanks
Try it like this:
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
The region_id column seems to be an integer type, don't compare it by using single quotes.
Try dropping the ; at the end of your query.
First of all - your code is very messy. You mix variables inside string with escaping string, integers should be passed without '. Try with:
$sql = 'SELECT region_description FROM ' . $DB_Table . ' WHERE region_id = ' . $region_id . ' AND region_status = 1';
Also ; should be removed.
try this
$sql = "select region_description from $DB_Table where region_id=$region_id AND region_status = 1";
When you are comparing the field of type integer, you should not use single quote
Good Luck
Update 1
Use this.. It will work
$sql = "select region_description from " .$DB_Table. " where region_id=" .$region_id. " AND region_status = 1";
You do not need the single quotes around the region id i.e.
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
if i have 4 variables and i want to select DISTINCT values form data base
<?php
$var1 = ""; //this variable can be blank
$var2 = ""; //this variable can be blank
$var3 = ""; //this variable can be blank
$var4 = ""; //this variable can be blank
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE **keywords ='$var1' OR author='$var2' OR date='$var3' OR forums='$var4'** ");
?>
note: some or all variables ($var1,$var2,$var3,$var4) can be empty
what i want:
i want to neglect empty fields
lets say that $var1 (keywords) is empty it will select all empty fileds, but i want if $var1 is empty the result will be like
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE author='$var2' OR date='$var3' OR forums='$var4' ");
if $var2 is empty the result will be like
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE keywords ='$var1' OR date='$var3' OR forums='$var4' ");
if $var1 and $var2 are empty the result will be like
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE date='$var3' OR forums='$var4' ");
and so on
Try this.
$vars = array(
'keywords' => '', // instead of var1
'author' => '', // instead of var2
'date' => '', // instead of var3
'forums' => '', // instead of var4
);
$where = array();
foreach ($vars as $varname => $varvalue) {
if (trim($varvalue) != '') $where[] = "`$varname` = '" . mysql_real_escape_string($varvalue) . "'";
}
$result = mysql_query("SELECT DISTINCT title, description FROM table WHERE " . join(" OR ", $where));
Thanks alot every one specially experimentX .. Your answer helped me to get the right function i Just replaced (isset) with (!empty) .. Then every thing will be more than OK
$vars = array(
(!empty($_GET["var1"]))? " keyword = '". $_GET["var1"] ."' ": null,
(!empty($_GET["var2"]))? " author = '". $_GET["var2"] ."' ": null,
(!empty($_GET["var3"]))? " date = '". $_GET["var3"] ."' ": null,
(!empty($_GET["var4"]))? " forums = '". $_GET["var4"] ."' ": null
);
function myfilterarray($var)
{
return !empty($var)?$var: null;
}
$newvars = array_filter($vars, 'myfilterarray');
$where = join(" OR ", $newvars);
$sql = "SELECT DISTINCT title, description FROM table ".(($where)?"WHERE ".$where: null);
echo $sql;
with this function if there is empty variable it will be neglected
Thanks again every one for your helpful suggestion
make your select statement string before you call mysql_query(...) so do something along the lines of this:
$queryString = "Select DISTINCT title, description FROM table WHERE";
if(!empty($var1))
$queryString .= " keywords = $var1";
and so forth for all of your variables. you could also implement a for loop and loop through your $var1 - $var# and check for !empty($var#)
Why do you not simply build a if else structure?
Like
if ($var1!="" && $var2!="" && $var3!="" && $var4!=""){
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE keywords ='$var1' OR author='$var2' OR date='$var3' OR forums='$var4' ")
} else if ($var2!="" && $var3!="" && $var4!=""){
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE author='$var2' OR date='$var3' OR forums='$var4' ");
} else if {
...
}
(I just posted the below in his duplicate post, so I'm re-posting the below here)
Forgive me if anything is wrong, it's very late here and I just typed this in notepad on Windows, without an environment to test on. * Use with caution * :)
$vars = array(
'blah1' => '',
'blah2' => '',
'blah3' => '',
);
$sql_statement = "SELECT first, last FROM names WHERE";
$clause = "";
foreach($vars as $k=$v)
{
$k = trim($k);
if(!empty($k))
{
$clause .= " `$k` = '$v' OR";
}
}
$clause = rtrim($clause, "OR");
// $clause should have what you want.
Well, there are manu ways of doing this but the shortest way I have found is creating an array of the following form
$vars = array(
(isset($_GET["var1"]))? " keyword = '". $_GET["var1"] ."' ": null,
(isset($_GET["var2"]))? " author = '". $_GET["var2"] ."' ": null,
(isset($_GET["var3"]))? " date = '". $_GET["var3"] ."' ": null,
(isset($_GET["var4"]))? " forums = '". $_GET["var4"] ."' ": null
);
function myfilterarray($var)
{
return !empty($var)?$var: null;
}
$newvars = array_filter($vars, 'myfilterarray');
$where = join(" OR ", $newvars);
$sql = "SELECT DISTINCT title, description FROM table ".(($where)?"WHERE ".$where: null);
echo $sql;
Your result for http://localhost/?var1=sadfsadf&var2=sadfasdf&var3=asdfasdf
SELECT DISTINCT title, description FROM table WHERE keyword =
'sadfsadf' OR author = 'sadfasdf' OR date = 'asdfasdf'
Your result for http://localhost/?
SELECT DISTINCT title, description FROM table