PHP - Array Access Problem
I am trying to pull images from my Flickr account with some success except that of accessing the description to be used as a caption for the image. What I have so far is:-
Code: [Select] <?php //>>> Define some variables $maximgs = 5; $images = array(); $params = array( 'api_key' => '***********************', 'method' => 'flickr.photos.search', 'user_id' => '****************', 'sort' => 'date-posted-desc', 'format' => 'php_serial', 'extras' => 'description', ); $encoded_params = array(); foreach ($params as $key => $value){ $encoded_params[] = urlencode($key) . '=' . urlencode($value); } //>>> Make request and decode the response $url = 'http://api.flickr.com/services/rest/?' . implode('&', $encoded_params); $response = file_get_contents($url); $response_object = unserialize($response); //var_dump($response_object['photos']['photo']); //>>> Why is this returning 100 results? if($response_object['stat'] !== 'ok'){ echo "Something went wrong!"; } //>>> Select the required number of images ($maximgs) for($loop = 0; $loop <= $maximgs; $loop++){ $images = $response_object['photos']['photo'][$loop]; var_dump($images); //>>> Url of the individual image location for the img src. $imgurl = 'http://farm'.$images['farm'].'.'.'static'.'.'.'flickr.com/'. $images['server'].'/'.$images['id'].'_'.$images['secret'].'_n.jpg'; //>>> Url of the individual image for the link. $flkrurl = 'http://www.flickr.com/photos/'.$images['owner'].'/'.$images['id'].'/'; /*The complete Url (<a href="link($flkrurl)"> <img alt="$images['title']" src="image location"($imgurl) width="required width of image" /> </a>) */ $compurl = '<a href="'.$flkrurl.'" target="_blank">'.'<img alt="'. $images['title'].'" src="'.$imgurl.'" width="320px" /></a>'; //>>> Display Images echo $compurl . '<br />' . $images['description']['content']; //<<<<<< Line 66 } ?> Which annoyingly throws this error:- Notice: Undefined index: content in C:\wamp\www\php\flickr_test1.php on line 66 The result of a var_dump():- array 'id' => string '6914498038' (length=10) 'owner' => string '************' (length=12) 'secret' => string '601a885f31' (length=10) 'server' => string '7137' (length=4) 'farm' => float 8 'title' => string 'newhaven_15' (length=11) 'ispublic' => int 1 'isfriend' => int 0 'isfamily' => int 0 'description' => array '_content' => string 'Great reflections found in Newhaven Harbour.' (length=44) with the info that I want to extract underlined. What I can't figure out is how to find out the name of the array below "description =>". I have been scratching my head for several hours now and am no nearer to working it out. Maybe a genius here will have the solution. Similar TutorialsThe title makes it sound more complicated than it is. I have a recurring function that searches for a specific value in a multi-dimensional array. When it finds it, it returns an array of the index. For example, if it found the value at $array[1][4][2][0], it would return an array like this: [0]=>1 [1]=>4 [2]=>2 [3]=>0 Here's the function. Code: [Select] <?php // Other Code /** * Find's the parent of an item * Unfortunately, it takes a bit more work than just using the loudspeaker at a grocery store * @param int $parent The parent to be searched for * @param array $array * @param array $cur_index */ private function findParent($parent, $array, $cur_index) { for($i = 0; $i < count($array); $i++) { // Search the array if($array[$i]['id'] == $parent) { // If the parent is found $cur_index[count($cur_index)] = $i; return array(true, $cur_index); } if(count($array[$i][1]) > 1) { // Call findParent again to search the child $cur_index[count($cur_index)] = $i; $found_in_child = $this->findParent($parent, $array[$i], $cur_index); if($found_in_child[0]) { return $found_in_child; } } } return array(false); // Return no matches } I need to be able to call that index using the keys from the key array (as we will call it). How can I do that? Thank you in advance for your help. Array ( [game] => Array ( [id] => 2011012593950636050 [name] => Array ( [us] => Castlevania II: Belmont's Revenge [uk] => Castlevania II: Belmont's Revenge ) echo print_r($this->game[0]['name']) but undefined offset error. I don't want to loop through the first array either. Thanks When I send values to the foreach they are not recorded in the array. $x = $getProductID; $_SESSION['pColors'] = array(); if(isset($_POST['pColors'])) { foreach($_POST['pColors'] as $colorKey => $RColors) { $_SESSION['pColors'][$colorKey] = $RColors; } } var_dump($_SESSION['pColors']); Send date with AJAX: $('.addToCart').click(function(){ $.ajax({ url:""+realLink+"cart.php", method:"POST", data:{action:action,pColors:pColors}, success:function(data){ //alert(data); } }); }); what am I doing wrong? I have an assoc array, but I can't seem to access it. Code: [Select] $var = Array ( 'domain' => asdfasdf.com 'port' => 2082 'adminuser' => admin 'INST_password' => adsfasdf 'adminnickname' => admin 'adminemail' => admin@asdfasdf.com 'sitename' => Play Bingo Online Austrailia 'description' => How to play bingo online in Australia 'site_root_path' => /home/chris/public_html/ 'theme' => default 'anchor_one' => How to play bingo online in Australia 'anchor_two' => play bingo 'anchor_three' => bingo online ) if( empty($var['domain']) ) exit; the code exits everytime. What am I missing? How would you access the number 10 in the $arr array?
<?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); error_reporting(E_ALL | E_WARNING | E_NOTICE); ini_set('display_errors', TRUE); if (session_status() == PHP_SESSION_NONE) { session_start(); } if(!isset($_SESSION['login'])) { echo ("<script>location.href='../clogin/'</script>"); die(); } if (isset($_POST['submit'])) { include_once('db.php'); //get post details from user $UserNumber = $_POST['uNumber']; $sql = "SELECT * FROM customer WHERE user_number=?"; $stmt = $connection->prepare($sql); $stmt->bind_param('i', $UserNumber); $stmt->execute(); $result = $stmt->get_result(); $count = $result->num_rows; if($count == 1) { while($row = $result->fetch_assoc()); { $db_Uno = $row['user_number']; if($userNumber !== $db_Uno) { echo'<script>swal.fire("FAILED!!", "<strong>No Customer with the user number you entered.</strong><hr><br/><i> Check well and try Again.</i>", "error");window.setTimeout(function(){ window.location.href = "home.php"; }, 2000);</script>'; exit(); } else { } }//while loop } //end of if rslt }// end submit for transfer post ?>
Hi! I am trying to use the View Model Design Pattern in my application The problem is that it is the first time I use it and I am a beginner. So, I have the logic in the Model and the "front end" in View. I am talking about a sign up page. In the current Html file I am trying to access an error array from the model file and display it to the user above the input field.
Here is the a snippet from the Model (Signup.php) $account = new Account($con); //the account which takes as param the db connection $error = null; //the array // anything the user writes gets inside this array if (isset($_POST["submitButton"])) { $firstName = UnifyFormInput::unifyUserFLName($_POST["firstName"]); $lastName = UnifyFormInput::unifyUserFLName($_POST["lastName"]); $username = UnifyFormInput::unifyFormUserName($_POST["username"]); $email = UnifyFormInput::unifyFormEmail($_POST["email"]); $password = UnifyFormInput::unifyFormPassword($_POST["password"]); //contain true or false based on the query being successful or not $success = $account->register($firstName, $lastName, $username, $email, $password); if ($success) { $_SESSION["userLoggedIn"] = $username; header("Location:index.php"); }else{ $error = $account->getError(Constants::$registerFailed); } } //compact — creates array containing variables and their values //call render function from View file to show the register page content View::render('register', compact('error')); And here is the view: <?php if (!empty($error)) { echo $account->getError(Constants::$loginFailed); } ?> <input type="text" class="form-control" name="firstName" placeholder= "First Name" value="<?php getInputValue("firstName"); ?>" required>
Hi friends, a quick print_r() shows the following array while connecting to my database. How to get them as individual items and display on the website ? Array ( [0] => Array ( [id] => 52 [document_name] => xyz [document_ext] => gif [download_file_name] => ktm_impact.gif [upload_dt] => 2010-08-11 ) ) Hey all. another quick question. here is the output of my 2D array: Code: [Select] array(2) { ["folder.jpg"]=> array(2) { ["valid"]=> bool(true) ["error"]=> bool(false) } ["file.mp3"]=> array(2) { ["valid"]=> bool(true) ["error"]=> bool(false) } } how can i foreach my way into getting an iterator that points to the folder.jpg and file.mp3? as is now, i have something that looks like this: foreach($arr as $val){ var_dump($val) } the var_dump of $val is an *array*. Thanks for your help! Not sure how to find what is causing my issue here, I'm running smarty which gives me this error if I switch PHP version to 7.4 (was on 7.3) : - Quote
ERRNO: 8 The line the error refers to is this : -
<p class="cart_del_info_box_text"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i> <span class="cart_del_info_box_message"><?php echo $_smarty_tpl->tpl_vars['cart']->value->mDelivery['cartdeliverymessage'];?>
How do I go about finding which file has the actual problem? Thanks for any pointers. CMS: PHP-Fusion version 9.03.110, PHP version: 7.4.16, MySQL Server Version: 5.7.33-log, DB Driver: PDO MySQL My own support people at PHP-Fusion main site have been unable to help me with this problem and I'm hoping for some new eyes and new input on this error. First of all my script works perfectly fine and outputs the result desired. I know that my script is not using PDO prepared statements and I am not prepared to modify it to do so because too much would have to be changed. And I'm not fluent on PDO. My script is an event calendar and can be seen at this url: https://windy.whisperwillow.net/grims_blog/index.php The error only occurs 3 times on 3 lines. <?php echo "<div class='col-sm-12'>\n"; include BASEDIR."grims_blog/include/cal_func_inc.php"; $day=date('d'); $endDate=date('t',mktime(0,0,0,$cMonth,$day,$cYear)); echo "<div><span class='hdspan2'><b>".$locale['gb_510']."</b></span></div><p>\n"; echo "<table class='tbl-responsive' width='67%' align='center' border='0' cellpadding='0' cellspacing='0'><tr>\n"; echo "<td align='center' colspan='3'><img style='max-width:100%;height:auto;' src='".BASEDIR."grims_blog/images/calhead/forest.jpg'></td>\n"; echo "</tr><tr height='30' bgcolor='#960000'>\n"; echo "<td align='left'> <a class='mcaldate' href='".FUSION_SELF."?month=$prev_month&year=$prev_year' title='Last Month'>".$locale['gb_511']."</a></td><td align='center'><span class='mnthhd'>".date("F Y",strtotime($cYear."-".$cMonth."-01"))."</span></td><td align='right'><a class='mcaldate' href='".FUSION_SELF."?month=$next_month&year=$next_year' title='Next Month'>".$locale['gb_512']."</a> </td>\n"; echo "</tr></table>\n"; echo "<table width='67%' align='center' border='0' cellpadding='0' cellspacing='0'><tr><td class='cal-blank'>\n"; echo "<table width='100%' align='center' border='0' cellpadding='0' cellspacing='0'><tr bgcolor='#005E00' height='35'>\n"; foreach ($short_days as $key=>$val) { echo "<th style='text-align:center' width='14%'><span style='font-size:12px; color:yellow;'><b>".$val."</b></span></th>\n"; } echo "</tr><tr>\n"; $s=date('w', mktime (0,0,0,$cMonth,1,$cYear)); for ($ds=1; $ds<=$s; $ds++) { echo "<td class='cal-blank' height='35' style='text-align:center;' valign='middle'></td>\n"; } for ($d=1; $d<=$endDate; $d++) { if (date('w',mktime (0,0,0,$cMonth,$d,$cYear)) == 0) { echo "<tr>\n"; } $result = dbquery("SELECT post_id, post_title, post_date FROM ".DB_GRIMS_BLOG_POST." WHERE active='1' AND MONTH(post_date) = '$cMonth' AND DAY(post_date) = '$d'"); $data = dbarray($result); $stuff1 = $data['post_id'] ? $data['post_id'] : ""; if ($stuff1) { $id = $stuff1; } else { $id = ""; } $stuff2 = $data['post_title'] ? $data['post_title'] : ""; if ($stuff2) { $title = $stuff2; } else { $title = ""; } $stuff3 = strtotime($data['post_date']) ? strtotime($data['post_date']) : ""; if ($stuff3) { $evday = $stuff3; } else { $evday = ""; } if (date("d", intval($evday)) == $d) { echo "<td height='35' class='event' align='center' valign='middle'>\n"; } elseif ($d == $day && $cMonth == date('m') && $cYear == date('Y')) { echo "<td height='35' class='today' align='center' valign='middle'>\n"; } else { echo "<td height='35' class='cal-norm' align='center' valign='middle'>\n"; } if ($d == $day && $cMonth == date('m') && $d <> $evday) { echo "<a class='cal2' href='".BASEDIR."grims_blog/filtered.php?post_id=$id' title='".$locale['gb_513']." $title'><b>$d</b></a>\n"; } elseif ($d == $day && $cMonth == date('m') && $d == $evday) { echo "<a class='cal2' href='#'><b>$d</b></a>\n"; } elseif ($evday) { echo "<a class='ecal' href='".BASEDIR."grims_blog/filtered.php?post_id=$id' title='$title'><b>$d</b></a>\n"; } else { echo "<span class='noevt'><b>$d</b></span>\n"; } echo "</td>\n"; if (date('w',mktime (0,0,0,$cMonth,$d,$cYear)) == 6) { echo "</tr>\n"; } } echo "</table></td></tr></table>\n"; echo "</td></tr></table><p></div>\n"; ?> Well I could not add comments to the posted script. These 3 lines of the db query area give the error in my error log: 1) $stuff1 = $data['post_id'] ? $data['post_id'] : ""; /* Trying to access array offset on value of type bool */ 2) $stuff2 = $data['post_title'] ? $data['post_title'] : ""; /* Trying to access array offset on value of type bool */ 3) $stuff3 = strtotime($data['post_date']) ? strtotime($data['post_date']) : ""; /* Trying to access array offset on value of type bool */ I know I am asking a lot for help on older code but would really appreciate it if someone can take a look. Edited April 19 by OldGrimClarify error lines Hi, WHAT: So I cannot for the life of me figure out why I'm getting this error. I'm trying to create a function that will display the user information from the database in a table but I have like a ton of these errors on the page and I don't know whats wrong. STEPS TO RESOLVE: So I've gone over my code a bunch of types to make sure that all the variables and what not were spelled correctly and as far as I can tell they are. I've also googled this issue to see if I can find a solution but none of them are very helpful. I honestly don't know whats wrong so kinda hard to find ways to resolve an issue, I don't even really know what this error means. THE CODE: This is where I put the function into action <?php display_table( array( "id" => "Id", "emailaddress" => "Email", "firstname" => "First Name", "lastname" => "Last Name", "salesperson" => "Salesperson", "phonenumber" => "Phone Number", "extension" => "Extension", "type" => "Type" ) ); ?> //This is the function <?php function display_table($fields, $data, $rows, $page){ if(isset($_GET['page'])){ $page = $_GET['page']; } else { $page = 1; } $firstRecord = ($page - 1) * ROWS_PER_PAGE; $pageNumbers = ceil($rows / ROWS_PER_PAGE); echo '<div class="table-responsive w-75 mx-auto py-3"> <table class="table table-dark table-bordered table-sm"> <thead> <tr>'; foreach($fields as $key){ echo '<th class="py-2">' . $key . '</th>'; } echo '</tr> </thead> </tbody>'; $keys = array_keys($fields); for($record = $firstRecord; $record < $firstRecord + ROWS_PER_PAGE; $record++){ $row = $data[$record]; echo '<tr>'; for($recordCount = 0; $recordCount < count($keys); $recordCount++){ $column = $keys[$recordCount]; echo '<td class="py-2">' . $row[$column] . '</td>'; } echo '</tr>'; } echo '</tbody> </table'; for($pages = 1; $pages <= $pageNumbers; $pages++){ echo '<a class="btn btn-dark mx-1" href=?page=' . $pages . '</a>'; } } ?> Any help/advice would be really appreciated I am getting these errors . This is my complete HTML page. Everything seems to work fine but when i retweet a message these error show up. Here is my tweet.php and the errors are at line 32 and 41. Previously there was an error at line 24: It was like this: '.((!empty($tweet->retweetMsg) && $tweet->tweetID === $retweet['tweetID'] or $tweet->retweetID > 0) ? ' I changed it to this and the error went away '.((isset($retweet['retweetID']) ? $retweet['retweetID'] === $tweet->retweetID OR $tweet->retweetID > 0 : '') ? ' Maybe this could help! I will really appreciate any suggestion coming my way! Hey guys, I've got a problem with an array sum. I tried doign array_sum(), and a few other stuff but none worked. Here's my code: Code: [Select] $upkeepcheck = $db->query("SELECT i.itmid, i.upkeep, inv . * , u.userid, u.will, u.maxwill, u.upkeepowed, u.money, h.hPRICE, hWILL FROM items i LEFT JOIN inventory inv ON inv.inv_itemid = i.itmid LEFT JOIN users u ON inv.inv_userid = u.userid LEFT JOIN houses h ON h.hWILL = u.maxwill WHERE i.upkeep >0"); $q5 = $db->query("SELECT * FROM settings WHERE conf_name = 'upkeep'"); while($upkeep=mysql_fetch_array($upkeepcheck)) { while($upkeep1=mysql_fetch_array($q5)) { if($upkeep['money'] > $upkeep['upkeep']) { $db->query("UPDATE users SET money = money - {$upkeep['upkeep']} WHERE userid = {$upkeep['userid']}"); } else { $db->query("UPDATE users SET upkeepowed = upkeepowed + {$upkeep['upkeep']} WHERE userid = {$upkeep['userid']}"); } if($upkeep1['conf_value'] == 'Stackup') { if($upkeep['upkeepowed'] > $upkeep['hPRICE']) { $db->query("UPDATE users SET will=100,maxwill=100 WHERE userid = {$upkeep['userid']}"); $db->query("UPDATE users SET upkeepowed = 0 WHERE userid = {$upkeep['userid']}"); event_add($upkeep['userid'], "You haven't paid your upkeep, so your house has been taken away. Next time sell some weapons or earn some more money to pay your upkeep!", $c); } } else if($upkeep1['conf_value'] == 'RemoveItems') { $rem = $db->query("SELECT i.itmid, i.upkeep, inv.*, u.userid, u.upkeepowed FROM items i LEFT JOIN inventory inv ON inv.inv_itemid = i.itmid LEFT JOIN users u ON inv.inv_userid = u.userid WHERE userid = {$upkeep['userid']}"); while($remove = mysql_fetch_array($rem)) { if(isset($remove['upkeep'])) { var_dump($remove['upkeep']); $upkeep = $upkeep + $remove['upkeep']; } } } } } The part that is messed up is Code: [Select] $upkeep = $upkeep + $remove['upkeep'];var_dump($remove['upkeep']); produces: Quote null string '100' (length=3) which is correct, I have 4 null values and 1 value of 100. And the error I get is: Fatal error: Unsupported operand types in C:\wamp\www\pagetest.php Any ideas how to fix this? I want the $upkeep to be updated with $remove['upkeep'] if the value isn't null. I want to store all the hours 0,1,2,3... in my $time array but it returns the last value only and I dont understand why... Code: [Select] <?php $time = array(); $hour = 0; for ( $i=0; $i<=7; $i++ ) { $time['hour'] = $hour; $hour++; } ?> Okay the problem is that it wont find the correct carrier. it dont even find it. i dont know whats wrong. Please take a look at the code. i dont know how to explain it better $carriers = array('verizon'=>'@vtext.com','tmobile'=>'@tomomail.com','sprint'=>'@messaging.sprintpcs.com','att'=>'@txt.att.net','virgin'=>'@vmobl.com','textnow'=>'@textnow.me','metro'=>'@mymetropcs.com','unknown'=>'@teleflip.com'); if (array_key_exists($carrier, $carriers)) { $correctCarrier = $carriers[$carrier]; $i = 0; While($i < $_POST['amount']) { $i++; $formatted_number = $to.$correctCarrier; $result = ("$i of Your Messages Has been sent to the number ". $_POST['to'] . ".<br>" . mail("$formatted_number", "$subject", "$message") . ""); } mysql_query("INSERT INTO `msgssent` (`number`, `numberofmsg`, `subject`, `message`) VALUES ('". $formatted_number ."', '". $i ."', '". $subject ."', '". $message ."')") Or die(mysql_error()); Echo $result; } I'm sure there must be a way to do whatI am after, as it seems like such an obvious thing to do, but I can't figure it out. 1. I have an array which contains a list of database's and their connections $slaveRes_array[0] = array('server' => 'localhost:3306', 'user' => $u, 'password' => $p, 'database' => 'MySQL01_5083', 'sendmail' => '0', 'repeat' => '0', 'dbID' => '1' ); and so on 10 times I then have a list of MySQL Queries: (at the moment there is only one, but there will be more later on). $query_array[] = array( 'query1' => "SHOW SLAVE STATUS"); The idea is that I take the first database from $slaveRes_array, connect to it, and run each query from the $query_array in turn against that database, and ultimately pass that resultset into an array that I can refer back to later on. Within $slaveRes_array I have a DB name (e.g. MySQL01_5083), I want this to be the first entry in my resultset array, so I can reference this. However, not all database's will return a result. So what I want to end up with is something like: => Array ( [name] => MySQL02_5083 ) ( [Slave_IO_State] => Waiting for master to send event)... (in this case the first server (MySQL01) didn't return a result, so the first item in the array is MySQL02. I have found lots of ways to achieve bits of this, but none that work together. I can get a list of database names that returned a result, but can't get the data to return to the array (or any array). I can get the data into an array, but not the database names. Surely this must be something straight forward that people do all the time, right? Hello mates, i've been googling about my problem but i couldn't fix it. Code: ###################################### $web = file_get_contents($tmpUrl); $explodedWeb = explode("<b>Somecode:</b> ",$web); print $explodedWeb [1]; ###################################### I'm just printing it for testing purposes, and the $web var works fine(since tried printing the hole source). Error: "Notice: Undefined offset: 1 in ..." I tried to create an empty array in explodedWeb ("$explodedWeb[]") but didn't work either. Greets. My array results keep displaying like this. I want it to just display the numbers in the quotations. any help? Code: [Select] array ( 0 => '4396', ) array ( 0 => '3934', ) array ( 0 => '5063', ) array ( 0 => '4394', ) array ( 0 => '3936', ) array ( 0 => '4393', ) array ( 0 => '4395', ) array ( 0 => '5064', ) array ( 0 => '5062', ) array ( 0 => '4224', ) array ( 0 => '3322', ) array ( 0 => '3321', ) array ( 0 => '3320', ) array ( 0 => '3725', ) |