PHP - How Do You Compare 2 Array Variables
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? Similar TutorialsI have a associative array and I need to compare it to a normal array. Code: [Select] associative will have anywhere from 2-8 of these ['name'] ['color'] ['uid'] Code: [Select] normal array will have anywhere from 1-8 names ['name'] What I need to do is get the name of the people that are in the associative array that are not in the normal array. I've tried all sorts of different loops and what not and I cant seam to get anything to work in every case. Hello Guys, I am trying to figure this out.. I have a page that has several check boxes that when checked the values ends up as an array Like this 1, 3, 9, 6, That's what it looks like in the database. I want to compare the values (numbers) submitted with the values in my database table called benefits Here is the function I wrote this function and I want to check the values of the submitted values but I am just not sure how to compare the values, especially with a comma in the array. Code: [Select] $benefits2 = $_POST['benefits']; function check_benefits ($benefits2,$member_id,$description,$ip){ $queryb = mysql_query("SELECT * FROM benefits WHERE b_id = $benefits2"); while ($row = mysql_fetch_array($queryb)) { $benefit_list = $row['b_id']; } if (isset($benefits2)&&( $benefit_list!== $benefits2)) { Do something here! } } Thanks for your help! I'm going crazy. I have two arrays. The first has working hours and the array is like this: ```array(7) { [0]=> array(4) { ["morning_from"]=> string(6) "closed" ["morning_to"]=> string(6) "closed" ["afternoon_from"]=> string(5) "13:00" ["afternoon_to"]=> string(5) "19:00" }``` The second one is the busy times, the array is like this: ```array(2) { [0]=> { ["title"]=> string(13) "Test" ["start_date"]=> string(19) "2019-11-25 13:00:00" ["end_date"]=> string(19) "2019-11-25 14:00:00" } }```
Now I do a cycle of 15 times because I need to make the list for the next 15 days from today.
``` Unfortunately it does not work as I would like, it does not mark correctly if the date is occupied. I'll post a piece of code:
if($book_i == 0){
$book_day = ucwords(strftime('%d %h', strtotime($book_today_day)));
if(count($getListCalendarStartToday) > $count_list_calendar_p){
$count_more_appointment_on_some_days_morning = 0;
foreach ($getListCalendarStartToday as $key => $value) {
if($day == $book_today_day){ $book_output .= "<li>"; if(isset($user["working_time"]) && $user["working_time"]){ $book_output .= "<div><p>".$book_name_day."</p><p>".$book_day."</p></div>";
if($book_name_day == $lang["days-mon"]){
$book_morning_from = $book_array_working_time[$book_day_int]["morning_from"];
$book_morning_from_hour = (int)substr($book_morning_from, 0, 2);
$book_afternoon_from_hour = (int)substr($book_afternoon_from, 0, 2);
$book_morning_from_hour_duplicated = $book_morning_from_hour;
$book_afternoon_from_hour_duplicated = $book_afternoon_from_hour;
$book_check_closed = 0;
if($book_afternoon_from_hour == 0 && $book_afternoon_to_hour == 0){ $book_output .= "<div>";
for ($n=0; $n < $count_more_appointment_on_some_days_afternoon; $n++) {
$day_appointment_p_start_hour = date('H', strtotime($getListCalendarStartToday[$count_list_calendar_p]["start_date"]));
if($book_afternoon_from_hour_duplicated != $book_afternoon_from_hour){
if($book_afternoon_from_hour != $book_afternoon_to_hour){
$book_afternoon_from_hour_duplicated += 1; if($book_afternoon_from_min == 0){
if($day_appointment_p_start_hour == $day_appointment_p_end_hour){
$count_hour_appointment = 0;
$count_hour_appointment += 1;
$book_afternoon_from_hour_duplicated += $count_hour_appointment; break; }else{ if($book_i == 0){
if($day_appointment_p_start_min >= $book_afternoon_from_min && $day_appointment_p_start_min <= 30){ }else{
if($day_appointment_p_start_min >= $book_afternoon_from_min && $day_appointment_p_start_min >= 30){ }
$book_output .= "<a class='uk-button-book-a-visit-hour' id='a-book-a-visit' data-book-day='".$book_today_day."' data-book-hour='".number_add_leading_0($book_afternoon_from_hour).":00'>".number_add_leading_0($book_afternoon_from_hour).":00</a>"; }else{
$book_afternoon_from_hour_duplicated += 1;
if($book_afternoon_from_min == 0){
if($book_afternoon_from_min == $book_afternoon_to_min){
$book_output .= "</div>";
$book_output .= "</li>"; Another noob question here. I've got a form that I use to collect info for an estimate. I also am using Developer toolbox from Adobe. Makes my life a lot easier, but doesn't teach you anything. lol Originally I had a drop down box that would hold the value of selected item and post it into to emailTO field. Which worked just fine. Example: //This is my array. $emails_array = array( 'Landscape Maintenance'=>'me@you.com', 'Landscape Design'=>'me@me.com', 'Planting Renovation'=>'me@me.com', 'Tree Service'=>'me@me.com', 'Weed Man Lawn Fertilization'=>'me@me.com', 'Snowplowing'=>'me@me.com', 'Other'=>'me@me.com'); //This grabs the post of the drop down box and inserts the email addy. $emailObj->setTo($emails_array[$_POST['Services']]); Now I have to change the drop down box to a check box group. In which the user can select multiple services and have multiple email sent out if necessary. This is where I'm stuck. I need to get the post values compare the results to the key in $emails_array then spit out the email associated with it. Here's what I got so far. $postresult = $_POST['services']; echo 'Postresult: ' . "$postresult" . "<br />"; $myarray = explode(",", $postresult); echo 'Dirty Array: '; print_r($myarray); Here are the results Code: [Select] Postresult: Landscape Maintenance,Tree Service,Snowplowing<br> MyArray: Array ( [0] => Landscape Maintenance [1] => Tree Service [2] => Snowplowing ) How do I take either $postresult OR $myarray and compare it to $emails_array and get the unique email values for it? I want to maintain the original $postreault so i can insert it into a mysql db. Here is the code Developer toolbox produces for the checkbox group. Code: [Select] <form method="post"> <label> <input type="submit" name="Submit" id="Submit" value="Submit"> <input name="services" id="services" wdg:recordset="Recordset1" wdg:subtype="CommaCheckboxes" wdg:type="widget" wdg:displayfield="service" wdg:valuefield="service" wdg:groupby="2" style="display: none; "><span><table cellpading="0" cellspacing="0" border="0"><tbody><tr><td><label id="services_label0" htmlfor="services_commacheckbox0" for="services_commacheckbox0"><input type="checkbox" id="services_commacheckbox0" value="Landscape Maintenance" cbFor="services">Landscape Maintenance</label></td><td><label id="services_label1" htmlfor="services_commacheckbox1" for="services_commacheckbox1"><input type="checkbox" id="services_commacheckbox1" value="Landscape Design" cbFor="services">Landscape Design</label></td></tr><tr><td><label id="services_label2" htmlfor="services_commacheckbox2" for="services_commacheckbox2"><input type="checkbox" id="services_commacheckbox2" value="Planting Renovation" cbFor="services">Planting Renovation</label></td><td><label id="services_label3" htmlfor="services_commacheckbox3" for="services_commacheckbox3"><input type="checkbox" id="services_commacheckbox3" value="Tree Service" cbFor="services">Tree Service</label></td></tr><tr><td><label id="services_label4" htmlfor="services_commacheckbox4" for="services_commacheckbox4"><input type="checkbox" id="services_commacheckbox4" value="Weed Man Lawn Fertilization" cbFor="services">Weed Man Lawn Fertilization</label></td><td><label id="services_label5" htmlfor="services_commacheckbox5" for="services_commacheckbox5"><input type="checkbox" id="services_commacheckbox5" value="Snowplowing" cbFor="services">Snowplowing</label></td></tr><tr><td><label id="services_label6" htmlfor="services_commacheckbox6" for="services_commacheckbox6"><input type="checkbox" id="services_commacheckbox6" value="Other" cbFor="services">Other</label></td><td colspan="2"> </td></tr></tbody></table></span> </label> </form> I would appreciate any help on this. thank you. Hi I am trying to search an array that comes from a power shell script, the array of strings that returns is ever changing as it receives variables from the script. Therefore I need to use preg_grep to search for the word "not" I am also using another array which inverts this I then need to compare these new two arrays to the original and separate the results $working and not working into a table. I would be most grateful for any advice/solutions. The preg_grep aren't displaying anything.
<?php
//phpinfo();
ini_set('display_errors', 'On');
error_reporting(0);//E_ALL
echo '<html>
<style>
body
{
font-family:Calibri,Helvetica,sans-serif;
font-size:100%;
}
</style>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
function uploadJS(){
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
var textAreaValue=document.getElementById(\'ServerList\').value;
var trimmedTextAreaValue=textAreaValue.trim();
if(trimmedTextAreaValue!="") {
document.myForm.submit();
} else{
alert("Server List Text Area is Empty");
}
};
var input=document.getElementById(\'fileSelect\').value;
if(input!="") {
document.myForm.submit();
} else{
alert("You have not selected a file, please select one to proceed.");
}
var handleFileSelect = function(e) {
var files = e.target.files;
if(files.length === 1) {
document.forms.myForm.filecsv.value = files[0].name;
}
}
};
</script>
</head>';
#Upload Code
$target = "D:\Web\Upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). "
has been uploaded";
}
else {
}
if ($uploaded_size > 150000)
{ echo "Your file is too large.<br>";
$ok=0;
}
if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
if (!($uploaded_type=="text/csv")) { echo "<br>";
$ok=0;
}
$target = "upload/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition
if ($uploaded_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($uploaded_type =="text/php")
{ echo "No PHP files<br>";
$ok=0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok==0)
{
}
//If everything is ok we try to upload it
else {
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else
{
}
}
#Start of scripts to check Servers in textbox
if(isset($_POST['ServerList']))
{
//$arry=explode( "\r\n", $_POST['ServerList'] );
$txttrim = trim($_POST['ServerList']);
//$textAr = explode("\n", $text);
//$textAr1 = array_filter($text, 'trim'); // remove any extra \r characters left behind
$txtarea = explode("\n",$txttrim);
$txtarea = array_filter($txtarea,'trim');
foreach ($txtarea as $line => $servername)
{
//$line => $servername;
##check if querying itself....
}
echo '<pre>';
$target="D:/Web/Upload/"; $target= $target . basename( $_FILES['uploaded']['name']) ;
$csv = $target;
//$filename= $_FILES['uploaded']['name'];
$output=shell_exec("powershell -Command D:/Web/scripts/PHPfwrules.ps1 $csv < NUL");
echo '<h6>';
print_r($output);
$nomatch=preg_grep('/^not/i',$output);
echo $nomatch;
$match=preg_grep("/not/",$output,PREG_GREP_INVERT);
echo $match;
if ($working1= array_intersect($output,$match))
{
echo"<link rel=stylesheet type=text/css href=style.css>
<table class=results>
<tr>
<th>Server Name</th>
<th>Working</th>
</tr>
<tr>
<td>".$servername."</td>
<td>".$working1."</td>
</tr></table>
";
}
else if ($notworking1= array_intersect($output,$nomatch))
{
echo"<link rel=stylesheet type=text/css href=style.css>
<table class=results>
<tr>
<th>Server Name</th>
<th>Not Working</th>
</tr>
<tr>
<td>".$servername."</td>
<td>".$notworking1."</td>
</tr></table>
";
}
}
echo' <link rel=stylesheet href=dhtmlwindow.css type=text/css />
<link rel=stylesheet type=text/css href=style.css>
<script src=js/dhtmlwindow.js></script>
<hr />
<table class=results>
<tr>
<th>Server Name</th>
<th>Working</th>
<th> Not Working</th>
</tr>
<tr>
<td>'.$servername.'</td>
<td>'.$working1.'</td>
<td>'.$notworking1.'</td>
<td></td>
';
echo '</pre>';
echo '
<h3>Firewall Implementation </h3>
<h4>Please enter the server below, you can only select one server at a time. </h4>
<!--The form-->
<form action="fw2.php" method="post" name="myForm" id="myForm" enctype="multipart/form-data">
<textarea name=ServerList id=ServerList>
</textarea>
<h5>Please select a CSV file.</h5>
<input name="uploaded" type="file" /><br />
<input type="submit" value="Submit" />
<br>
</html> '
;
?>
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? Hi 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 />'; 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!!! 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! 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, 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! 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. 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. 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 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?? 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'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; } 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. |