php using eval to obtain an objects attribute value - php

I am trying to set a function that will dynamically update an object attribute in the db w/o updating the whole object.
$sql = "UPDATE " . self::$table_name . " SET ";
$sql .= "$attribute = '" . eval("\$this->$attribute;") . "'";
$sql .= " WHERE ...";
I cant seem to get this eval("\$this->$attribute;") to produce the object attribute value. There is a value in the attribute and it is a public attribute.
Thanks
$attribute is a function var that will contain a string like 'address_id' so I want
UPDATE table_name SET address_id = '11' WHERE user_id='1'
This is a simple example of it

You don't need to do this using eval. PHP supports variable variables: http://php.net/manual/en/language.variables.variable.php
So this will do:
$this->$attributes
Note the second $ sign. This basicly means the value of $attributes is used as attribute name. If you want it to write a bit clearer you can do so using brackets:
$this->{$attributes}
This bracket is required if you wanted to do this using an array, or if you wanted to use multiple variables to build a variable name like this:
$this->{$var1}_{$array[0]}_{$var2}
This goes probably behind the scope of this question, but its good to know what variable variables are. But i don't recommend using them, because it makes the code unreadable and hard to understand.

There's no need to use eval():
$sql = "UPDATE " . self::$table_name . " SET ";
$sql .= "$attribute = '" . $this->attribute . "'";
$sql .= " WHERE ...";
If attribute is a variable, use:
$this->$attribute
Are you sure $this->attribute is sanitized correctly?

Related

Escape a literal so that it is wrapped with double quotes

We use doctrine 2 and want to write parameterised code like this:
attributes #> \'{' . $con->quote($attrId) . ':' . (int)$value . '}\'';
to have a query like this:
WHERE attributes #>'{"color":14}';
The "color" is the custom (user chosen) name of an attribute. So I feel that quote() is an appropriate function to shield it. But it wraps a parameter with single quotes, what makes the request syntax incorrect.
quoteIdentifier() function wraps with double quotes, BUT I'm not sure if it's right to use it in this context.
How to build a safe code to get the request I need?
Here is a way to do it with json_build_object and pg_exec_params:
<?php
$dbconn = pg_connect('');
$data = 'some"th\'ing';
pg_query_params($dbconn, 'SELECT json_build_object($1::text, $2::integer)', [$data, 14]);
?>
You need the explicit type casts so that PostgreSQL knows whether the argument is a string or a number.
You can include the double quotes in the string.
$attr = '{"' . $attrId . '":' . (int) $value . '}';
Don't depend on quoting to keep you safe, but instead execute the query with a method that binds the value to a prepared statement.
$statement = $con->executeQuery('SELECT * FROM your_table WHERE attributes #> ?', [$attr]);

Calling PHP functions from within the same file

I have a php file called choose.php where inside i echo some HTML i.e. a select element.
I am using PDO to populate the select element from a mysql database.
the code i have written works perfectly but when i put it into a function and try to call it i get an error telling me that i cannot declare said method again.
the code is thus:
echo '<select>';
$sql = "SELECT name FROM people";
$res = $conn->prepare($sql );
$res ->execute();
while ( $row = $res ->fetch() )
{
echo '<option value = "' . $row['name '] . '">' . $row['name '] . '</option>';
}
echo '</select>';
in other words the function would look like this:
function getnames()
{
$sql = "SELECT name FROM people";
$res = $conn->prepare($sql );
$res ->execute();
while ( $row = $res ->fetch() )
{
echo '<option value = "' . $row['name '] . '">' . $row['name '] . '</option>';
}
}
Why cant i call the method inside the echoed select element?
echo '<select>';
getnames();
echo '</select>';
Also how would i accomplish this by placing the method in another php file to keep it tidy?
Why cant i call the method inside the echoed select element?
Because the method body references $conn, which is supposedly a global variable and not in scope inside the method body. You can verify that this is the problem (and "fix" it) with
function getnames()
{
global $conn;
// the rest as before
}
Now, although this will make the problem go away, what you propose here is not a good way to organize things. There are several issues:
getnames uses a global variable ("invisible argument") -- note that you would not have had reason to ask this question if this had been corrected!
The name of the method is misleading -- it doesn't "get" something, it prints HTML.
The method is unusable for anything else other than its specific purpose -- if you wanted to do something else with the names (e.g. print a table) you would have to write another method.
You are interleaving straight HTML output (the <select> tag) with business logic (querying the database). It's better to do all the business logic up front (keep the results you need in variables) and then do the HTML all in one go.
All of the above are serious deficiencies of the chosen approach and none of them would be present in a well built application. I suggest that instead of making the problem go away you would be better served by refactoring the code to address these, and the problem will fix itself on the way.
Code Review would be an excellent place to ask a question along the lines of "I have this code and this recommendation -- how would I implement it properly?" if you need extra help.
You are trying to access $conn variable which is not available in your function scope.
To access $conn variable inside your function use global, like below:
global $conn;
How are you loading the file in which the getnames function is defined? Try using require_once and making sure it's not being included more than once - already defined means it's be defined and the file is being called again, hence trying to define it again
If you're calling that same code multiple times on your page it will get very heavy to load. I would recommend just running it at the top of the page and putting the data to a variable, then echoing that variable at each location that you need it
So your code in the top of your page
$sql = "SELECT name FROM people";
$res = $conn->prepare($sql );
$res ->execute();
$outputData = '';
while ( $row = $res ->fetch() ){
$outputData .= '<option value = "' . $row['name '] . '">' . $row['name '] . '</option>';
}
Then
echo '<select>'.$outputData.'</select>';

issue when inserting variable value to MySQL table

Hey I am currently trying to insert a global variable to a table. The other values I pass are variables too but they get sent correctly.
Here is my query. my error handling does not capture anything
$result = mysql_query("INSERT INTO IPmanagement (userId, NameUsed, EmailUsed, IPStatus, Ip) VALUES ('" .$masterUserId . "', '" . $Entry['LeadName'] . "', '" . $Entry['LeadEmail'] . "', '0', '" . $ip . "')") or die(ErrorException("Function 6", "Error when processing the current lead. your data is unaffected and if the proccess continues please contact an Admin.", mysql_error(),$_SERVER['REMOTE_ADDR'], CurrentPath(), $masterUserId));
my variable that is global defined before the function is
$masterUserId = "1";
I tried echoing the variable before it sends and it echos out correctly YET my table holds a value of 0.
here is a screenshot of how I have my table setup.
Click for Larger Image
Any idea what is going on. I am rather stumped and tried writing this same code different ways and it still gives me same issue. Also $masterUserId will always be an int value
Edit: also would like to mention the variable is different .php that contains the varaiable and database login information. It is being included at the top. (don't know if that is relevant)
Because you are not inserting IP STATUS.Which is not null
\
You should either set this to null or enter some value to it.
If you are using query in a function than use like this
function (){
//than define
$globat $masterUserId;
// use the global defination
// than use this variable with global value
}
Do not use mysql_*. Replace them with mysqli_* or PDO::.
Did you try to echo the mysql_query()? Do this. Replace mysql_query("..."); with die("..."); and put it in the phpMyAdmin and try executing.
And in your table, I see that IP Status is a NOT NULL. So that might throw an exception. Use a default value in the table.
And yeah, what do you get the result as in mysql_error()?
Why ''' or "' in query?
I have cleaned up query with PHP function sprintf and using NULL for EntryID(Autoincrement)
$query = sprintf("INSERT INTO IPmanagement (EntryID,userId, NameUsed, EmailUsed, IPStatus, Ip) VALUES (NULL,%s,%s,%s,'0',%s)",
$masterUserId , $Entry['LeadName'] , $Entry['LeadEmail'] , $ip ));
$result = mysql_query($query);
You should also use MySQLi or PDO

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