PHP - $counter Inside A Variable Name
If I have a for loop with a variable called $counter, how can I use the value of this inside a variable name. For example:
If I want a bunch of variables called $d1name, $d2name, $d3name ...etc. what's the correct syntax to use? The following gives me a string but not a variable name: $myVariable = "$"."d".$counter."name"; Similar Tutorialsi'm creating a page counter which updates a value in a database each time the page is loaded. I'm trying to make it so that it checks to see if a session has been set, if not, it updates the database, and then sets the session. This way it wont update every time someone refreshes the page. $id=$_GET['id']; if(!isset($_SESSION[$id])){ $_SESSION[$id]= $id; $views = $row['views'] + 1; $update_views=mysql_query("UPDATE topic SET views='".$views."' WHERE topic_id='".$id."'") i want to set the session variable as that of the page id ($id) The problem is that it keeps updating the database everytime the page is reloaded. I'm not sure if i'm setting the session variable correctly. Any ideas would be great Thanks i have a variable called $cake it needs to have this loop inside it so I can call it out Code: [Select] while( $r = $DB->fetch_row() ){ if ( $r['last_activity'] > (time() - 900) ) $r['status'] = "<span style=float:right;><span class=desc4><b>Online</b></span></span>"; else $r['status'] = "<span style=float:right;><span class=desc4>Offline</span></span>"; $column++; if ($ibforums->member['settings']['2'] or (!$ibforums->member['id'])){ $color = "{$r['color']}"; $colors = explode(",", $color); if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ){ { $r['color'] = ($r['color']) ? "style=\"padding:1px 1px 1px 2px;color:#{$colors[0]};filter:Glow(color=#{$colors[1]},strength=3)\"":""; } }else{ $r['color'] = ($r['color']) ? "style=\"color:#{$colors[0]};text-shadow:#{$colors[1]} 2px 1px 1px\"":""; } } $test = explode(";", $info['pdata']); $r['avatar'] = ($r['avatar']) ? "<img src={$r['avatar']} width=64 height=64>" : ""; $r['star'] = ($r['star']) ? "<img class=top3 src=style_images/1/icons/{$r['star']}.png>":""; $r['name'] = "<a href=?i={$r['friendid']}>{$r['name']}{$r['star']}</a>"; $this->to_print .= <<< LOL <dl class="LOL LEFT flm" style="margin-right:5px"><dt2>{$r['name']}</dt2><dd class=padding4>{$r['avatar']}<div class="RIGHT">{$r['status']}</div></dd></dl> LOL; } I tried: Code: [Select] $cake = ' while( $r = $DB->fetch_row() ){ if ( $r['last_activity'] > (time() - 900) ) $r['status'] = "<span style=float:right;><span class=desc4><b>Online</b></span></span>"; else $r['status'] = "<span style=float:right;><span class=desc4>Offline</span></span>"; $column++; if ($ibforums->member['settings']['2'] or (!$ibforums->member['id'])){ $color = "{$r['color']}"; $colors = explode(",", $color); if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ){ { $r['color'] = ($r['color']) ? "style=\"padding:1px 1px 1px 2px;color:#{$colors[0]};filter:Glow(color=#{$colors[1]},strength=3)\"":""; } }else{ $r['color'] = ($r['color']) ? "style=\"color:#{$colors[0]};text-shadow:#{$colors[1]} 2px 1px 1px\"":""; } } $test = explode(";", $info['pdata']); $r['avatar'] = ($r['avatar']) ? "<img src={$r['avatar']} width=64 height=64>" : ""; $r['star'] = ($r['star']) ? "<img class=top3 src=style_images/1/icons/{$r['star']}.png>":""; $r['name'] = "<a href=?i={$r['friendid']}>{$r['name']}{$r['star']}</a>"; $this->to_print .= <<< LOL <dl class="LOL LEFT flm" style="margin-right:5px"><dt2>{$r['name']}</dt2><dd class=padding4>{$r['avatar']}<div class="RIGHT">{$r['status']}</div></dd></dl> LOL; }'; but not working Im having a problem with getting the quotes correct with this. I can either get the variable to work in the href and img src or in the css. Anyone have any ideas on this. Cuase im really stuck. This allows the $address and $cos to echo in but not the css variables <td><?php echo "<a href='planet_profile.php?planet=$address'> <img src='images/star.jpg' id='$cos' style='position:absolute;' left:'$b_x px;' top:'$b_y px;'></a>"; ?></td> and this allows only the css variables to work <td><?php echo '<a href="planet_profile.php?planet="' . $address . '"> <img src="images/star.jpg" id="' . $cos . '" style="position:absolute; left:' . $b_x . 'px; top:' . $b_y . 'px;"></a>'; ?></td> I dont know why I'm having so many problems with this. I need to get a variable that defined in an included file inside of a function I've got this Inside file.php I've got the $variable1 and $variable2 defined (they're dynamic/different to each user) include('file.php'); function foo() { GLOBAL $variable1, $variable2; echo $variable1; echo $variable2; } foo(); Yet it outputs nothing? If I Include file.php right inside of the function it works however. Any idea? The org variable holds the value of the folder name. The problem is that the header is sending out ".$org." and not the actual value of $org. Example output url: http://127.0.0.1/application/".$org."/display/trackingboard.php I want this url if the value is test: http://127.0.0.1/application/test/display/trackingboard.php Thanks! Code: [Select] $org = "test"; header('Location: ../application/".$org."/display/trackingboard.php'); how can you increase the page number in the following line until $status returns an empty result? curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept: application/xml", "Authorization: xxxxxxxxxxxxx:xxxxxxxxxxxxxxxx", "Page: 2")); I'm redoing my login script using functions and a basic switch function checking against a $_GET variable (hope you guys know what I'm talking about). What I want to do is create two functions: 1 that displays the login form and 1 that processes the information The form tag would look like this: <form action=\"<?php $_SERVER['PHP_SELF']?>?action=process\" method=\"post\"> </form> Here's my switch statement: Code: [Select] <?php //**************************************** //****************Action****************** //**************************************** switch ($_GET["action"]) { default: case "index": if (!$_SESSION["member"]) { if (!$timeout) { display_form(); } else { echo $timeout_error; } } else { echo "You are already logged in."; } break; case "process": if (!$_SESSION["member"]) { if (!$timeout) { process_form(); } else { echo $timeout_error; } } else { echo "You are already logged in."; } break; } ?> This runs as soon as "login.php" loads. It'll automatically run the commands under case "default" and "index". It'll first check to see if the member's logged in. If not, it'll then check to see if "$timeout" is true ($timeout becomes true if the member has attempted to login 5 times and failed). If not, it'll display the login form, by running "display_form()". Once the form has been filled and submitted, the commands under case "process" will be performed. Again it will first check to see if the member's logged in. If not, it'll check to see if "$timeout" is true. If not, it'll start validating the forms. For the validation, I've created a variable called "$errors_found", and scripted one if statement checking to see if the email and password exist. If so, the variables "$rm_field_un" and "$rm_field_pw" become true, as well as "$errors_found". So, back to submission of the form... If "$errors_found" is true, display the form (when the form is displayed, there will be an if statement within that says "<?php if ($rm_field_un) { echo "Username is wrong."; } ?>", which will be displayed right underneath the username field and label. Same with the password elements). If "$errors_found" is not true, go ahead and register the member. Now, here's where I need help, because I'm really confused as to how to accomplish this. The "display_form()" function will contain a single variable called "$login_form". It will contain a value of the HTML constructed login form, and the function will return the variable. Remember how I stated in the third paragraph up that I will have <php> statements within the form which would display errors if necessary? Well, how do I put those if statements within the HTML, which is contained within the variable? If that last question confuses you, allow me to present you with an instance: Code: [Select] <?php function display_form() { $login_form = " <form name=\"login_form\" method=\"post\" action=\"<?php $_SERVER['PHP_SELF']?>?action=process\"> Username: <input type=\"text\"> <?php if ($rm_field_un) { echo "Username is wrong"; } ?> "; return $login_form; } ?> See what I mean? This code confuses me ALOT. I'm not sure if the <php> tags are needed as it is already contained within existing ones, or what. Can somebody please help me out? Any and all help is much appreciated. =D I'm trying to build a math game. But I'm having trouble trying to make a variable calculate that contains an operator. Example: $c1_op = "+"; $a1_num_user = $_POST['a1_num']; $e1_num_user = $_POST['e3_num']; $row_1 = $a1_num_user . $c1_op . $e1_num_user; echo "result: " . $row_1; If I now input a 10 and a 2 I will get echo'd out: result: 10+2 It's not calculating. When I don't use any quotation marks then I will get the error "unexpected ;". I need the operator inside a variable, it's the nature of the math game, any idea how I can make it work so it calculates? Hi Everyone, I have built a website utilizing a PHP abstract Webpage class to create the pages. When creating another class that inherits from Webpage class I rewrite abstract functions, etc. where needed. When instantiating an object of the extended classes I pass the constructor the $page_title, $css_file, $meta_data, $keywords, etc., etc.. I am able to pass html markup in a string variable to a class level "Setter" function to populate a "main area" of the website and all works perfectly. However, I have a contact form which I send the "Submit Message" button click to a PHP function that takes care of making sure the form fields are not empty, then sends email and returns a success message back to the calling page, if they are empty, the function returns what fields are empty(required). If the page includes empty and populated fields I want to put the populated fields into session variables so that I may populate the fields when the user is taken back to the page and display to the user the required fields that were empty(this functionality is already within the function). This brings me to my question(see code below for reference): Seeing that I am populating a variable with a string it seems I cannot use an if statement, echo or the like, my IDE gives me errors. How may I insert an if statement where needed to populate the empty form fields? Code: [Select] include('../php_functions/functions.php');//for the chechData() function $error_message = NULL; if(isset($_POST['submit'])) { $error_message = checkData($_POST, 'Renovation & Consulting'); } $main_content = '<form method="post" action=""> <fieldset id="contactform"> <legend>Renovations & Consultations</legend>'. [color=red]//placing a variable here works fine![/color] $error_message .'<div class="row_div"> <div class="label_div"> <label>First Name:</label> </div> <div class="input_div"> <input name="First Name" type="text" maxlength="50" size="50" value="'.[color=red]if(session variable not empty) echo it here;.'"[/color] /> </div> </div> <div class="row_div"> <input name="submit" type="submit" value="Send Message" /> </div> </fieldset> </form>'; Thanks for any and all responses. Chuck I am echoing a variable that is an array. I want to change the first part of the variable but don't know how to manipulte names inside the ['brackets'] Code: [Select] echo $row['v1_name']);?> lets say I have a value called $var = v1. How do I substitute that like this: Code: [Select] echo $row[$var.'_name']);?> I know the above doesnt work, but thats what i want it to do :-) Trying to figure out how to make it so name is a link to the profile when its echo anyone know how to do this? im at a huge stand still Code: [Select] <?php $sql = "SELECT name FROM users WHERE DATE_SUB(NOW(),INTERVAL 5 MINUTE) <= lastactive ORDER BY id ASC"; $query = mysql_query($sql) or die(mysql_error()); $count = mysql_num_rows($query); $i = 1; while($row = mysql_fetch_object($query)) { $online_name = htmlspecialchars($row->name); echo '<a href="Inbox.php">"'[$goauld]'</a>"'; ?> Hi, The array shown below is causing problems. I know this for sure because when I comment the array out the script runs. Is it: 'pswrd1'=>SHA1('$_POST['pswrd1']') inside the array causing the script not to run?? All help will be greatly appreciated. $register_data = array('username'=>$_POST['username'], 'first_name'=>$_POST['first_name'], 'last_name'=>$_POST['last_name'], 'address'=>$_POST['address'], 'postcode'=>$_POST['postcode'], 'country'=>$_POST['country'], 'e_mail'=>$_POST['e_mail'], 'pswrd1'=>SHA1('$_POST['pswrd1']'), 'phone_no'=>$_POST['phone_no']); I tried these below, Code: [Select] class Site extends Controller { function Site() { public $data = Array(); } } but it fail? Thanks in advanced. Hi, I have a connection set up to an API using a PHP script - the API sends back data in JSON format, and if I capture it and echo it, it displays in extremely unfriendly format on the screen. I've tried to find a way to convert this data into readable format, ideally in a HTML table, but although there are articles on converting manually inputted JSON data into a HTML table using Javascript, I can't find a way to do it from a PHP variable. This is what I have so far: if ($_POST['getcompany']) { $companyname = $_POST['_Name']; $ch = curl_init(); $data_array2 = array( 'token' => $token ); $make_call2 = json_encode($data_array2); //echo 'Token is '.$token; $token2 = substr($token, 14); $token3 = substr($token2, 0, -3); //echo 'Token 2 is '.$token3; //echo 'Company Name is '.$companyname; //curl_setopt($ch, CURLOPT_GET, 1); //curl_setopt($ch, CURLOPT_POSTFIELDS, $make_call2); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Authorization: '.$token3.'')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, 'https://connectionurl?countries=GB&name='.$companyname); //Execute the request $result = curl_exec($ch); echo 'Companies: '.$result; //This displays the data provided by the search, but is in JSON format
So I need a way to get the data held in $result, into a HTML table. Any idea how I can do this? Code: [Select] <?php session_start(); $index="1"; $_SESSION[$index]=2; echo "$_SESSION[$index]"; ?> Hi good day check how to have a variable "$index" inside session.. Hello all, I have some piece of code that is nested like this $variable = 'This is a global argument'; function parentFunction($variable) { function childFunction() { echo 'Argument of the parent function is '.$GLOBALS['variable']; } childFunction(); } parentFunction(5); What I want to know is - Is there a way to access a variable from the parent function without passing arguments to the child function? (Something like how classes have parent::?). I don't want to use $GLOBALS because it might cause some variable collision, and I didn't want to pass arguments because incase I decide to change the arguments in the parent function I'd have to do it in the child function aswell. From my searching around in the Internet it seems like this is not possible, but if theres a slight chance that there might be something out there, i'm willing to give it a shot . Thanks in advance The Script:
$desired_width = 110; if (isset($_POST['submit'])) { $j = 0; //Variable for indexing uploaded image for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array $target_path = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/uploads/"; //Declaring Path for uploaded images $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $new_image_name = md5(uniqid()) . "." . $ext[count($ext) - 1]; $target_path = $target_path . $new_image_name;//set the target path with a new name of image $j = $j + 1;//increment the number of uploaded images according to the files in array if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded. && in_array($file_extension, $validextensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>'; $tqs = "INSERT INTO images (`original_image_name`, `image_file`, `date_created`) VALUES ('" . $_FILES['file']['name'][$i] . "', '" . $new_image_name . "', now())"; $tqr = mysqli_query($dbc, $tqs); // Select the ID numbers of the last inserted images and store them inside an array. // Use the implode() function on the array to have a string of the ID numbers separated by commas. // Store the ID numbers in the "image_file_id" column of the "thread" table. $tqs = "SELECT `id` FROM `images` WHERE `image_file` IN ('$new_image_name')"; $tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc)); $fetch_array = array(); $row = mysqli_fetch_array($tqr); $fetch_array[] = $row['id']; /* * This prints e.g.: Array ( [0] => 542 ) Array ( [0] => 543 ) Array ( [0] => 544 ) */ print_r($fetch_array); // Goes over to create the thumbnail images. $src = $target_path; $dest = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/thumbs/" . $new_image_name; make_thumb($src, $dest, $desired_width); } else {//if file was not moved. echo $j. ').<span id="error">please try again!.</span><br/><br/>'; } } else {//if file size and file type was incorrect. echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>'; } } }Hey, sorry that I am posting this darn image upload script again, I have this almost finished and I am not looking to ask more questions when it comes to this script specifically. With the script above I have that part where the script should store the ID numbers (the auto_increment column of the table) of the image files inside of one array and then the "implode()" function would get used on the array and then the ID numbers would get inserted into the "image_file_id" column of the "thread" table. As you can see at the above part the script prints the following: Array ( [0] => 542 ) Array ( [0] => 543 ) Array ( [0] => 544 )And I am looking to insert into the column of the table the following: 542, 543, 544I thought of re-writing the whole image upload script since this happens inside the for loop, though I thought maybe I could be having this done with the script as it is right now. Any suggestions on how to do this? This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=316454.0 I'm trying to pull results from a database (using php) to populate a javascript "top news rotation" script I found. The problem is that I'm getting the "java is disabled" message that is in the code...instead of the results I'm expecting. Here's the code: Code: [Select] <!-- create a element in your HTML like the following --> <div id="quotetext" > Text will go here. Be sure to add initial text here for users with JavaScript disabled. </div> <!-- The easiest way is to place the below JavaScript code after the above HTML. The better way would be to add in the <head> section of the document and call the rotatequote() function through the window.onload event. However this can cause problems if you have other scripts that use the window onLoad settings --> <script type="text/javascript" > var myquotes = new Array( <?php $link = mysql_pconnect($host, $username, $password); mysql_select_db('briansch_brn',$link); $sql = "SELECT * FROM story WHERE ORDER BY date DESC LIMIT 4"; $rs = mysql_query($sql,$link); $matches = 0; while ($row = mysql_fetch_assoc($rs)) { $matches++; echo "'<strong>$row[headline]</strong><br />(posted $row[date]) - $row[short_story]<br /><a href='/pages/$row[keyword]'>READ MORE</a>'"; if($matches < 4) { echo ','; } if($matches == 4) { echo ''; } } if (! $matches) { echo (""); } echo ""; ?> ); function rotatequote() { thequote = myquotes.shift(); //Pull the top one myquotes.push(thequote); //And add it back to the end document.getElementById('quotetext').innerHTML = thequote; // This rotates the quote every 10 seconds. // Replace 10000 with (the number of seconds you want) * 1000 t=setTimeout("rotatequote()",10000); } // Start the first rotation. rotatequote(); </script> I know that javascript inside php is hard to make work...and I know that php inside javascript is hard to make work. Any ideas? Thanks! How can I say, if more than one of these if's happens do this.... Code: [Select] if ((!isset($_POST['state'])) && (($_POST['country'] != $r['country']) || ($_POST['city'] != $r['city']))) { $details = $_POST['city'].', '.$_POST['country']; update_user_actions(1, $details); } else if ((isset($_POST['state'], $_POST['city'])) && (($_POST['state'] != $r['state']) || ($_POST['city'] != $r['city']))) { $details = $_POST['city'].', '.$_POST['state']; update_user_actions(1, $details); } if ((isset($_POST['credentials'])) && ($_POST['credentials'] != $r['credentials'])) { $details = ''; update_user_actions(2, $details); } if ((isset($_POST['specialties'])) && ($_POST['specialties'] != $r['specialties'])) { $details = ''; update_user_actions(3, $details); } if ((isset($_POST['personalweb'])) && ($_POST['personalweb'] != $r['personalweb'])) { $details = $_POST['personalweb']; update_user_actions(4, $details); } |