PHP - Could You Help A Neophite? Absolute Positioning Of The Variables Of An Array
Could someone help an absolute beginner? I've been searching for hours and can't figure it out.
I have an array and I would like to position each of the variables in various positions around a page. I have a div tag with an absolute position statement, how would I wrap it around the one variable below..."$name" ? I actually have several variables in the array. I've reduced it to one for simplicity. Thanks so much for any help. <?php $query = "select * from todolist where id='$id'"; $result = mysql_query($query); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) extract($row); echo "$name"; //this is the element that I want to position ?> I had envisioned that it would be something like this.... '<div id="position1">' echo "$name" '</div>'; But yea, that doesn't work. Similar TutorialsHi folks,
Amateur coder here in need of some help.
Background: I have a dozen sensors that get recorded in a database. The sensors are not very reliable, so to smooth out the data to graph, I compare the reading to the previous reading and if they differ by a given delta I replace the reading by the previous reading (smooth out spikes). The data for each sensor is loaded into arrays that are names according to sensor numbers (ie sensor one - $sensor1, sensor 6 - $sensor6). I have go through and do the comparison on each array and just repeat the code a dozen times, but I'd like to simplify the amount of code if possible. I'm not sure how to refer to an array by using a variable.
Here is a simplified example of what I would like to do. The issue comes with - $array($i)[$x]
Hope this makes sense of what I'm tring to do. Any guidence would be greatly appreciated. Trying to become a better programmer than just repeating the same piece of code a dozen times..
<?php //define arrays of data $array1 = array (7,8,9,10,11,12); $array4 = array (13,14,15,16,17,18); $array6 = array (1,2,3,4,5,6); //define array of sensors $sensors = array(1, 4, 6); //loop through each data point of each array foreach ($sensors as $i) { for ($x = 0; $x <= 6; $x++) { echo $array($i)[$x]; } } ?> This code outputs the table fields. how do I set them into an array and assign then to a variable to be inserted into a mysql database. // Load html string $dom->loadHTML($html2); // Get tables from html $tables = $dom->getElementsByTagName('table'); // Get rows from tables $rows = $tables->item(0)->getElementsByTagName('tr'); // Loop over each row foreach ($rows as $row) { // Get each column by tag name $cols = $row->getElementsByTagName('td'); // Echo values (here you can assign them in array for example) echo $cols->item(0)->nodeValue.'<br />'; echo '<hr />'; is it possible to have variables in an array? I have been trying to plot some data using phplot, a graph package but it plots different values to the ones I expect. it should be able to cope with array($variable1, $variable2) shouldn't it? I have a function where I am returning a few different arrays into one return json_encode(); but how would I do this? I'm bulling an array from 2 different database tables, and I can't join or union these, because I am actually going to have quite a few different calls that needs to call into other areas. Anyway, My 2 variables are,' $names and $posts If I put one of these in the return json_encode($posts); like that, then the $posts show up fine while the names of course display Undefined, and if I put in return json_encode($names); then my code works for the names to be displayed but anything in the posts of course is undefined, how do I put these two together? Thanks Hello everyone and thanks in advance for the help. I am working on a permission system for a site I am creating that will be used to restrict access to various areas of the site. I have a table with all the permission that is linked to a group that the user is a member of. I then use a query to get a list of the permission ids the user is part of and put those into the session array. I used a basic login script I found online I planned on modifying to add my own features and to make more secure. Originally it had just a member id and member name variable in the session array saved in the login script which are both working fine after login. I am using a dynamic variable to set one session variable for each permission with the id being the changing part in the variable name. The problem I found is that the new variables are not being set. When i removed the redirect from my login script so I could check the problem I found that the temp variable, which is also set before it saves to the session array, is blank as well. If I hit refresh on my browser the new variables become set and all is well. I was talking to nvee in irc chat who said I need to make a function on the page I am redirected to that checks if the variable exists. I looked through the original code of the login script I am using and found that this seems to be how they did it as well so I added an if statement to my index page to check if the variable has a value with and without using if isset. In both cases the new variable is still not getting set. He also gave me some pointers to help make my login checks more secure but the main thing IM concerned with right now is to make my new permission variables accessible to the session. My login script is available in my pastebin. All of my form POST data (from multiple forms) is managed through a file called formdata.php. Formdata.php and check_input() performs trim/stripslashes/htmlspecialchars etc on the posted variables. (it also indirectly calls relevant database functions such as insert or select). What is the correct way to add all of the variables to an array so that I can so that I can pass the array(ofvariables) to a function. ie the checked variables (only a few of them): Code: [Select] $subject = check_input($_POST['subject']); $repphone = check_input($_POST['repphone']); $repfirstname = check_input($_POST['repfirstname']); $replastname = check_input($_POST['replastname']); $streetnum = check_input($_POST['streetnum']); $streetname = check_input($_POST['streetname']); $suburb = check_input($_POST['suburb']); $postcode = check_input($_POST['postcode']); there will be many subjects and many more variables so instead of listing the variables such as: Code: [Select] function post_to_table(){ // variables global $subject;, $streetnum, $streetname, $suburb, $postcode; global $repphone, $repfirstname, $replastname; if ($subject === "specifiedsubject"){ post_to_appropriate_table($streetnum, $streetname, $suburb, $postcode, $repphone, $repfirstname, $replastname); } I would rather use an array instead of passing each variable individually: Code: [Select] function post_to_appropriate_table ($streetnum, $streetname, $suburb, $postcode $repphone, $repfirstname, $replastname) { global $database; $sql = "INSERT INTO incident ("; $sql .= "streetnum, "; $sql .= "streetname, "; $sql .= "suburb, "; $sql .= "postcode, "; $sql .= "repphone, "; $sql .= "repfirstname, "; $sql .= "replastname"; $sql .= ") "; $sql .= "VALUES ("; $sql .= "'{$streetnum}', "; $sql .= "'{$streetname}', "; $sql .= "'{$suburb}', "; $sql .= "'{$postcode}', "; $sql .= "'{$repfirstname}', "; $sql .= "'{$replastname}'"; $sql .= ") "; // echo $sql; //for debugging if required; return $database->query($sql); } how can I ditch the ever growing list of variables and use an array? Thanks. Hi everyone, I really need some help with a project I'm working on. I have a table in MySQL that I am querying to pull out some data. This is the results I am getting from my query: ----------------------------------------------- | fld_id | fld_vl | ----------------------------------------------- | CLNT_NM | Motel1 | | CLNT_MGR | Frank | | CLNT_TMZ | EST | ----------------------------------------------- What I would like to do is get a variable for each fld_id and populate it with the field value. So, in essence it would look like this. $CLNT_NM = 'Motel1'; $CLNT_MGR = 'Frank'; $CLNT_TMZ = 'EST'; How can I do this? I have tried to figure this out but I can't seem to do it. Any help you guys can provide would be greatly appreciated. THANKS in advance!!! So what I'm wanting to do is log changes made by users, to the database... I was thinking on the lines of first doing a query of the database row that is going to be affected, prior to it being affected, putting that row result in an array variable, then allowing the update to happen and re-querying the database row and putting the results in a separate array, to then compare to the original database row array variable... So I guess, (A): Does this make sense to do this, this way? and (B): How do you compare 2 identical arrays, then extract the value from both where the particular element does not match, e.g. has been updated? I have a form that is producing the following : Array ( [formID] => 3154008308 [q1_applicationDate] => Array ( [month] => 11 [day] => 15 [year] => 2010 ) [q4_fullName4] => Array ( [first] => TOM [last] => STONE ) [q5_email] => TSTONE@YAHOO.COM [q6_address6] => Array ( [addr_line1] => 325 E LINCOLN [addr_line2] => [city] => GENESEE [state] => NY [postal] => 33256 [country] => United States ) [q38_selectProvider38] => Sprint [q39_selectPlan] => Individual [website] => [simple_spc] => 3154008308-3154008308 ) HOW do I automatically get each item above into it's own PHP variable? The page that receives this Array is the second page of a 3 or 4 page form. I need to send the above information on through the remainder of the form?? Would appreciate any help! Thanks! Hello, I'm taking values for various cities/areas my members live in. One member can be placed in many cities and on registering they are required to input one city but are allowed to enter a maximum of 6 cities. So, from my posted form I have; //member ID (numeric) $MemID; $City=$_Post['City']; $City2=$_Post['City2']; $City3=$_Post['City3']; $City4=$_Post['City4']; $City5=$_Post['City5']; $City6=$_Post['City6']; Where $City must be set, but any of the other $City'x' may or may not be empty. There are two tables, 1) Cities (CityID,City) 2) Mem-Cities (MemID,CityID). I have some SQL statements which check if the city exists and if it doesn't inserts it. Then adds the $MemID to that $CityID. The way im doing this now is not very efficient like this; if(!empty($City)) { $sql="SELECT COUNT(City) AS Count FROM Cities WHERE City='$City'"; $query=mysql_query($sql); $row=mysql_fetch_array($query); if($row['Count'] == 0) { $insert="INSERT INTO Cities (City) VALUES ('$City')"; mysql_query($insert) OR die('<h1>There was an error adding into Cities</h1>' .mysql_error()); //inserting additional City } $insert="INSERT INTO Mem-Cities (MemID,CityID) SELECT '$MemID',CityID FROM Cities WHERE City='$City' LIMIT 1"; mysql_query($insert) OR die('<h1>There was an adding additional City Cities to members</h1>' .mysql_error()); //inserting additional city into Cities to Members } And repeating the code above for each city. How can I loop through each city and optimise this code? Steps 1) if $City'x' is not empty and doesn't exist in DB insert it 2) add the $MemID to that CityID Thanks! Hello All, Attached are 2 screenshots of the form and output for better reference. What I am trying to do is select all or some checkboxes and for those boxes that are checked, echo out their Payment Method. ---If a checkbox is checked but the Payment Method box == select, give an error. ---If checkbox is checked and Payment Method != select, echo out the ID and selection from the drop down box. Currently, I am echoing the correct ID(s) when certain boxes are checked, but I'm getting every drop down box selection when the corresponding box is not selected. Any help would be greatly appreciated. This is the HTML / PHP Form: $results .= '<table align="center" width="70%" border="0" bgcolor="'.$bg.'" cellpadding="2" cellspacing="0" class="resultsUnderline">'; $results .= '<tr>'; $results .= '<td width="30%" align="left">'.'<input type="checkbox" name="checkbox[]" value="'.$app_pmt_id.'" id="checkbox" />' .$full.'<FONT size="1" color="maroon"> ( '.$app_id.' )</FONT></td>'; $results .= '<td width="30%" align="center">'.$created.'</td>'; $results .= '<td width="20%" align="center"> <select name="pay_method[]" class="drop" id="pay_method"> <option value="select">-- Method --</option> <option value="check">Check</option> <option value="credit">Credit Card</option></td>'; $results .= '<td width="10%" align="center">'.$paid.'</td>'; $results .= '<td width="10%" align="right">'.$fee.'</td>'; $results .= '</tr>'; $results .= '</table>'; Here is the PHP getting the results: if(isset($_POST['action_box']) && $_POST['action_box'] == 'mark_paid') { $checked = array(); $checked2 = array(); if(!isset($_POST['checkbox'])) { $val_error[] = 'You have not selected any applications.'; } elseif($_POST['pay_method'] == 'select') { $val_error[] = 'Please select a Payment Method.'; } else { foreach($_POST['checkbox'] as $value) { $checked[] = $value; } foreach($_POST['pay_method'] as $value2) { $checked2[] = $value2; } echo implode(",", $checked); echo implode(",", $checked2); //$result = mysql_query("UPDATE app_pmt SET paid = '1' WHERE app_pmt_id IN(" . implode(",", $checked) . ")"); //header('Location: bal_due.php?id='.$_GET['id']); } } Hi I am adapting Jeffery Ways Mysql class to accept multiple where statements however I have got stuck on the final hurdle. It is when I try to do the bind_results() and I pass in the parameter types and the parameters. Here is that part of the code: if ($this->_where) $values = array_values($this->_where); $str = "'"; $str .= implode('\', \'', $values); $str .= "'"; // echo $str; $count = count($this->_where); foreach($this->_where as $key => $value){ $key = $value; } $user = 'matt25'; $pass = '6722853cacc4a9649dc75abc852f23c35b1f75cb'; $stmt->bind_param($this->_paramTypeList, $user, $pass); } It works how it is by setting the parameters as variables, but that obviously isn't practical. as you can see I also tried to make a string with the values from the array which brought up the error: Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of elements in type definition string doesn't match number of bind variables in C:\wamp\www\trick_tips\admin\includes\MysqlDb.php on line 260, the same as when I try to put the array into there. So I need some way of setting each value in the array as a variable to then put into the function, or another Idea that I have completely missed. Any help would be much appreciated. Cheers, Matt I'm not versed in PHP OOP and I have some code that I need to echo out onto a page. I don't know what the meaning of $ct->something is in this code. Is this an array of some type? How do I echo out the $ct->title onto another page? Use a function call? I just don't know what all of the $ct variables are and how to get to them. Any help is appreciated. Code: [Select] function current_theme_info() { $themes = get_themes(); $current_theme = get_current_theme(); if ( ! isset( $themes[$current_theme] ) ) { delete_option( 'current_theme' ); $current_theme = get_current_theme(); } $ct->name = $current_theme; $ct->title = $themes[$current_theme]['Title']; $ct->version = $themes[$current_theme]['Version']; $ct->parent_theme = $themes[$current_theme]['Parent Theme']; $ct->template_dir = $themes[$current_theme]['Template Dir']; $ct->stylesheet_dir = $themes[$current_theme]['Stylesheet Dir']; $ct->template = $themes[$current_theme]['Template']; $ct->stylesheet = $themes[$current_theme]['Stylesheet']; $ct->screenshot = $themes[$current_theme]['Screenshot']; $ct->description = $themes[$current_theme]['Description']; $ct->author = $themes[$current_theme]['Author']; $ct->tags = $themes[$current_theme]['Tags']; $ct->theme_root = $themes[$current_theme]['Theme Root']; $ct->theme_root_uri = $themes[$current_theme]['Theme Root URI']; return $ct; } Hello. I have an array like this: Code: [Select] Array ( [1] => MOR [2] => CON [3] => CP1 [4] => CP2 [5] => EMAIL [6] => NIF [7] => BI [8] => DIS ) And then I defined, for example this one variable: define("DIS","District"); When I try to... echo $array[8]; All I get is "DIS". I'm obviously trying to echo a string and it won't work that way... but I still gave it a try. How can I do this then? I need "District" to be outputted instead of the actual variable name. I know that if I were to "echo DIS;" this would work but that defeats the purpose as I have various defined variables per row... Thanks. I need to extract shopping cart transaction information from a database, convert it to json format and send to another DB. Because the fields are not a direct match the calculated values are first bing put into variables. I'm extracting the line items from the database into an array and looping through the array to get each line item which I want to then insert into another array as a sub array. By the way, I'm new at PHP so be gentle. The first step I've coded as: Code: [Select] foreach ($oit_array as $inner1) { // Check type if (!is_array($inner1)) {$inner1 = array($inner1);} $lineprice+=$inner1[orderitem_price]; //calculate amounts required in variables $linepriceinc=$inner1[orderitem_price]+($inner1[orderitem_tax]/$inner1[orderitem_quantity]); if($inner1[orderitem_tax]==0){$linetaxrate+=0;} else $linetaxrate=($inner1[orderitem_final_price]-$inner1[orderitem_tax])/$inner1[orderitem_tax]; $linetaxtotal+=$inner1[orderitem_tax]; $orderqty+=$inner1[orderitem_quantity]; $productname=$inner1[orderitem_name]; $qtyshipped+=$inner1[orderitem_quantity]; $totallineamount+=$inner1[orderitem_final_price]-$inner1[orderitem_tax]; $totallineamountinc+=$inner1[orderitem_final_price]; $unitofmeasure="Units"; $linearray[] = array("LinePrice"=>$lineprice, "LinePriceInc"=>$linepriceinc, "LineTaxCode"=>"GST", "LineTaxRate"=> $linetaxrate, "LineTaxTotal"=> $linetaxtotal, "OrderQty"=> $orderqty, "ProductName"=> $productname, "QtyShipped"=> $orderqty, "TotalLineAmount"=> $totallineamount, "TotalLineAmountInc"=>$totallineamountinc, "UnitOfMeasure"=>"Units"); I then reference the array as $linearray as follows: Code: [Select] //Create Array $salesarray= array ("type"=> "TCashSale", "fields"=>array ("CustomerName"=>$customername, "ShipToDesc"=>$shiptodesc, "Lines"=> array("type"=> "TCashSaleLine", "fields"=> $linearray)), "SalesPayments"=>array("type"=>"TSalesPayments", "fields"=>array("Amount"=> $amount, "PayMethod"=> $paymentmethod))); The problem that I have is that the resulting array contains square brackets around the "linearray" data like so: Code: [Select] {"type":"TCashSale","fields":{"CustomerName":"Cash Customer","ShipToDesc":"Rod Farrell\n\r1234 Short St\n\r\n\rSlackville Queensland 4001","Lines":{"type":"TCashSaleLine","fields":[{"LinePrice":54.54545,"LinePriceInc":54.54545, What am I doing wrong?? PLEASE HELP! I need help I am a new php user, and am trying to understand how to read a .txt file into an array then to retrieve the index of the array at will. Code: [Select] <?php //echo $myfile = fopen("ArrayTestFile.txt", "r") . "File exists: " or die("File does not exist or you lack permission to open it! "); //echo "The contents of the file is " . file_get_contents("ArrayTestFile.txt") . "<br />"; $fh = fopen("ArrayTestFile.txt", 'r+') or die("Failure"); $array = array(); //creation of array $num = fgets($fh);// recursive call variable $num fgets(.txt line) for ($i = 0; $i <= 5; $i++) //for loop loads first 5 of .txt { $array["i"] = $num; //loads each line of .txt into the array at the loops index. echo "Line " . $i . " of the array is " . $array["i"]; // displays the contents of the array in a print message } ?> Thank you. MOD EDIT: code tags added. I have an audit trail that record users ids and a copy of the sql string for any updates they make to my application. This is very easy for me to follow to find exactly where changes happened but do end users it is a bit of a challenge. Has anyone seen or made a script that can either compare two sql strings to see what fields have different values or a script that takes an SQL string and outputs its field names and values to an array that I can use for comparisons? Example being the look at a update made by user X, the database pulls the sql for that change then looks for the previous change up any user before (update sql should have a value for all fields) then compares to see what user X changed. If not im thinking of case statement to divide sql request between inserts and update then writing a script to split the strings based on where the commas were. Any thoughts? 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 ) ) I am trying to insert values stored within two dimensional array into mysql database but it does not work as I would expect it. The locations in mysql are defined as char length of 2. When I print_r the array it shows: Array( [0] => Array ( [0] => 04 [1] => 22 [2] => 27 [3] => 28 [4] => 39 [5] => 43 [6] => 47 )) but when I insert them into the mysql like this: Number1A='$MaxMillionsNumber[0][0]', Number1B='$MaxMillionsNumber[0][1]', Number1C='$MaxMillionsNumber[0][2]', Number1D='$MaxMillionsNumber[0][3]', Number1E='$MaxMillionsNumber[0][4]', Number1F='$MaxMillionsNumber[0][5]', Number1G='$MaxMillionsNumber[0][6]'; my values in mysql all show as Ar What am I doing wrong? This is really blowing my mind... the code is as follows the table, the column names everything is right and contains information but the variables aren't being filled... I don't get it... Anyone have any ideas or options I might not have thought of for debugging? $item_name = ("SELECT * FROM items WHERE id = '$grab_item'"); $que_items = mysql_query($item_name); while ($item_todel = mysql_fetch_array($que_items, MYSQL_BOTH)) { $name = $item_todel['name']; $desc = $item_todel['desc']; } echo ($name . "<br>" . $desc . "<br>" . $grab_item); the only variable thats set is grab_item, fetch_array throws no errors, if I plug in the query straight to the sql I get all the proper information... It's just not filling the two variables.... |