Which one is best and faster method ?(making drop down method) - php

I have two different method which help to make drop_down (select) option. Both are work same. only different is in logic for showing selected option
Method 1:
function unit_type_drop_down($selected=''){
$where = array('status'=>'1');
$unit_type_data = $this->select_result('unit_type', 'id,name', $where);
$html = '';
foreach ($unit_type_data as $value) {
if($value->id == $selected){
$html.='<option value="' . $value->id . '" selected>' . ucfirst($value->name) . '</option>';
}else{
$html.='<option value="' . $value->id . '">' . ucfirst($value->name) . '</option>';
}
}
return $html;
}
Method 2:
function unit_type_drop_down($selected=''){
$where = array('status'=>'1');
$unit_type_data = $this->select_result('unit_type', 'id,name', $where);
$html = '';
foreach ($unit_type_data as $value) {
$html.='<option value="' . $value->id . '">' . ucfirst($value->name) . '</option>';
}
$html = str_replace('value="'.$selected.'"', 'value="'.$selected.'" selected="selected"', $html);
return $html;
}
unit type data has value something like
$unit_type_data = array(
array('id'=>1,'name'=>'unit1'),
array('id'=>1,'name'=>'unit1'),
array('id'=>1,'name'=>'unit1'),
.
.
.
.
.
array('id'=>1,'name'=>'unit1')
);

The first method is faster because IF-ELSE statement and string concatenation consume fewer resources and operations than search and replacement in a string.
Of course, if you want to get exact metrics of speed both methods - should calculate asymptotic complexity for concatenation of strings and replacement string in PHP.
Also, the first method seems more clear to readable than the second method

You can use getusage to check execution time of any PHP script. Or with microtime before and after each script, like this:
$before = microtime(true);
// some script
$after = microtime(true);
echo ($after-$before);

Related

Problem fetching data from table using foreach loop

I am having problem in fetching data from database table, after loading data into array and loop using foreach it return blank instead of the values. I have tried using this way $row[''] it works fine but i want to use this operand -> but its fetching bank data.
$query = "SELECT * FROM pages_words";
$select_posts = mysqli_query($connection, $query);
$rows[] = array();
while ($row = mysqli_fetch_assoc($select_posts))
$rows[] = $row;
foreach ($rows as $key => $row) {
$idpw = $row['idpw'];
$pages = $row['pages'];
$words = $row['words'];
$amount_added = $row['amount_added'];
$page_type = $row['page_type'];
if ($page_type == 'double') {
if ($row->idpw == $post['no_of_pages']) {
echo '<option selected="selected" id="' . $row->idpw . 'nop" value="' . $row->idpw . '" title="' . $row->amount_added . '"> ' . $row->pages . ' Page(s) / ' . $row->words . ' Words</option>';
} else {
echo '<option id="' . $row->idpw . 'nop" value="' . $row->idpw . '" title="' .
$row->amount_added . '"> ' . $row->pages . ' Page(s) / ' . $row->words . ' Words</option>';
}
}
}
?>
blank data
kindly help solve the problem
You used mysqli_fetch_assoc(), which fetches rows as associative arrays. In other places in the foreach loop, you're accessing the row correctly using array syntax, such as $idpw = $row['idpw'];. You can't access array values using object syntax. Instead of using $row->idpw when outputting the option, you could either use $row['idpw'] or just use the $idpw variable you created earlier.
If you want the arrow operator to work, you'll need to use mysqli_fetch_object() instead, but if you do that you'll need to change the places where you're using array syntax to use object syntax as well.

Take specific value from database array using following php code

from the following code i want to take just a few value data from "elemen_desc" array. How to do it? I try to put if else statement in the option but the syntax is error. Maybe anyone can help? . Below is the following code.
public function ListElementDesc() {
$document = new Document_Template_Model();
$result = $document->ListElementDesc();
$html = '';
foreach ($result as $multi):
$html .= '<option value="' . $multi['element_desc'] . '"></option>'; //' . $multi['element_code'] . '
endforeach;
return $html;
}
It would be useful to see the syntax you did try that raised the error, however, perhaps this will help:
foreach ($result as $multi):
if (isset($multi['element_desc'][1])):
$html .= '<option value="' . $multi['element_desc'][1] . '"></option>'; //' . $multi['element_code'] . '
else:
$html .= '<option value="' . $multi['element_code'][0] . '"></option>'; //' . $multi['element_code'] . '
endif;
endforeach;
For further reference perhaps this page will help, PHP Alternative Syntax for Control Structures

php echo statement inside $output

I have the following php code:
$skizzar_masonry_item_width = $masonry_item_width;
$skizzar_masonry_item_padding = $masonry_item_padding;
$skizzar_double_width_size = $masonry_item_width*2 +$masonry_item_padding;
$output .= '<style>.skizzar_masonry_entry.skizzar_ma_double, .skizzar_masonry_entry.skizzar_ma_double img {width:'.$skizzar_double_width_size.'}</style>';
return $output;
For some reason though, the value of $skizzar_double_width_size is not being added into the $output - is there a way to echo a value in an output variable?
As #Rizier123 mentioned, ensure you initialise any string variables before trying to append to them.
$var = '';
$var .= 'I appended';
$var .= ' a string!';
I would also like to strongly discourage you from using inline styles as well as generating them with inline PHP. Things get very messy very quickly.
In a situation like this you need to check that all the variables you are using in the calculation are valid before you panic.
So try
echo 'before I use these values they contain<br>';
echo '$masonry_item_width = ' . $masonry_item_width . '<br>';
echo '$masonry_item_padding = ' . $masonry_item_padding . '<br>';
$skizzar_masonry_item_width = $masonry_item_width;
$skizzar_masonry_item_padding = $masonry_item_padding;
$skizzar_double_width_size = $masonry_item_width*2 +$masonry_item_padding;
echo 'after moving the fields to an unnecessary intemediary field<br>';
echo '$skizzar_masonry_item_width = ' . $skizzar_masonry_item_width . '<br>';
echo '$skizzar_masonry_item_padding = ' . $skizzar_masonry_item_padding . '<br>';
echo '$skizzar_double_width_size = ' . $skizzar_double_width_size . '<br>';
$output .= '<style>.skizzar_masonry_entry.skizzar_ma_double, .skizzar_masonry_entry.skizzar_ma_double img {width:'.$skizzar_double_width_size.'}</style>';
echo $output;
This should identify which fields are causing you problems.
Also while testing always run with display_errors = On It saves so much time in the long run.

mssql_fetch_array only displays one row if columns are put into variables

I'm still a PHP noob, so I apologize if this is something simple.
I am creating a fairly basic search facility for a website using PHP and mySQL. I have connected to the database, selected the database, queried the table and have fetched the table columns;
$k = htmlspecialchars($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
while ($results = mssql_fetch_array($select)) {
$title = $results['Title'];
$link = $results['Link'];
$description = $results['Description'];
}
}
When I put the $results[''] columns into variables and then try to echo out each variable like so;
if( isset($noResults)) {
echo $noResults;
} else {
echo '<li>' . '<h2>' . '' . $title . '' . '</h2>' . '<p>' . $link . '</p>' . '<p>' . $description . '</p>' . '</li>';
}
it only echo's out one row matching that query however, If I was to just simple echo out the columns like so;
echo $results['Title'];
echo $results['Link'];
echo $results['Description'];
all rows matching the query will be displayed..
I'm not sure why this is happening. If someone could help me out that would be great!
You need to use a loop:
$k = mysql_real_escape_string($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
$results= array();
while ($result = mssql_fetch_array($select)) {
$results[]= $result;
}
}
if( isset($noResults)) {
echo $noResults;
} else {
echo "<ul>";
foreach($results as $result){
echo '<li>' . '<h2>' . '' . $result['title'] . '' . '</h2>' . '<p>' . $result['link'] . '</p>' . '<p>' . $result['description'] . '</p>' . '</li>';
}
echo "</ul>";
}
Do you execute the output in the while-loop?
If you execute the while-loop and call the echo after that, each resultset will overwrite the previous, and the echo will output the last resultset which was fetched.
If you call the echo in the Loop, every result set will generate "his own" output line.
If you want to hold every resultset in a variable you can use an array, which is declared in front of the loop and gets filled in the loop.
a few things are not clear from your question, but i am assuming that you are echo'ing the variables outside the loop since you are checking isset($noResults). that means you are reassigning the variables with new values in each loop of while. so ultimately you get the last one assigned to the variables. you have to either use an array to hold the values or echo it with in the loop.

error with strpos on form

I'm coding the locations for groups, and the user can search based on the location to find the nearest group to them. The fields are: country, state, city, neighborhood. Let's say there are ten groups in the USA -- I don't want it to list the option USA ten times. I added in a strpos so that it will only list them once, but I'm getting an error.
Here's the php code:
<?php
$myQuery = "select country, state, city, neighborhood from groups WHERE group_status = 'open to new members'";
$rs = mysql_query($myQuery);
$country_options = $state_options = $city_options = $neighborhood_options = '';
while($get_row = mysql_fetch_assoc($rs)){
$pos_country = strpos($get_row['country'], $country_options);
if($pos_country === false) {
echo $country_options .= "<option value='" . $get_row['country'] . "'>" . $get_row['country'] . "</option>";}
$pos_state = strpos($get_row['state'], $state_options);
if($pos_state === false) {
echo $state_options .= "<option value='" . $get_row['state'] . "'>" . $get_row['state'] . "</option>";}
$pos_city = strpos($get_row['city'], $city_options);
if($pos_city === false) {
echo $city_options .= "<option value='" . $get_row['city'] . "'>" . $get_row['city'] . "</option>";}
$pos_neighborhood = strpos($get_row['neighborhood'], $neighborhood_options);
if($pos_neighborhood === false) {
echo $neighborhood_options .= "<option value='" . $get_row['neighborhood'] . "'>" . $get_row['neighborhood'] . "</option>";}
}
?>
It outputs the following errors:
Warning: strpos(): Empty delimiter in sidebar.php on line 66
Warning: strpos(): Empty delimiter in sidebar.php on line 70
Warning: strpos(): Empty delimiter in sidebar.php on line 73
Warning: strpos(): Empty delimiter in sidebar.php on line 76
Underneath the error it has a nice form with the correct fields: country, state, city, neighborhood. It's just listing the same countries multiple times.
The delimiter for strpos() is the second parameter passed in.
In your code, you start out with:
$country_options = $state_options = $city_options = $neighborhood_options = '';
These are each the values you use as delimiters, and they are all empty - hence your error. After you perform your strpos() checks using a given key, then you set it. For instance:
$pos_country = strpos($get_row['country'], $country_options);
if($pos_country === false) {
echo $country_options .= "<option value='" . $get_row['country'] . "'>" . $get_row['country'] . "</option>";
}
I'm not sure what character you're searching for with $country_options, but you immediately append a <option></option> tag to it (which is one really long delimiter). Are you, perhaps, using the wrong variables as the characters you're searching for?
EDIT
After re-reading your question, I understand the goal you're trying to achieve (I think). You simply don't want to display the same country, state, city, or neighborhood more than once.
To accomplish this, it may be easier to keep an array of "seen" values and just check that array in each loop. Try something like this:
$countries = array();
$states = array();
$cities = array();
$neighborhoods = array();
while($get_row = mysql_fetch_assoc($rs)) {
if (!in_array($get_row['country'], $countries)) {
$country_options .= '<option value="' . $get_row['country'] . '">' . $get_row['country'] . '</option>';
$countries[] = $get_row['country'];
}
if (!in_array($get_row['state'], $states)) {
$state_options .= '<option value="' . $get_row['state'] . '">' . $get_row['state'] . '</option>';
$states[] = $get_row['state'];
}
if (!in_array($get_row['city'], $cities)) {
$city_options .= '<option value="' . $get_row['city'] . '">' . $get_row['city'] . '</option>';
$cities[] = $get_row['city'];
}
if (!in_array($get_row['neighborhood'], $neighborhoods)) {
$neighborhood_options .= '<option value="' . $get_row['neighborhood'] . '">' . $get_row['neighborhood'] . '</option>';
$neighborhoods[] = $get_row['neighborhood'];
}
}

Categories