I'm trying to understand how to fix this error.
Warning: prev() expects parameter 1 to be array, string given in
Its in the if statement below. Is this happening since the first value doesn't have a previous and I need to deal with that condition? Weirdly this worked in regular .php but not in the framework I have it in now.
I'm trying to generate an XML file based on a result set returned for a query. (I'm open to better ideas)
$export.= '<Campaigns>';
while ($line = mysql_fetch_assoc($result) ) {
//echo '<Email Timestamp="' . $line['EmailTimeStamp'] . '" ';
$export.= '<Campaign Info="' . $line['EmailTrackingNumber'] . '" EmailId="' .$line['EmailId'] . '">';
$export.= '<Emails>';
if (prev($line['EmailTrackingNumber']) == current($line['EmailTrackingNumber'])) {
$export.= '<Email Timestamp="' . $line['EmailTimeStamp'] . '" ';
$export.= 'City="' . $line['City'] . '" ';
$export.= 'Zip="' . $line['Zip'] . '"';
}
$export.= '</Emails></Campaign>';
}
$export.= '</Campaigns></EmailTrackingData>';
//echo $export;
file_put_contents('DateOfFile-export.xml', $export);
This
prev($line['EmailTrackingNumber'])
is not an array but a string. This
prev($line)
makes more sense. It returns the array entry which is before the current entry of $line.
But I think you would like to compare the last record with the current record. But that does not work like this. You can only access the columns of the current record. You have to temporarly save your last record.
$export.= '<Campaigns>';
$lastLine = null;
while ($line = mysql_fetch_assoc($result)) {
//echo '<Email Timestamp="' . $line['EmailTimeStamp'] . '" ';
$export.= '<Campaign Info="' . $line['EmailTrackingNumber'] . '" EmailId="' .$line['EmailId'] . '">';
$export.= '<Emails>';
if ($lastLine['EmailTrackingNumber'] == $line['EmailTrackingNumber']) {
$export.= '<Email Timestamp="' . $line['EmailTimeStamp'] . '" ';
$export.= 'City="' . $line['City'] . '" ';
$export.= 'Zip="' . $line['Zip'] . '"';
}
$export.= '</Emails></Campaign>';
$lastLine = $line;
}
$export.= '</Campaigns></EmailTrackingData>';
//echo $export;
file_put_contents('DateOfFile-export.xml', $export);
Related
I'm working on a script that will retrieve API information of the 'near earth objects' from NASA's website. User selects date, api grabs the information and displays it. How do I fix the foreach in this script? would appreciate some help with this.
$jsonAsteroids = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($jsonAsteroids, true);
echo "<h4>Retrieving the first element (i.e. \"links\") of the JSON structure</h4>";
var_dump( $data["links"]);
echo "<h4>Retrieving the first element (i.e. \"next\") inside the \"links\" element</h4>";
echo( $data["links"]["next"]);
You were very close. Your main issue was that you used json_decode(..., true); which gives you an array, but then used the object->property syntax instead of object['property']. My suggestion is to use json_decode without the 2nd argument in this case.
Finally, your 2nd foreach was malformed.
<?php
$result = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($result);
foreach ($data->near_earth_objects as $date => $objects) {
echo "<p>" . count($objects) . " objects detected on $date</p>";
echo "<ol>";
foreach ($objects as $object) {
echo "<li>" . $object->name . " <a href='" . $object->nasa_jpl_url . "'>" . $object->nasa_jpl_url . "</a><br>";
echo "Diameter of the object: " . $object->estimated_diameter->meters->estimated_diameter_min . "-" . $object->estimated_diameter->meters->estimated_diameter_max . " metres<br>";
echo "<ul>";
foreach ($object->close_approach_data as $close_approach) {
echo "<li>Close approach: " . $close_approach->close_approach_date . " traveling at a velocity of " . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "missing " . $close_approach->orbiting_body . " by " . $close_approach->miss_distance->kilometers . " km</li> ";
}
echo "</ul>";
}
echo "</ol>";
}
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.
I have something like this:
public function options()
{
$out = '';
$docs = $this->getAll();;
foreach($docs as $key => $doc) {
$out .= ',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
return $out;
}
It gives me a list of options from the DB, but it also gives me a null value at the top.
if I write it like this:
public function options()
{
//$out = '';
$docs = $this->getAll();;
foreach($docs as $key => $doc) {
$out = '';
$out .= '{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
return $out;
}
It doesn't give me the null value but it only returns one value.
$out .= ',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
In this line if I don't add an , it gives me an error message, This because I have $out = ''; at the top. Now can you guys give me an idea how can I get all the values from the DB without the empty value at the beginning.
I also have another question , why we use ;; (double semicolon) in this code:
$docs = $this->getAll();;
test $out to see if it has any length, if so add the comma and the line, otherwise just set it to be the line:
$out="";
foreach($docs as $key=>$doc){
if(strlen($out)){
$out.=',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}else{
$out='{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
}
as to your other question, er, you wrote the code, so why did you put a double semi-colon?
This is not the correct way to build JSON. First create an array, and use json_encode() on it.
I'd suggest using an array instead to hold the individual values, and using join to concatenate them together.
public function options()
{
$docs = $this->getAll();
// Create an empty array
$items = array();
foreach($docs as $key => $doc) {
// "Push" an item to the end of the array
$items[] = '{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
// Join the contents together
$out = join(",", $items);
return $out;
}
Also, the double semi-colon is completely unnecessary.
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.
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'];
}
}