find() returning NULL Yii - php

find() is returning NULL even though there is a row that matches the criteria.
Find snippet
$tempApp = Applicant::model()->find(array('condition'=>'phn=' . $app->phn . ' AND id<>' . $app->id));
if($tempApp != NULL) {
$archId = $this->archive($tempApp);
if($archId != NULL) {
$tempApp->phn = NULL;
$tempApp->save();
$app->note = 'Former name: ' . $tempApp->first_name . ' ' . $tempApp->middle_name . ' ' . $tempApp->last_name;
} else {
unset($archId);
}
}
NOTE: This code works the second time the applicant is updated. I'm confused why this is happening. Can someone give me advice as to why this is happening.
NOTE: I tried the different ways find() can be used (ie. find('phn=:phn AND id<>:id', array(':phn'=>$app->phn, ':id'=>$app->id));
Thanks

use count() instead of NULL
if(count($tempApp)) {
$archId = $this->archive($tempApp);
if(count($archId)) {
$tempApp->phn = NULL;
$tempApp->save();
$app->note = 'Former name: ' . $tempApp->first_name . ' ' . $tempApp->middle_name . ' ' . $tempApp->last_name;
} else {
unset($archId);
}
}

Try echoing out your SQL statement and pasting it in phpmyadmin sql tab and see if you get a result.
Also, I would try using !empty() instead of NULL for my if statement

Related

php mysql search options combination

i have got 4 checkboxes for filterung mysql result. Checkboxes can be activated all or single, too. I don't know how to make sql statement. DO i really have to use all combined possibilities manually or is there a simplier solution? Perhaps with "switch"?
No as first statement i have:
if ($vart1 == "1" AND !isset($vart2) AND !isset($vart2) AND !isset($vart2) AND !isset($vart4)) {
$tname_sql .= " a.tdesc = 'option1' AND";
};
How many variations are there?
Thank you for help.
Regards,
Olaf.
You can make a simple PHP function which returns WHERE or AND depending how many times has been called:
$wa = 0;
function whereAnd() {
global $wa;
if ($wa == 0) {
$wa = 1;
return ' WHERE ';
} else {
return ' AND ';
}
}
$query = "SELECT * FROM table1 t ";
if (isset($var1)) {
$query .= whereAnd() . "t.field1 = " . $var1;
}
if (isset($var2)) {
$query .= whereAnd() . "t.field2 = " . $var2;
}
if (isset($var3)) {
$query .= whereAnd() . "t.field3 = " . $var3;
}
if (isset($var4)) {
$query .= whereAnd() . "t.field4 = " . $var4;
}
First call will returns WHERE, all other calls will return AND no matter what kind of combinations you may have. You don't need to care about how many checkboxes are passed.

Exiting a foreach loop and retrieve result

I'm working on a little project and I've gone brain dead, so I'm hoping someone here can help me defeat my coders block.
I'm trying to create a page using php that changes its content display depending on what (if any) value is passed to the page (Locations). I have created a safelist array which I've stored the different locations. First I check any value passed against the safe list, if its a match I display one set of content.
If it doesn't match I'm running a similarity test to check if theres maybe a simple typo and can still navigate people to the page I think they wanted but this is where I'm getting stuck.
I'm hoping that someone could type
www.example.co.uk/location.php <---- to load a generic location page
www.example.co.uk/location.php?loc=Bishops-Stortford <---- to load a targeted location page
www.example.co.uk/location.php?loc=Bishop-Stortford <---- to load a targeted location page despite mispelling providing its a 90% or more match
www.example.co.uk/location.php?loc=?php echo "I hacked your site"; ?> ---- hopefully my system will disarm nasty code injection
I'll post my code below so you can see what I've got.
<?php
$loc = "";
$safelist = array("Bishops Stortford", "Braintree", "Chelmsford", "Dunmow", "Harlow", "Hertford", "Saffron Walden", "Sawbridgeworth", "Stansted", "Ware",
"Essex", "Hertfordshire");
if(isset($_GET["loc"])) {
/* Gets the value of loc if set, replaces hyphens with spaces and capitalises first letters of words converting the rest to lowercase. */
$loc = ucwords(strtolower(str_replace("-", " ", $_GET["loc"])));
}
/* Is word in safelist */
if (in_array($loc, $safelist)) {
/* Yes */
if (($loc == "Essex") or ($loc == "Hertfordshire")) {
$county = True;
} else {
$county = False;
}
if ($county == False) {
echo "\"" . $loc . "\" is not a county";
}else{
echo "\"" . $loc . "\" is a county";
}
} else {
/* No, Is string 90% similar to any entry within the safelist? */
foreach ($safelist as $safeword) {
similar_text($safeword, $loc, $percent);
echo $safeword . " " . $loc . " " . $percent . "<br />";
if ($percent >= 90) {
}
}
?>
I can't think what to do for the if ($percent >=90). I know I want to exit the loop and get the result from the first 90% or more match I find but am not 100% sure how to do this.
Also whats the best way to deal with code injection like www.example.co.uk/location.php?loc=?php echo "I hacked your site"; ?>
I think this is what you want:
foreach ($safelist as $safeword) {
similar_text($safeword, $loc, $percent);
echo $safeword . " " . $loc . " " . $percent . "<br />";
if ($percent >= 90) {
$loc = $safeword;
$county = true;
break;
}
}
As long as you don't call eval() on user input, you don't have to worry about them injecting PHP statements. When you echo something, it's sent to the browser, it's not executed again by PHP. However, you should still sanitize the output, because it might contain HTML markup, perhaps even Javascript, which could hijack the user's browser. When displaying output on the page, use htmlentities() to encode it:
echo "Greetings, " . htmlentities($first_name);
To answer the second part of your question, I use htmlentities to output data directly to the screen from input and something like this function on the data before a save to a database:
function escape_value($value)
{
if($this->real_escape_string_exists)
{
if($this->magic_quotes_active){$value = stripslashes($value);}
$value = mysql_real_escape_string($value);
}
else
{
if(!$this->magic_quotes_active){$value = addslashes($value);}
}
return $value;
}
I think I would restructure it, something like this:
$loc = "";
$safelist = array("Bishops Stortford", "Braintree", "Chelmsford", "Dunmow", "Harlow", "Hertford", "Saffron Walden", "Sawbridgeworth", "Stansted", "Ware",
"Essex", "Hertfordshire");
if(isset($_GET["loc"])) {
/* Gets the value of loc if set, replaces hyphens with spaces and capitalises first letters of words converting the rest to lowercase. */
$loc = ucwords(strtolower(str_replace("-", " ", $_GET["loc"])));
}
$good = '';
if (in_array($loc, $safelist)) {
$good = $loc;
} else {
foreach ($safelist as $safeword) {
similar_text($safeword, $loc, $percent);
echo $safeword . " " . $loc . " " . $percent . "<br />";
if ($percent >= 90) {
$good = $safeword;
}
}
}
if ( ! empty($good)){
/* Yes */
if (($good == "Essex") or ($good == "Hertfordshire")) {
$county = True;
} else {
$county = False;
}
if ($county == False) {
echo "\"" . $good . "\" is not a county";
}else{
echo "\"" . $good . "\" is a county";
}
//And whatever else you want to do with the good location...
}
Like Barmar said, since you're not doing anything with the input value except for comparing it to an array, there's no risk of an attack in that way.

PHP if null echo else echo

Not sure what im doing wrong here, but the out come is always null. The script should output "you did not select an answer" only if no answer was selected but otherwise it should output the answer given:
I have updated the script as mentioned but still getting the empty output even when answer is given :/
Thanks for all the help so far guys, but even the below code doesnt work, it now just outputs as blank if no anwser, but if you do fill it in, it correctly echos the answer.
if (empty( $a1 )) {
echo"<li>\n<h2>1. " . $q1[0] . "</h2>\n"
. "<p>You did not select an answer</p>\n"
. "</li>\n";
}
else {
echo"<li>\n<h2>1. " . $q1[0] . "</h2>\n"
. "<p><strong>" . $q1[$a1] . ":</strong></p>\n"
. "<p>" . $r1[$a1] . "</p>\n"
. "</li>\n";
}
Completely forgot to show this part!!
// get local copies of single answers
$a1 = trim(isset($_POST['a1'])?$_POST['a1']:99);
$a3 = trim(isset($_POST['a3'])?$_POST['a3']:99);
$a4 = trim(isset($_POST['a4'])?$_POST['a4']:99);
$a5 = trim(isset($_POST['a5'])?$_POST['a5']:99);
Don't use if($a1 == null) use if(empty($a1)) or if(isset($a1))
An empty string is not null
$a1 = '';
if ($a1 == null) // is wrong
should be
$a1 = '';
if ($a1 === '')
or
if (empty($a1))
an empty is not the same as null try
if ($a === '') this respects also the type which is better for code quality
if (empty( $a1 )) {
echo"<li>\n<h2>1. " . $q1[0] . "</h2>\n"
. "<p>You did not select an answer</p>\n"
. "</li>\n";
}
else {
echo"<li>\n<h2>1. " . $q1[0] . "</h2>\n"
. "<p><strong>" . $q1[$a1] . ":</strong></p>\n"
. "<p>" . $r1[$a1] . "</p>\n"
. "</li>\n";
}
Use empty instead of null checking
'null' is not same as false or ''.'null' is an object.
In PHP, empty string ($a) & empty array ($b) will return true if you test following express:
$a = ''; $b = array();
$a == null -> TRUE $b == null -> TRUE
also,
$a == 0 -> TRUE
So you should use '===' to test, or there's always unexpected result in your code.

Magic trick to get the correct url?

I am about to make a system that automaticly puts &pni=something behind an URL. It would be easy if the url just was http://t.co/something.php with "?pni=...." but users can also have http://t.co/something.php?myown=paramater and then the system should add & instead of ?
How can I put the pni parameter behind the URL and to be valid every time? I've tried this without luck.
<?php
function nice($in){
$out = parse_url($in);
return $out['scheme'] . "://" . $out['host'] . $out['path'] . "?" . $out['query'];
}
$urls = array(
"http://t.co/something.php?w=23&",
"http://t.co/something.php?w=23&dfdf=",
"http://t.co/something.php?",
"http://t.co/something.php",
"http://t.co/something",
"http://t.co/something.php?w=23&dfdf=34&hvem",
);
foreach ( $urls as $url):
echo print_r(nice($url)) . "<br/>";
endforeach;
?>
function nice($in) {
$out = parse_url($in);
if ($out['query'] != "") {
$out['query'] = "pni=something&".$out['query'];
}
else {
$out['query'] = "pni=something";
}
return $out['scheme'] . "://" . $out['host'] . $out['path'] . "?" . $out['query'];
}
check if there is any "?" in the url and concat the pni=something to it accordingly.
function nice($url){
if(strpos($url,"?")!==false){
return $url."&pni=something";
}else{
return $url."?pni=something";
}
}
You can access the query string specifically using
$_SERVER['QUERY_STRING']
If it is empty you can use
$url .= '?arg=val';
If query string is ! empty
$url .= '&arg=val';

way to check for if sql row exists?

my problem is this
i am fetching a mysql row via this
$sql_istorrenthere = $this->query_silent("SELECT media_type
FROM " . DB_PREFIX . "auction_media WHERE
auction_id='" . $item_details['auction_id'] . "'");
$row = mysql_fetch_array($sql_istorrenthere);
and then calling it with this
if ($row['media_type'] == 4)
{
$display_output = GMSG_TORRENT;}
else
{
$display_output = GMSG_NOTORRENT;
}
}
however, media_type has multiple values, (1,2,3,4)
how to write it so that it checks if 4 exists? because now i believe it is checking if media_type equals 4 and that is false, which is giving me the wrong display_output
You can use mysql_num_rows to determine if any rows were returned, and this works by adding a search condition in your query adding " AND media_type = 4" to the end
if(mysql_num_rows($sql_istorrenthere)) {
} else {
}
// You can loop through records by doing the following, this prints out every media type :)
while ($row = mysql_fetch_array($sql_istorrenthere)) {
echo $row['media_type'] . '<br />';
}
You can just add on "AND media_type = '4'" to your query. But you really should use paramaterized queries.
Once your query has "AND media_type = '4'" you can check RowCount.
There are probably better ways, but here's one idea.
$media_type_ids = explode(',', $row['media_type']);
if (array_search(4, $media_type_ids) !== FALSE) {
// found
}
It could be possible to even do this in-situ in the database query ... potentially.
// Comment the next line after you get what it is
#print ("Value of media type is: >>>".$row['media_type']."<<<"); // Line to be commented
if (isset($row['media_type']) && $row['media_type'] == 4) {
$display_output = GMSG_TORRENT;
}
else {
$display_output = GMSG_NOTORRENT;
}
To fetch all media types:
<?php
$sql_istorrenthere = $this->query_silent("SELECT media_type FROM " . DB_PREFIX . "auction_media");
while ($row = mysql_fetch_array($sql_istorrenthere)) {
// Comment the next line after you get what it is
#print ("Value of media type is: >>>".$row['media_type']."<<<"); // Line to be commented
if (isset($row['media_type']) && $row['media_type'] == 4) {
$display_output = GMSG_TORRENT;
}
else {
$display_output = GMSG_NOTORRENT;
}
}

Categories