There are two columns in the database table "system". I have the systemId and want to get the mobileSystemId. But the variable $mobileSystemIds which I already defined as global is always empty.
EDIT: Now array_map doesn´t work. I always get my Exception output "Arrayfehler ArrayMap"
I have the following code :
$mobileSystemIds=array();
function getMobileSystemId($systemId)
{
global $mysqli;
global $mobileSystemIds;
$query="SELECT mobileSystemId FROM system WHERE systemId ='" .$systemId ."'";
if(!$result=$mysqli->query($query))
{
echo "Datenbankfehler DB-QUery";
exit(0);
}
if (!$mobileSystemId=$result->fetch_assoc())
{
echo "Datenbankfehler DB-Fetch";
exit(0);
}
$mobileSystemId=$mobileSystemId["mobileSystemId"];
echo "mobile System ID: " .$mobileSystemId ."<br />";
return $mobileSystemId;
}
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
In this case, using a return in your function would be much cleaner.
Nothing to do with your problem, but is your $systemId var trusted ? (To prevent SQL injection).
Update:
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
ought to read (just checked; it works for me):
$mobileSystemIds = array_map('getMobileSystemId', $systemsList);
if (empty($mobileSystemIds))
{
if (empty($systemsList) || !(is_array($systemsList)))
echo "OK: no mobile IDs, but no systems either";
else
echo "THIS now is strange :-(";
}
else
{
echo "Alles OK";
var_dump($mobileSystemIds);
}
I tried this by returning a dummy value based on input; if it does not work for you, there must be something strange in the database.
(Update: the text below refers to your original code, which did not use array mapping)
Your code ought to be working as it is. You put several $mobileSystemId 's into a single $mobileSystemId.
It works: I tested with a simpler code, removing the DB calls but leaving your code, and spelling, untouched.
So, the error must be elsewhere. I would guess that this code is included into something else, and:
the $mobileSystemIds = array(); declaration gets executed more than once, thereby losing all its data;
the $mobileSystemIds = array(); declaration is itself included in a more local scope and you read it from outside, reading an empty value or a totally different value.
Try replacing the first part of your code with:
GLOBAL $mobileSystemsIds;
if (defined($mobileSystemsIds))
trigger_error("mobileSystemsId defined more than once", E_USER_ERROR);
else
$mobileSystemsIds = array();
and also, in the function body:
if (!defined($mobileSystemsId))
trigger_error("mobileSystemsId should have been defined", E_USER_ERROR);
Related
hello am still learning php and trying to call php function by url link and i did found this code
if(function_exists($_GET['f'])) {
$_GET['f']();
}
but it's not safe for my function so i did something like that
if($_GET['f']=='mouner'){
function mouner(){
$s = 'my name is mouner';
return($s);
}
echo mouner();
}
is that safe code ? and if it's not what is the best way to call function by url with no security risk
As #JuliePelletier suggested, you need to check your user input before executing any functions associated to it. Another handy way might be something like this:
$funcs["foo"] = function()
{
echo "In foo function";
};
$funcs["bar"] = function()
{
echo "In bar function";
};
if (isset($funcs[$_GET["f"]]))
$funcs[$_GET["f"]]();
Store the functions (either anonymous or just by their name) in an associative array of allowed functions and just execute those.
You are right that the first option is extremely risky, which is why you need to validate user inputs (including GET parameters).
Your second option does exactly that. The code is not perfect but does solve that serious vulnerability.
Julie has the right answer, just offering up some code cleanup:
if($_GET['f'] == 'mouner'){
$s = 'my name is mouner';
echo $s;
}
If you expect the result to have a lot of variation, could make use of switch() like so:
if(isset($_GET['f'])){
$s = "My name is ";
switch($_GET['f']){
case 'mouner':
$s .= "Mouner";
break;
}
echo $s;
}
I have a function, that check user language and write it down in a variable. After a time, i come of idea to merge they, so that i need a call the function anytime before the first use of a variable, so i put a call of function inside of var, with a idea, that i would be replace it self. But it does not working, becouse it trying to give me a "Closure Object" back, i think it is a function in clear and not the result :( Here is the important part of code:
$GLOBALS['user_language'] = function()
{
return get_user_language();
}
function get_user_language()
{
$user_language = 'en';
$GLOBALS['user_language'] = $user_language;
return $user_language;
}
//somewhere in the script
print_r($GLOBALS['user_language']);
I wish to get 'en' out, nothing more.
function get_user_language()
{
$user_language = 'en';
$GLOBALS['user_language'] = $user_language;
return $user_language;
}
$GLOBALS['user_language'] = get_user_language();
//somewhere in the script
print_r($GLOBALS['user_language']);
But this is strange because you set it already in get_user_language() then you pull it again. It would almost create a loop. The proper way would probably be to remove the $GLOBALS['user_language'] = $user_language; from the function.
Hope this answers your question.
Just use print_r(get_user_language()) instead of print_r($GLOBALS['user_language']);.
If getting the user's language multiple times would be particularly slow (e.g. a database query would be executed over and over again), you can do something like this:
function get_user_language()
{
static $user_language = null;
if ($user_language === null) {
$user_language = 'en'; // this would be where you make the DB query
}
return $user_language;
}
In practice, in a large PHP application, this code would generally be located in a class and would store the value as an object property, so that, for example, the application can cache DB query results for multiple users rather than for only the current one.
I use the latest code igniter (2.0.3) and php-active 0.0.1.
All are working fine except save();
Code:
if($_POST)
{
$entry= Customers::find_by_routeid('4');
$entry->routeid=5;
$entry->save();
}
Here's my problem: for some reason that I cannot understand the above code does not work, but if I take the code out of if ($_POST), it works fine.
What I am doing wrong?
EDIT:
Thanks Damien Pirsy $this->input->post() does the trick, but when I uncomment the comments in the code the problems returns.
The code now is:
if($this->input->post())
{
$id = $this->input->post('id');
$oldRoute = $this->input->post('oldRoute');
$newRoute = $this->input->post('newRoute');
$entry= Customers::find_by_routeid($this->input->post('oldRoute'));
$entry->routeid=$this->input->post('newRoute');
$entry->save();
/*
if($oldRoute<$newRoute)
{
for ($i=$newRoute; $i>$oldRoute; $i--)
{
$element = Customers::find_by_routeid($i);
echo $element->routeid -= 1;
$element->save();
}
}
*/
}
The elements new IDs ($element->routeid -= 1;) are echoing right, but I have the same problem as in the beginning and neither of two saves work.
You didn't provide much details or debug info, so I'll just guess: try using the CI's native post handler instead. You should have var_dump()ed the $_POST array, see if isset() or not, also, since you're using it as a condition
if($this->input->post())
{
//...
}
UPDATE:
Since we're talking about Post variables, don't assume they're exactly as you want them. Keep in mind that $this->input->post('field') returns FALSE when the index is not present; that might well brake your if condition.
Assuming you need numbers to do this, you can do a check like
if($this->input->post('newRoute') AND is_numeric($this->input->post('newRoute'))
{
$newRoute = $this->input->post('newRoute');
}
else
{
// give it a default value, or raise an error, for example. If you need this
// variables, and need them to be numbers, you cannot go on in case these
// conditions are not met, right?
}
And the same for $oldRoute.
And yeah, OK, maybe you can write a cleaner code than mine, but you get the picture ;)
I have a function (which I did not write) inside an existing php tag in the head of a page that I've been using for several years the parses URL's and email addresses to make them clickable links:
function ParseURLs($str){
if(isset($str)){
$Output=strip_tags($str);
$Output=preg_replace("/(\swww\.)|(^www\.)/i"," http://www.",$Output);
$Output=preg_replace("/\b(((ftp|http(s?)):\/\/))+([\w.\/&=?\-~%;]+)\b/i"
,"<a href='$1$5' target='_blank' rel='nofollow'>$1$5</a>",$Output);
$Output=preg_replace("/\b([\w.]+)(#)([\w.]+)\b/i"
, "<a href='mailto:$1#$3'>$1#$3</a>",$Output);
return nl2br($Output);
}
}
I wanted to replace the rel='nofollow' with a php check of a MySQL dbase field and have it only put up the rel='nofollow' if the dbase field is empty. I tried to do it by replacing rel='nofollow' in the function with something like this which was my starting point:
<?php if (empty( $row_rswhatever['linkfollow'])) {echo "rel='nofollow'";}?>
or just this:
if (empty( $row_rswhatever['linkfollow'])) {echo "rel='nofollow'";}
I've tried it a hundred different ways (something good usually happens sooner or later) but cannot get it to work. I know from past experience that I am probably missing the boat on more than one issue, and would appreciate any help or guidance. Thanks.
A easy/lazy way to do it would be to continue doing it as you are doing now, however after the last $output=preg_replace add your if test and if you don't want the rel='nofollow', just use str_replace to remove it.
ie.
function ParseURLs($str)
{
if(isset($str)){
$Output=strip_tags($str);
$Output=preg_replace("/(\swww\.)|(^www\.)/i"," http://www.",$Output);
$Output=preg_replace("/\b(((ftp|http(s?)):\/\/))+([\w.\/&=?\-~%;]+)\b/i","<a href='$1$5' target='_blank' rel='nofollow'>$1$5</a>",$Output);
$Output=preg_replace("/\b([\w.]+)(#)([\w.]+)\b/i", "<a href='mailto:$1#$3'>$1#$3</a>",$Output);
if (empty( $row_rswhatever['linkfollow'])) {
$Output = str_replace(" rel='nofollow'", "", $Output);
}
return nl2br($Output);
}
}
Without knowing exactly what you'd be checking for in the database:
function ParseUrls($str) {
$sql = "SELECT ... FROM yourtable WHERE somefield='" . mysql_real_escape_string($str) ."'";
$result = mysql_query($sql) or die(mysql_error());
$rel = (mysql_num_rows($result) == 0) ? ' rel="nowfollow"' : '';
blah blah blah
}
Incidentally, the isset check is useless in your code. The function parameter does not have a default value (function x($y = default)), so if no parameter is specified in the calling code, it will cause a fatal error in PHP anyways.
This also assumes that you've already connected to MySQL elsewhere in your code, and are using the mysql library (not mysqli or pdo or db or whatever else).
I am trying to insert messages to a function
function addMessage($item) {
if ($result) {
$message = '<p class="ok">
<span> Item added </span>
</p>
';
header("Refresh: 2; url=?page=$item");
}
else{
$message = '<p class=not><span>There is an error blah blah</span></p>';
}
return $message;
}
When I use it : addMessage('contents') it only returns to second condition. How can I fix this?
You are checking $result inside the if but its neither been assigned any value before that nor been declared as global . I think you meant to check $item:
if ($item) {
Hi jasmine
Your function always returns the second condition because you haven't assigned a value to $result, eider inside the function or when you call the function (like unicornaddict mentioned by other words).
To get your code working the way you probably want, your function should be like this:
function addMessage($item, $result) {
if ($result) { // It will return this condition, case $result has any value assigned and is different from FALSE (boolean)
$message = '<p class="ok">
<span> Item added </span>
</p>
';
header("Refresh: 2; url=?page=$item");
}
else{ // It will return this condition, case $result doesn't has any value assigned or is equal to FALSE (boolean)
$message = '<p class="not"><span>There is an error blah blah</span></p>';
}
return $message;
}
And then you can call the function like you where already calling it, but don't forget to include a variable or a value that should be handled as the $result variable inside the function
addMessage('contents', $result);
Note:
In your $message variable you have <p class=not> and should be <p class="not">.
Remember that header() must be called before any actual output is sent to the browser.
Hope it Helps.
Is $result defined in your script? Use if ($item) instead.
Be very careful that PHP allows the usage of undefined variables.
what they said :-)
Btw, a decent IDE (like Zend) will analyze your code and warn you about things like that.
Such static code analysis is known as "linting", so google for "PHP lint" or see questions like Is there a static code analyzer [like Lint] for PHP files?
But this code sample is so small that I guess you are a beginner (no offence interned - we all had to start somewhere), so do a lot of reading and gather a lot of tools and experience.
For instance, a decent IDE (like Zend or Eclipse PDT) would let you step through your code, line nby line, and examine the value of each variable and then you ought to have seen the problem.
Welcome to PHP and good luck!