PHP - Assigning Variables To Themselves Using Curly Braces
I didn't know how to describe this, so please excuse my title.
As most of you know, this is possible: foreach($items as $key => $item) { ${$key} = $item; } // I would then be able to access it like so: $key // or whatever the value of "$key" is. However, how could I append something extra to the ${$key} variable? Instance: foreach($items as $key => $item) { $my_{$key} = $item; // or ${$key}_arr = $item; } // So that the end result of my variable becomes like so: $my_key // or $key_arr // Instead of just $key // or whatever the value of "$key" is. Is there a known method for this? Any input is appreciated, thank you. Similar TutorialsHi Guys I am having trouble with a mysql regexp expression called through php. I am not sure but I suspect its to do with the {} in the mysql code and PHP parsing them incorrectly. Here is my code snippet: $q = mysql_real_escape_string($_POST['keyword']); $limit = 10; //limit number of responses from dictionary $remainder = 11 - strlen($q); if ($q) { $qy = "SELECT * FROM dict_list WHERE UCASE(word) <> UCASE('$q') AND (word REGEXP '^$q.{$remainder}') LIMIT $limit"; $query = mysql_query($qy); ... What I want to do is this: a user types in a word. I then want to query a dictionary table called dict_list for all matches of the this word up to 11 characters max. Example: if $q was the word aero then the response would be all words beginning with aero and up to a max of 11 characters. That is why IU thought I could calculate length of $q and from this get the $remainder = 11 - strlen($q) then in the REGEXP use .{$remainder} but when testing if I echo out the query $qy the curly braces will not show on screen. Any help would be greatly appreciated. I hope this is posted in correct location. Apologies if not. Thanks, Fergal. This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=353613.0 $text = "wow {one|two|three}fsasfa happy ness"; preg_match('/\b{*+}\b/i', $text, $matches); print_r($matches); Basically, $matches will contain "one|two|three" - but all I got is an array with "}" I have a query that pulls 1 field with 20 rows of data. I need to assign each row to a different variable so that I can then display them in different locations on a page. I cannot make each row of data a different field because of other constraints. My data is very well normalized. I am using mysqli so something like the old mysql_result would be lovely! How can this be done without hitting my database 20 times? Thanks for the help. So I have a text file "name.txt" in the text file I have ids and auth keys set up like this 1234564 abcdfhu 3123900 sdkoao etc How could I make it to where the ids are $ids and the auth keys are $auth_keys? I've tried using foreach() but I cant get it Hi Guys Quick noob question. I am still fairly new to oop and i'm trying to also build my first simple mvc to learn about that too. I came across some syntax use in a tutorial that works but i don't really understand why and don't know what this is called to search for it on google. I've instantiated the class and then i pull out and explode the url to make controller or function calls in the mvc. The noob bit i don't understand is this Code: [Select] $controller->{$url[1]}(); Why do the curly brackets allow you to place a variable name? And what is this type of syntax called so i can read about it. Any help would be massively appreciated! Drongo Hi There, I'm trying to get the following array to work as a separate include php file to make the HTML easier to follow. Within the HTML it has been working fine, as the "echo $tdata_consent Variable is within the main curly brackets. As soon as I move the variable outside of the brackets I only get 1 item from the array rather than all of the items. $projects_const = array(); $required_const = ['Consent']; $colors_const = array_combine($required_const, ['bg-danger text-white font-weight-bold'] ); $xml_const=simplexml_load_string($jobs_task_response) or die("Error: Cannot create object"); foreach($xml_const->Jobs->Job as $item_const) { if (in_array((string)$item_const->State, $required_const)) { $projects_const[] = array( 'job_no' => (string)$item_const->ID, 'job_name' => (string)$item_const->Name, 'job_start' => date('d/m/Y', strtotime($item_const->StartDate)), 'job_due' => date('d/m/Y', strtotime($item_const->DueDate)), 'job_status' => (string)$item_const->State, 'job_staff' => (string)$item_const->Assigned->Staff->Name, ); } } usort($projects_const, function($a,$b) {return $b['job_due'] <=> $a['job_due']; } ); foreach ($projects_const as $proj_const) { $job_no =$proj_const['job_no']; $job_name =$proj_const['job_name']; $job_status =$proj_const['job_status']; $job_staff =$proj_const['job_staff']; $job_due =$proj_const['job_due']; $clr_1 = $colors_const[$job_status]; $tdata_const = ''; $tdata_const .= "<div class='row no-gutters'>"; $tdata_const .= "<div class='col-sm bg-white border rounded'><a href='managejob.php?job_id=$job_no' class='text-left ml-1'><strong>$job_no</strong></a></div>"; $tdata_const .= "<div class='col-sm-2 bg-white border rounded'><p class='text-left ml-1'>$job_name</p></div>"; $tdata_const .= "<div class='col-sm-2 bg-white border rounded'>" . state_dropdown_1($job_no, $job_status, $clr_1) . "</div>"; $tdata_const .= "<div class='col-sm-2 bg-white border rounded'><p class='text-left ml-1'>$job_status</p></div>"; $tdata_const .= "<div class='col-sm-2 bg-white border rounded'><p class='text-left ml-1'>$job_staff</p></div>"; } echo $tdata_const; Any thoughts would be much appreciated. Thanks in Advance. Hi all I'm quite a competent PHP coder but where it comes to preg_match I prefer to be ignorant, because I can't get my head around the patterns. Basically, I'm working with a script that someone else has written, and I'm coming across problems because the URL that is being validated sometimes has curly brackets '( )' in it (these are image file names generated by an internal system). I have the pattern, how do I modify this to allow curly brackets? On some occasions, the urls have just the opening or just the closing, so its never the complete set. if someone could give me an indication with this, because I'm clueless! Thanks in advance! Ste pattern: Code: [Select] $pattern = '/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/'; Quotation marks are confusing me.
What do you guys use when it comes to quotation marks?
In HTML attributes and throughout the bodies of my web pages, I use the HTML entity ("). For example:
<a href="" title="Read "Article Name""> <p>In his new book, he says: "This is a quote."</p>I thought that this is the best practice. However, today, I read that it's perfectly safe to use straight quotes (") in the body, and that I should use the HTML entity only in HTML attributes. Is that correct? But what if I want to use curly quotes in the body instead of straight quotes? Should I always use the HTML entities for curly quotes (“ and ”), or can I also safely use the characters (“”)? I heard that straight quotes are safe in all browsers, even if you don't specify the character set of your web pages, but that curly quotes are only safe if you specify the character set or if you use the HTML entities. Is that true? And what about the <q> tag? Apparently, it's compatible with all browsers but they treat it differently. Edited by Fluoresce, 30 August 2014 - 07:37 AM. I am trying to assign a text value to an XML node. $Data->nodeValue = '<xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:'.$URN_UUID_ATTACHMENT.'" />' The resulting xml is: Code: [Select] <Data><xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:urn:uuid:1294192877" /></Data> is there a way to generate this instead: Code: [Select] <Data><xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:urn:uuid:1294192877" /></Data> Hi, I cant quite figure out how to assign an unique id to the picture I upload to my page, all help would be appreciated. Here's the upload code: //This is the directory where images will be saved $target = "images/"; $target = $target . basename( $_FILES['photo']['name']); //This gets all the other information from the form $name=$_POST['name']; $email=$_POST['email']; $phone=$_POST['phone']; $pic=($_FILES['photo']['name']); // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()) ; mysql_select_db("Database_Name") or die(mysql_error()) ; //Writes the information to the database mysql_query("INSERT INTO `employees` VALUES ('$name', '$email', '$phone', '$pic')") ; //Writes the photo to the server if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { //Tells you if its all ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { //Gives and error if its not echo "Sorry, there was a problem uploading your file."; } ?> I have two tables in my MySQL database: 1. user user_id | firstname | lastname | nickname etc. and 2. con (for contribution) con_id | user_id (foreign key) | name | contribution | category etc. Here's how I wanted to solve the problem of assigning the foreign key to the 2nd table (I'm a beginner so bear with me. ) When logging in, I assigned the user_id to the session variable like this: // do the while loop while ($assoc = mysqli_fetch_assoc($rows)) { // assign database COLUMNS to the variables $dbuser_id = $assoc['user_id']; $dbuser_name = $assoc['nickname']; $dbuser_password = $assoc['password']; etc..................... // set a session after login $_SESSION['user'] = $dbuser_name . $dbuser_id; This prints out the user_id just like I wanted to: echo "Your user_id is: " . $_SESSION['user_id'] = $dbuser_id; Gives: Code: [Select] Your user_id is: 35 ... and this is how the assignment of the foreign key looks like WHILE posting the contribution: $user_id = $_SESSION['user'] = $dbuser_id; if (!empty($knuffix_name) && !empty($knuffix_category) && !empty($knuffix_contribution)) { // Write the data into the database $query = sprintf("INSERT INTO con (con_id, user_id, name, contribution, category, contributed_date) VALUES (' ', '$user_id', '%s', '%s', '%s', now())", mysqli_real_escape_string($dbc, $knuffix_name), mysqli_real_escape_string($dbc, $knuffix_contribution), mysqli_real_escape_string($dbc, $knuffix_category)); When I now do a contribution through the input areas, nothing gets inserted into the database and I automatically get logged out. Obviously it's not working as I thought it would and I'd like to know why is that? Notice that if I take the user_id part OUT, it's working again, so the rest of the code must be right then. Another question I have is: Is this common practice to solve this problem of assigning a foreign key, or is there a better way of doing it? hi, i am updating records from database using ajax and javascript on php page. The result is displayed inside a div (<div id="show"></div>). Now i want to assign the content of the above div(say y) to php variable for further calculations. How can i assign the value displayed in div tag to a php variable? Thanks. I just have a quick question, what happens if I don't assign a visibility element to methods? In other words, if I just have: [php] class Article_model { public $data; function index() { return $data; } [php] ...instead of declaring public, private, static, and so on before the function. Will php just consider it public? I need to assign unknown array keys and their values to strings. The code I am using is: Code: [Select] $cart = $_SESSION['cart']; $items = explode(',',$cart); $qty = array(); foreach ($items as $item) { $qty[$item] = $qty[$item] + 1; } print_r($qty); The keys change and are not ordered. I do not know what the key or it's value may be. So as an example, I might have: Code: [Select] Array ( [2] => 5 [4] => 8 ) or in a different scenario, I might have: Code: [Select] Array ( [1] => 6 ) What those numbers represent is a product id (the key), and the quantity (the value of the key). Can someone help me to assign these to a string? I have been reading all morning, and not making any progress. Thank you! would anyone know how to assign the value (value returned by some function in the class) of variable $temp in the class: source looks like: class newRecord{ var $temp = listCat('gallery_menu', 'submenu', 'submenu_id'); ////// this line is not working, does not assign? function listCat($table, $submenu, $submenu_id) { $return = '<select name="'.$submenu_id.'" id="'.$submenu_id.'">'; $result = mysql_query("SELECT * FROM $table"); while($row=mysql_fetch_object($result)) { $return = $return.'<option value="'.$row->id.'">'.$row->$submenu.'</option>'; } $return = $return.'</select>'; return $return; } } if function is used out of the class and used in index.php directly, returns expected value of it (there is no doubts - works ok) Hi all, I can't seem to designate an array key by using a variable and I was wondering if this is possible. I'm looking to do something like this: Code: [Select] <?php $key = "apple"; $arr = array($key => "fruit"); ?> Any suggestions would be appreciated! Hey everyone. I have been trying to assign dates to image so I could sort them, and also display the date they were uploaded. But I need some help. I have a script that uploads an image to a file directory, and also stores the file directory and the upload date in a database. And I also have a script that displays the images in the file directory but I cannot find a way to assign the right date to the right image. Here is the script that displays the images: Code: (php) [Select] if (isset($_POST['submit'])) { // fill an array with all items from a directory $dir = "thumbs/"; $handle = opendir($dir); while ($file = readdir($handle)) { $files[] = $file; // This removes the full stops from the array unset($files[0]); unset($files[1]); } foreach($files as $fileimg) { echo "<img src='". $dir . $fileimg ."'/>\n"; echo "$date"; } } and here is the script for calling the date from the database: Code: [Select] $query = mysql_query("SELECT imgaddress, uploaddate FROM thumbs WHERE imgaddress='" . $dir . $file . "'"); if (mysql_num_rows($query) == 1) { $row = mysql_fetch_assoc($query); $date = $row['uploaddate']; If I use the database statement before the foreach, then it does not get the right file directory, but if I call it inside the foreach, then I cannot use krsort() to sort the array. Any help would be greatly appreciated, thanks hi there, i'm trying to put a message in the footer of a page which welcomes a person who is logged in with his/her name, using sessions of course; when i place this: Code: [Select] $username = $_SESSION['valid_user']; in the footer before the echo: Code: [Select] echo "You are logged in as $username"; but the session is also needed before the footer to use the username for other things , such as -checking his credit- so if place in footer the footer shows name in browser but checking credit would not happen as the assignment is at the buttom. IF i place the assignment above at the top of the file: everything works for the user and checking credit ..etc...but the footer is not there... cud not put this any clearer..sorry...hope if someone cud help...thanks Good Day Everyone! I'm having trouble figuring out how to assign weapons from a MySQL table to soldiers. Say I have the following... $soldiers = 100; $damage = 0; $q = mysql_query("SELECT `item_quantity`, `item_power` FROM `items` WHERE `owner_id`='".$userid."' ORDER BY `item_power` DESC"); while($row = mysql_fetch_assoc($q)) { // assign weapons to soldiers and add `item_power` * `item_quantity`to $damage } I want to assign all the weapons until there's not enough soldiers to assign them to, and I want to assign them in order of `item_power` descending. I'm sure this is really simple, I just can't for the life of me get my head around it. Thanks in advance! Kind Regards, Ace |