I have a PHP function that makes a query to MySQL DB.
function regEvent($event, $l)
{
$sqlz_upd="UPDATE {$event} SET f1a='$_POST[F1A"'.$l.'"]'";
The question is what is the syntax to use variable $l in $_POST[F1A$l]?
$condition = $_POST["F1A" . $l];
$sqlz_upd="UPDATE {$event} SET f1a='".mysql_real_escape_string($condition)."'";
This is how to use your dynamic post and be safe for Sql Injection.
Here you go:
$var = mysql_real_escape_string($_POST["F1A".$l]);
$sqlz_upd="UPDATE {$event} SET f1a='$var' ";
if you are using a string as key in an associative array. It should be enclosed in single or double quotes(though PHP won't give any error).
i.e. $_POST['F1A'. $l] or $_POST["F1A$l"]
my suggestion will be...
$sqlz_upd="UPDATE {$event} SET f1a='" . $_POST["F1A$l"] . "'";
Related
I have a variable defined as an array, which is built in a loop:
$years=array("2010","2011","2012");
foreach($years as $year)
{
///an SQL query + some PDO that queries a different table based on $year
$dataset_full_{$year} = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
so you end up with a set of arrays named
$dataset_full_2010
$dataset_full_2011
$dataset_full_2012
when I print_r($dataset_full_2012); however I get nothing, but if I go ahead and define
$current_year="2012";
then
print_r($dataset_full_{$current_year});
I get my array. What piece of syntax am I misusing here?
Thanks in advance
To be safe, you can always use an intermediate string:
$var_name = "dataset_full_" . $year;
$$var_name = $stmt->fetchAll(PDO::FETCH_ASSOC);
You can also use concatenation within curly braces:
${"dataset_full_" . $year} = ...
Here's the docs
I'm having some trouble with what I believe should be some fairly simple PHP. It's run inside of WordPress, but the question shouldn't be WordPress specific. The $wpdb->get_results() is just a way to query the WordPress database without having to use a connection string. I also use a couple of $_GET commands.
Here's what I have so far:
$Data = $wpdb->get_results("SELECT *
FROM database.table
WHERE sem.MonthNum >= " .$_GET["minMonth"]. "
AND sem.MonthNum <= " .$_GET["maxMonth"]. "
AND sem.Year >= " .$_GET["minYear"]. "
AND sem.Year <= " .$_GET["maxYear"]. ");
This works, so long as the $_GET is populated. I'd like to add a kind of default value such that if $_GET is empty, a number is set, and if it's not empty, it grabs that number. Something along the lines of...
$Data = $wpdb->get_results("SELECT *
FROM database.table
WHERE sem.MonthNum >= " if(!$_GET){echo 1;} else {echo ".$_GET[\"minMonth\"]. "} "
But that doesn't work for me...probably some silly PHP syntax error, I'm not sure about all the echo statements and the quotes within other quotes and whatnot.
For each of your variables do this:
$minMonth = isset($_GET["minMonth"]) ? intval($_GET["minMonth"]) : 1;
...
"WHERE sem.MonthNum >= " .minMonth. "
The intavl() call will make convert the $_GET value to an integer if it is not already, which will protect you from SQL injection security issues. If you need to do something similar with strings, use something like mysql_escape_string() instead.
You could add a variable for each, for example:
// If not set $minMonth is set to 1
$minMonth = (isset($_GET['minMonth']) ? $_GET['minMonth'] : 1);
Just do this for the other variables as well.
You can use short hand notation like Scott and David show directly in your query:
$Data = $wpdb->get_results("SELECT *
FROM database.table
WHERE sem.MonthNum >= ".(!isset($_GET['minMonth'])?'1':$_GET['minMonth'])."
AND...
You really need to sanitize the variables first though, otherwise you could be SQL injected very easily.
ingHey guys.
I am wonder the correct syntax for using a $_POST statement in a while loop.
I have written this.
$result_i = $_POST['result_i'];
while ($result_i > 0){
//Get Post Values
$driver = $_POST['driver_update_".$result_i."'];
$BookingID = $_POST['ID_".$result_i."'];
$Task_No_update = $_POST['Task_No_update_".$result_i."'];
//SQL
$driver_update = mysql_query("UPDATE booking SET driver = '$driver', TaskNo= '$Task_No_update' WHERE BookingID = '$BookingID' " );
}
The problem I have is:
$_POST['driver_update_".$result_i."'];
Is it possible to write $_POSTS statements in this way.
Cheers.
The problem is you cannot interpolate variables in single-quoted strings.
Try concatenation instead
$_POST['driver_update_' . $result_i]
or use double-quotes and variable enclosures
$_POST["driver_update_{$result_i}"]
See http://www.php.net/manual/en/language.types.string.php
Also, that looks like an infinite loop as $result_i never changes.
You don't need to wrap everything in quotes here
$driver = $_POST["driver_update_" . $result_i];
$BookingID = $_POST["ID_" . $result_i];
$Task_No_update = $_POST["Task_No_update_" . $result_i];
I'm trying to insert into a database a field called Id_Obj and it's a VarChar but when I try to send it I get an error:
Unknown Column 'Id_Obj4' in 'field List'
The insert looks like this:
while($info=mysql_fetch_Array($data))
{
print "name :".$info['Id']." ";
$count=$info['Id'];
}
$t = "INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES(";
$t = $t."IdObj$count".",".$_GET["ns"];
$t = $t.")";
mysql_query($t);
The fields in the database are Id, Id_Obj, Num_Sides.
Couple of things:
You really want to make sure that
your values are escaped
You're missing out on your last ")"
in the query
Your strings need to be wrapped in
quotes, otherwise it thinks you're
using a table name
Your SQL can be like:
$t ="INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES('IdObj4','". $_GET["ns"]. "')";
Also, just as a side so you know the shortcut:
$t = $t . " something added"; is the same as $t .= " something added"
You need to wrap strings with single quotes in SQL.
$ns = intval($_GET('ns')); // This should sanitize $ns enough for the db.
if ($ns > 0)
{
$t="INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES(";
$t = $t."'IdObj4'".",".$ns . ")";
mysql_query($t);
}
You also forgot the closing parenthesis.
I have modified your code to be more resistant to SQL Injection in a very simple way. If you intend to make the Id_Obj a variable as well, you should consider using mysql_real_escape_string() to escape the value for use in your SQL statement.
When you are in a situation where your insert query is so small like this, why you don't use everything in a single line? It saves you from a lot of small problems.. I think #Mark solved your problem.
Let's say I have a query:
" SELECT * FROM table
WHERE donor_id = " .$this->session->userdata('id') ."
GROUP BY rating"
However, it appears that I get a mysql syntax error here, citing that $this->session->userdata('id') gives me '25' for example, instead of 25. Are there any workarounds here to prevent $this->session->userdata('id') from being quoted?
Thanks.
In CI, I do this all the time:
$id = intval($this->session->userdata('id'));
$sql = " SELECT * ".
" FROM table ".
" WHERE donor_id = {$id} ".
"GROUP BY rating ";
//process $sql below
Creating query like this will make you easier to spot bug and prevent SQL injection. Use concatenation when you need to split query to multiple lines instead of make it a long multiple string is to prevent the actual query string got too long. Indent the SQL keyword is to make it easier spot logical and syntax bug.
intval($this->session->userdata('id'))
Assuming you mean that it is returning you a string instead of an integer you could always try using settype or intval:
$var = '2';
settype($var, "integer");
$var = intval($var);
However, if you mean that the quotes are for some reason hard-coded in, you could do a string replace, if you are sure that the value will not contain quotes:
ech str_replace("'", "", "'2'"); // prints 2