PHP - Cannot Get Set To Work Properly W/ Array Values
I cannot get my script to update table: locations_all column city_state to the full state name.. Here's what I've been hacking at for 4.5 hours now! Ready to hit the sack.. Thanks for any input:
$state_list = array('AL' => "Alabama", 'AK' => "Alaska", 'AZ' => "Arizona", 'AR' => "Arkansas", 'CA' => "California", 'CO' => "Colorado", 'CT' => "Connecticut", 'DE' => "Delaware", 'DC' => "District Of Columbia", 'FL' => "Florida", 'GA' => "Georgia", 'HI' => "Hawaii", 'ID' => "Idaho", 'IL' => "Illinois", 'IN' => "Indiana", 'IA' => "Iowa", 'KS' => "Kansas", 'KY' => "Kentucky", 'LA' => "Louisiana", 'ME' => "Maine", 'MD' => "Maryland", 'MA' => "Massachusetts", 'MI' => "Michigan", 'MN' => "Minnesota", 'MS' => "Mississippi", 'MO' => "Missouri", 'MT' => "Montana", 'NE' => "Nebraska", 'NV' => "Nevada", 'NH' => "New Hampshire", 'NJ' => "New Jersey", 'NM' => "New Mexico", 'NY' => "New York", 'NC' => "North Carolina", 'ND' => "North Dakota", 'OH' => "Ohio", 'OK' => "Oklahoma", 'OR' => "Oregon", 'PA' => "Pennsylvania", 'RI' => "Rhode Island", 'SC' => "South Carolina", 'SD' => "South Dakota", 'TN' => "Tennessee", 'TX' => "Texas", 'UT' => "Utah", 'VT' => "Vermont", 'VA' => "Virginia", 'WA' => "Washington", 'WV' => "West Virginia", 'WI' => "Wisconsin", 'WY' => "Wyoming"); foreach ($state_list as $key => $value) { // get all state abbr and name values. while ($row = mysqli_fetch_array($result)) { $query2 = "UPDATE locations_all SET city_state=$value WHERE city_state=$key"; $result2 = mysqli_query($cxn, $query2) or die("MySQL error: " . mysqli_error($cxn) . "<hr>\nQuery: $query2"); } //while ($row = mysqli_fetch_array($result)) } //foreach ($state_list as $key => $value) Similar Tutorialswhy aint this working?? Code: [Select] <?php if ($_COOKIE['watch_id']){ $cookie = $_COOKIE['watch_id']; $cookie_query = mysql_query("SELECT * FROM user WHERE cookie='$cookie'"); if (mysql_num_rows($cookie_query) >= 1){ ?> <li><a href="/index.php">Home</a></li> <li><a href="/cpanel.php">C-Panel</a></li> <li><a href="/logout.php">Logout</a></li> pass <?php } if (mysql_num_rows($cookie_query) <= 1){ ?> <li><a href="register.php">Register</a></li> <li><a href="#" onclick="OPEN_login();">Login</a></li> <li><a href="index.php">Home</a></li> fail1 <?php } } if(!$_COOKIE['watch_id']){ ?> <li><a href="register.php">Register</a></li> <li><a href="#" onclick="OPEN_login();">Login</a></li> <li><a href="/index.php">Home</a></li> fail2 <?php } ?> i have checked in the browser and the cookies match but it always echos fail2 which means that this line is returning false: Code: [Select] if ($_COOKIE['watch_id']){ i have tried using isset but that didnt help either! any help? For the life of me, I cannot get an uploaded file to move from the tmp folder to the uploads folder. I have made sure all permissions were set to allow for the transfer. $upfile points to the right folder and file. print_r($_FILES); yields the following: Array ( [userfile] => Array ( [name] => 02.jpg [type] => image/jpeg [tmp_name] => /tmp/phpClFyXP [error] => 0 [size] => 121200 ) ) Any help would be greatly appreciated. HTML: Code: [Select] <html> <head></head> <body> <form enctype="multipart/form-data" action="upload.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value = "2000000000"> Upload this file: <input name ="userfile" type="file"> <input type="submit" value="Send File"> </form> </body> </html> PHP: <html> <head> <title>Uploading...</title> </head> <body> <h1>Uploading file...</h1> <?php if ($_FILES['userfile']['error'] > 0) { echo 'Problem: '; switch ($_FILES['userfile']['error']) { case 1: echo 'File exceeded upload_max_filesize'; break; case 2: echo 'File exceeded max_file_size'; break; case 3: echo 'File only partially uploaded'; break; case 4: echo 'No file uploaded'; break; } exit; } // Does the file have the right MIME type? // put the file where we'd like it $upfile = '/timporn/uploads/'.$_FILES['userfile']['name']; echo $upfile; if (is_uploaded_file($_FILES['userfile']['tmp_name'])) { if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $upfile)) { echo '<br>Problem: Could not move file to destination directory'; exit; } } else { echo 'Problem: Possible file upload attack. Filename: '; echo $_FILES['userfile']['name']; exit; } echo 'File uploaded successfully<br><br>'; // reformat the file contents $fp = fopen($upfile, 'r'); $contents = fread ($fp, filesize ($upfile)); fclose ($fp); $contents = strip_tags($contents); $fp = fopen($upfile, 'w'); fwrite($fp, $contents); fclose($fp); // show what was uploaded echo 'Preview of uploaded file contents:<br><hr>'; echo $contents; echo '<br><hr>'; ?> </body> </html> I'm able to get the image file name in the database, the image to the right place BUT the problem is the image is totally black and after it's uploaded, a whole bunch of warnings appear. Here are the warnings: Warning: getimagesize(image_files/image-16.jpg) [function.getimagesize]: failed to open stream: No such file or directory in C:\Desktop\xampp\htdocs\image-crop-demo.php on line 37 Warning: Division by zero in C:\Desktop\xampp\htdocs\image-crop-demo.php on line 54 Warning: Division by zero in C:\Users\Samantha\Desktop\xampp\htdocs\image-crop-demo.php on line 71 Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in C:\Desktop\xampp\htdocs\image-crop-demo.php on line 78 Warning: imagecopyresampled() expects parameter 1 to be resource, boolean given in C:\Desktop\xampp\htdocs\image-crop-demo.php on line 86 Warning: imagecopy() expects parameter 2 to be resource, boolean given in C:\Desktop\xampp\htdocs\image-crop-demo.php on line 102 Here is the form: <form action="image-crop-demo.php?username=<?php echo $username ?>" method="post" enctype="multipart/form-data"> Upload an image for processing<br> <input type="file" name="Image1"><br> <input type="submit" value="Upload"> </form> And here is the form action file: $username = $_GET['username']; define( 'DESIRED_IMAGE_WIDTH', 150 ); define( 'DESIRED_IMAGE_HEIGHT', 150 ); $source_path = $_FILES[ 'Image1' ][ 'name' ]; $sql="UPDATE thumbnail SET Image1='$source_path' WHERE username = '$username'"; if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } else { // // Add file validation code here // list( $source_width, $source_height, $source_type ) = getimagesize( $source_path ); switch ( $source_type ) { case IMAGETYPE_GIF: $source_gdim = imagecreatefromgif( $source_path ); break; case IMAGETYPE_JPEG: $source_gdim = imagecreatefromjpeg( $source_path ); break; case IMAGETYPE_PNG: $source_gdim = imagecreatefrompng( $source_path ); break; } $source_aspect_ratio = $source_width / $source_height; $desired_aspect_ratio = DESIRED_IMAGE_WIDTH / DESIRED_IMAGE_HEIGHT; if ( $source_aspect_ratio > $desired_aspect_ratio ) { // // Triggered when source image is wider // $temp_height = DESIRED_IMAGE_HEIGHT; $temp_width = ( int ) ( DESIRED_IMAGE_HEIGHT * $source_aspect_ratio ); } else { // // Triggered otherwise (i.e. source image is similar or taller) // $temp_width = DESIRED_IMAGE_WIDTH; $temp_height = ( int ) ( DESIRED_IMAGE_WIDTH / $source_aspect_ratio ); } // // Resize the image into a temporary GD image // $temp_gdim = imagecreatetruecolor( $temp_width, $temp_height ); imagecopyresampled( $temp_gdim, $source_gdim, 0, 0, 0, 0, $temp_width, $temp_height, $source_width, $source_height ); // // Copy cropped region from temporary image into the desired GD image // $x0 = ( $temp_width - DESIRED_IMAGE_WIDTH ) / 2; $y0 = ( $temp_height - DESIRED_IMAGE_HEIGHT ) / 2; $desired_gdim = imagecreatetruecolor( DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT ); imagecopy( $desired_gdim, $temp_gdim, 0, 0, $x0, $y0, DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT ); // // Render the image // Alternatively, you can save the image in file-system or database $remote_file = "image_files/".$_FILES["Image1"]["name"]; imagejpeg($desired_gdim,$remote_file); }// Hello,
I have one search form and when I search something the result is whole records from the database not only the search term. Any help is appreciated. I will post only the part where is calculating the rows from db but if need I will post whole pagination script.
$searchTerm = trim($_POST['term']); $adjacents = 3; $sql1 = mysql_query("SELECT * FROM images ORDER BY id ASC"); $nr = mysql_num_rows($sql1); $limit = 6; $targetpage = "search.php"; $page = $_GET['page']; if($page) $start = ($page - 1) * $limit; else $start = 0; if ($page == 0) $page = 1; $prev = $page - 1; // $prev = $page - 1 $next = $page + 1; // $next = $page + 1 $lastpage = ceil($nr/$limit); //lastpage = total pages / items per page. $lpm1 = $lastpage - 1; $pagination = ""; .... .... // pagination ... ... // while loop for the results $sql = "SELECT id, name, caption FROM images WHERE caption LIKE '%".$searchTerm."%' ORDER BY id DESC LIMIT $start, $limit"; $result = mysql_query($sql); while($row = mysql_fetch_array($result)) { $output.= "<div class=\"container_image\">"; $output.= "<a href=\"/pic-".$row['id'].".html\"><img src=\"/upload/".$row['name']."\" width=\"210\" height=\"150\"/></a>"; $output.= "</div>"; } Edited by vinsb, 21 July 2014 - 06:58 AM. Hi guys, I have stuck with this issue for over 3 hours now. My remove all button just wouldn't work.
Can anyone tell me what's the issue? I have 2 pages, one parent and another pop-up page that takes the values (cartSubmit) from parent. And I wrote out the code for both pages but I just cannot get it to work.
I apologize in advanced if my code looks messy or doesn't make any sense.
Please take a look at the code and let me know if you could spot anything wrong with it. Any help is greatly appreciated.
Here is the code related to the remove all button in the parent page:
if(isset($_POST['finalSelected'])) { echo "<br/>inside"; if(!empty($_POST['fSelected'])) { echo "<br/>if NOT empty"; $chosen = $_POST['fSelected']; foreach ($chosen as $item) echo "</br>aID selected: $item </br>"; //implode function to transform an array to a string //chosen(array) to $delimit(String) $delimitStr = implode(", ", $chosen); //Save the selected String to SESSION if(!isset($_SESSION["final"])) { $_SESSION["final"] .= "$delimitStr"; } else { $_SESSION["final"] .= ", $delimitStr"; } //Explode function to transform the SESSION variable back to an array for further trimming. $arraySession = explode(', ', $_SESSION["final"]); //Array unique to filter out duplicates. $uniqueArray = array_unique($arraySession); $cartSubmit = implode(", ",$uniqueArray); $_SESSION['cartSubmit'] = $cartSubmit; } else { echo "<br/>else empty"; $noSubmit = $_SESSION["final"]; //Explode function to transform the SESSION variable back to an array for further trimming. $arraySession = explode(', ', $_SESSION["final"]); //Array unique to filter out duplicates. $uniqueArray = array_unique($arraySession); $cartSubmit = implode(", ",$uniqueArray); $_SESSION['cartSubmit'] = $cartSubmit; } } <form name= "finalForm" method="POST" action="test6-1.php" target = "_self"> <input type="Submit" name="finalSelected"/> <a href="javascript:popup('test6-3.php?aID= <?php if(empty($_SESSION['final']) && empty($_SESSION['cartSubmit'])) echo "0"; else if(empty($cartSubmit)) echo "0"; else echo $_SESSION['cartSubmit'];?>')">Cart</a> <?php if(isset($FinalName)) { foreach($FinalName as $key => $item) {?> <tr><td> <input type="checkbox" name="fSelected[]" value="<?php echo htmlspecialchars($FinalID[$key])?>" /> <?php echo "$FinalID[$key] & $item";?> </td></tr> <?php } }?> </form>And here is the code in the pop-up page. <script> window.onunload = refreshParent; function refreshParent() { window.opener.location.reload(); } </script> if(isset($_POST['removeAll'])) { $aID = "0"; unset($_SESSION['cartSubmit']); unset($_SESSION['final']); header("Location : test6-3.php?aID=0"); } Edited by Cyjm1120, 18 November 2014 - 12:16 PM. Hi all, I'm a first time poster here and I would really appreciate some guidance with my latest php challenge! I've spent the entire day googling and reading and to be honest I think I'm really over my head and need the assistance of someone experienced to advise the best way to go! I have a multi dimensional array that looks like (see below); the array is created by CodeIgniter's database library (the rows returned from a select query) but I think this is a generic PHP question as opposed to having anything to do with CI because it related to working with arrays. I'm wondering how I might go about searching the array below for the key problem_id and a value equal to a variable which I would provide. Then, when it finds an array with a the matching key and variable, it outputs the other values in that part of the array too. For example, using the sample data below. How would you recommend that I search the array for all the arrays that have the key problem_id and the value 3 and then have it output the value of the key problem_update_date and the value of the key problem_update_text. Then keep searching to find the next occurrence? Thanks in advance, as above, I've been searching really hard for the answer and believe i'm over my head! Output of print_r($updates); CI_DB_mysql_result Object ( [conn_id] => Resource id #30 [result_id] => Resource id #35 [result_array] => Array ( ) [result_object] => Array ( ) [current_row] => 0 [num_rows] => 5 [row_data] => ) Output of print_r($updates->result_array()); Array ( [0] => Array ( [problem_update_id] => 1 [problem_id] => 3 [problem_update_date] => 2010-10-01 [problem_update_text] => Some details about a paricular issue [problem_update_active] => 1 ) [1] => Array ( [problem_update_id] => 4 [problem_id] => 3 [problem_update_date] => 2010-10-01 [problem_update_text] => Another update about the problem with an ID of 3 [problem_update_active] => 1 ) [2] => Array ( [problem_update_id] => 5 [problem_id] => 4 [problem_update_date] => 2010-10-12 [problem_update_text] => An update about the problem with an ID of four [problem_update_active] => 1 ) [3] => Array ( [problem_update_id] => 6 [problem_id] => 4 [problem_update_date] => 2010-10-12 [problem_update_text] => An update about the problem with an ID of 6 [problem_update_active] => 1 ) [4] => Array ( [problem_update_id] => 7 [problem_id] => 3 [problem_update_date] => 2010-10-12 [problem_update_text] => Some new update about the problem with the ID of 3 [problem_update_active] => 1 ) ) I am currently creating a multi-user login system, and I have created the database in MySQL, but the problem is that my PHP script is not working as expected. I would like it so that if the user enters in a correct username + password combination, then they are redirected to a webpage called "congrats.php" for example. However, with my current PHP code, if I include a redirection instruction based on the correct input, then when I run the script, then the user is instantly taken to the congrats.php page without filling in any login details. I'm quite sure that the database has been connected to, as due to the layout of my script at the moment, the text that reads "You did it!" appears 4 times, the same number of rows in my MySQL database. My PHP coding for this is: Code: [Select] <html><head><title>Multi-User Log In Form</title></head> <body> <?php $self = $_SERVER['PHP_SELF']; $username = $_POST['username']; $password = $_POST['password']; ?> <form action = "<?php echo $self; ?>" method = "post"> Username <input type = "text" name = "username" size = "8"> Password <input type = "password" name = "password" size = "8"> <input type = "submit" value="Submit"> </form> <?php $conn = @mysql_connect("localhost", "root", "") or die ("Err: Conn"); $rs = @mysql_select_db("test3", $conn) or die ("Err: Db"); $sql = "select * from users"; $rs = mysql_query($sql, $conn); while ($row = mysql_fetch_array($rs)) { $name = $row["uname"]; $pass = $row["pword"]; if ($username = $name && $password = $pass) { //CODE FOR REDIRECTION SHOULD GO HERE //header("location:congrats.php"); echo "You did it!"; } else { echo "Invalid username and password combination"; } } ?></body> </html> Any help in trying to get it so that my PHP script will redirect only if a correct username + password combination is entered would be greatly appreciated HI, according to my knowledge session_destroy() function would destroy all session variables and mysql_close() would close connection with the database. i make a simply logoff.php file and close myssql connection and destroy session. but i still get values from the database and session variables. and doesnt work properly here is the code Code: [Select] <?php session_start(); /* * To change this template, choose Tools | Templates * and open the template in the editor. */ require_once '../database/db_connecting.php'; $dbname="sahansevena";//set database name $con= setConnections();//make connections use implemented methode in db_connectiong.php mysql_select_db($dbname, $con); //update the time and date of the admin table $update_time="update admin set last_logged_date =CURDATE(), last_log_time=CURTIME() where username='$uname'limit 3,4"; //my admin table contain 5 colums they are id, username,password, last_logged_date, last_log_time $link= mysql_query($update_time); // mysql_select_db($dbname, $link); //$con=mysql_connect('localhost', 'root','ijts'); $result="select * from admin where username='a'"; $result=mysql_query($result); mysql_close($con); //here i just check after closing data baseconnection whether i do get reselts but i do, why? echo "after the cnnection was closed"; echo "<html>"; echo "<table border='1' cellspacing='1' cellpadding='2' align='center'>"; echo "<thead>"; echo"<tr>"; echo "<th>"; echo ID; echo"</th>"; echo" <th>";echo Username; echo"</th>"; echo"<th>";echo Password; echo"</th>"; echo"<th>";echo Last_logged_date; echo "</th>"; echo "<th>";echo Last_logged_time; echo "</th>"; echo" </tr>"; echo" </thead>"; echo" <tbody>"; while($row= mysql_fetch_array($result,MYSQL_BOTH)){ echo "<tr>"; echo "<td>"; echo $row[0]; echo "</td>"; echo "<td>"; echo $row[1]; echo "</td>"; echo "<td>"; echo $row[2]; echo "</td>"; echo "<td>"; echo $row[3]; echo "</td>"; echo "<td>"; echo $row[4]; echo "</td>"; echo "</tr>"; } echo" </tbody>"; echo "</table>"; echo "</html>"; session_destroy(); session_commit(); echo "session and database are closed but i still get values".$_SESSION['admin']; ?> I have an ongoing mission to tighten up my code for a directory listing for a non-profit organization. Brief background is - there are multiple "company" members in each County, and usually multiple "contact people" at each company. Also, some companies have "branch" offices, but not all, and most of the branches also have "contact people." I have successfully segregated my code, so that the "listing" work is handled by separate functions. I am trying to work with JOIN queries, and in my first step I am treating the "company" and "branch" listings with separate test code for now, and the branch output is missing the first row of the array that I am creating.
To demonstrate what is happening, I am going to attache a screen shot of the correct results from my query, which starts with a branch called "Louisiana Branch". To see the results of my code, click on this link: http://www.nmlta.org...ew_br_test2.php
And finally, I am including the working portions of my code below... leaving out the connection details, which are not an issue. Just to be clear, I have the exact code structure for a query of the company table, with a similar JOIN, and the listing results of my code do not skip the first row of that array. I must be missing something that should be obvious, but I can't see the problem. I would appreciate any and all help... thanks - Rob
My Code:
<?php function listCompany($row) { echo $row['comp_name'],"<br />"; if (!empty($row['comp_uw'])) { echo $row['comp_uw'],"<br />";} echo "</b>",$row['comp_street'],"<br />"; if (!empty($row['comp_pobox'])) { echo $row['comp_pobox'],"<br />";} echo $row['comp_csz'],"<br />"; echo $row['comp_ph'],"   Fax: ",$row['comp_fx'],"<br />"; if (!empty($row['comp_tfree'])) { echo "Toll Free: ",$row['comp_tfree'],"<br />";} if (!empty($row['comp_email'])) { echo "Email: <a href='mailto:",$row['comp_email'],"'>",$row['comp_email'],"</a><br />";} if (!empty($row['comp_web'])) { echo "<a href='http://",$row['comp_web'],"' target='_blank'>",$row['comp_web'],"</a><br />";} echo "</p>"; } function listBranch($row2) { if (!empty($row2['br_name'])) { echo "<p>     <b>",$row2['branch_name'],"</b><br />";} echo "     ",$row2['br_street'],"<br />"; echo "     ",$row2['br_csz'],"<br />"; echo "     ",$row2['br_ph'],"   ",$row2['br_fx'],"<br /></p>"; } function listContact($row) { if (!empty($row['cont_name'])) { echo "<p>     <b>",$row['cont_name'],"</b>, ",$row['cont_title'],"<br />";} if (!empty($row['cont_email'])) { echo "     Email: <a href='mailto:",$row['cont_email'],"'>",$row['cont_email'],"</a><br />";} echo "</p>"; } function listBranchContact($row2) { if (!empty($row2['cont_name'])) { echo "<p>          <b>",$row2['cont_name'],"</b>, ",$row2['cont_title'],"<br />";} if (!empty($row2['cont_email'])) { echo "          Email: <a href='mailto:",$row2['cont_email'],"'>",$row2['cont_email'],"</a><br />";} echo "</p>"; } // Connection to DB // Retrieve all the data from the "company" table $query2 = "SELECT * FROM branch LEFT JOIN br_contact ON branch.branch_id = br_contact.branch_id WHERE br_county = 'BERNALILLO' ORDER BY branch.comp_name, branch.br_street, br_contact.cont_rank"; $result2 = $mysqli->query($query2) or die($mysqli->error.__LINE__); // Build the $company_array $branch_array = array(); while($row2 = $result2->fetch_assoc()) { $branch_array[] = $row2; } $lastBranch = ''; //Initialize $lastBranch variable // Start building the table to show results echo "<table border='1' cellpadding='10' cellspacing='0' bgcolor='#f0f0f0' style='margin-left:100px; margin-bottom:20px'>"; // Begin the "foreach" loop for rows in the $branch_array foreach($branch_array as $row2) { // Branch Loop // Check if this is a different branch than the last one if ($lastBranch != $row2['branch_id']) { // Loop to check if New Branch // If this is a different branch - change the $lastBranch variable $lastBranch = $row2['branch_id']; echo "<tr><td>"; // List the branch info only if it is not the $lastBranch listBranch($row2); } // End check if New Company loop // List all Contacts in the Branch listBranchContact($row2); } // End Branch Loop echo "</td></tr>"; // Free result set mysqli_free_result($result2); echo "</table>"; mysqli_close($mysqli); ?>Attached Files adminer_bern_br_join_cont.png 450.37KB 0 downloads Code: [Select] $teamLineUp=explode(";", $team['lineUp']); #This is the team line up foreach ($teamLineUp as $value) echo "<BR>".$value; this works fine and outputs what I want EXCEPT if a word has a ' in it; for example the name O'Reilly gets broken into 2 values "O" and "Reilly"; is there a way around this? I have mysql select query shown below retrieving data from a database:
$sql = " SELECT student, sum( test_score ) as score FROM test INNER JOIN level ON test.level_id = level.level_id GROUP BY student" $result = $mysqli->query($sql, MYSQLI_STORE_RESULT); if($result) { while ($row = $result->fetch_array(MYSQLI_ASSOC)) { var_dump($row); } }On inspection of the retrieved array with var_dump(), i have these result below: array (size=2) 'John' => string 'English' (length=2) 'Score' => string '20' (length=3) array (size=2) 'Mary' => string 'Math' (length=3) 'Score' => string '35' (length=3) array (size=2) 'Samuel' => string 'Physics' (length=3) 'Score' => string '5' (length=3)How do I get at and print out the highest score from this set of array values within this context. I tried this echo max($row['count']) but i understandably got this feedback: Warning: max(): When only one parameter is given, it must be an array Thanks. Hi there, Basic question, but I can't seem to find a page in the PHP docs that answers (though I'm sure such a one exists, I just can't seem to think up the right search terms - anyway) My question is: is there a short-hand way to use a value from an associative array as the key in another associative array? So for example, given this array: $the_array = array(0 => array('name': 'the_name', 'value' : 'the_value'), 1 => etc....); then this kind of foreach loop doesn't work Code: [Select] $new_data = array(); foreach($the_array as $element){ $new_data[$element['name']] = $element['value']; } Obviously I can just save out the values, like $name = $element['name'] --- but I was just wondering if there was a more efficient way to do it? Cheers, PS. I tried encapsulating with {} - i.e. $new_data[{$element['name']}] --- but that also fails. Hello all, I have yet again trouble finding a logical solution to my problem. I'm fetching an array which can hold 1 or more values. The problem is, I want these values to ouput in my json_encode function, but this also needs to happen dynamically depending on the amount of values. I can't explain it further, so here's the code so far: Code: (php) [Select] $files = mysql_fetch_array($get_files); $a = count($files); $i = 1; while ($files) { $variablename = 'fileName' . $i; $$variablename = $files['fileName']; $i++; } $output = array( OTHER VALUES , 'fileName1' => $fileName1, 'fileName2' => $fileName2, 'fileName3' => $fileName3, ............); // How do I add the fileNames dynamically depending on how many there are? This got me thinking, I also need to dynamically GET the values with jQuery. How would I do that, when the above eventually works? Thank you. So ive created a forum that I got handling several different approvals. (it is used to approve or decline all submitted notes) it works fine and it even submits fine im at the part know where i process the information and do something with it, below is my form: <form action="course_proccess.php?action=approve" method="post"> <table align="left" border="1" cellspacing="0" cellpadding="3"> <tr> <td><b>Author</b></td> <td><b>File name</b></td> <td><b>Download</b></td> <td><b>Suggested catagory</b></td> <td><b>Select Catagory</b></td> <td>Approve</td> </tr> <td><input type="text " disabled="disabled" name="tr1_author" value="MikeH" </td> <td><input typee="text " disabled="disabled" name="tr1_name" value="A lot of my skills set back"</td> <td><a href= /uzEr%20Upl0ds/cache.zip > Download</a></td> <td>1001 Laws - Polceing </td> <td><select name="tr1_scatagory"> <option value="1"> Intro To Law </option> <option value="2"> 1001 Laws - Police Foundations </option> </select></td> <td><select name = "tr1_approve"> <option value = "1"> Yes</option> <option value = "2"> no</option> </select></td> </tr> <td><input type="text " disabled="disabled" name="tr2_author" value="MikeH" </td> <td><input typee="text " disabled="disabled" name="tr2_name" value="MM"</td> <td><a href= /uzEr%20Upl0ds/Michael Heintzman.doc > Download</a></td> <td>1001 Laws - Polceing </td> <td><select name="tr2_scatagory"> <option value="1"> Intro To Law </option> <option value="2"> 1001 Laws - Police Foundations </option> </select></td> <td><select name = "tr2_approve"> <option value = "1"> Yes</option> <option value = "2"> no</option> </select></td> </tr> <input type="hidden" name="rowCount" value="2"> <tr> <td><input type="submit" name="sendData" value="send"/></td> </tr> </table> </form> so what I do in my process file is I have a for loop for all of the "TR's" in the table and if it is approved I have an if statment and then I want to add db stuff my problem is my $_POST's are returning blank and I have no idea why. Can someone please assit me with this? (p.s i have debugged and it does get into the if approve == 1 statment. if(isset($_GET['action'])){ if ($_GET['action'] == "approve"){ if(isset($_POST['sendData'])) { $dataArray = array(); $row_count = $_POST['rowCount']; for($i=1;$i<$row_count;$i++) { $approven = "tr".$i."_approve"; $approve = $_POST[$approven]; if($approve == 1) { //Move the info over to "approved files" and delete it out of newnotes $author = "tr".$i."_author"; $location = "tr".$i."_location"; $catagory ="tr".$i."_scatagory"; $filename = "tr".$i."_name"; $submitedby = $_POST['author']; die($submitedby); $dataArray[]=array('author'=>$author,'fileName'=>$fileName,'Catagory'=>$catagory,'location'=>$location); var_dump($dataArray); }else{ //Email user saying they did not recive credits AND delete the entry } } if(!empty($dataArray)) { //now do what you want with the dataArray... var_dumb($dataArray); } } } I have an array created to control the down states of the my buttons in my navigation. Which is working well. This array will have quite a few strings in it before I'm done. I then want to conditionally load a CSS file for all the files in that array with the exception of two, is this possible? In plain in english I want to say If in array apart from these values then load my css file. My array (will have more values when complete) Code: [Select] $otherTitles = array('Product Selector', 'Avon Range', 'Knightsbridge Range', 'Kingston Range' ); My code to load a css file Code: [Select] <?php if (in_array($title, $otherTitles)) { ?> <link rel="stylesheet" type="text/css" href="homepage.css"/> <?php } ?> I want all titles in the otherTitles array to get this CSS file apart from two Product Selector and Avon Range. Thanks Richard I need to some how pull comma separated images $data[23] from this $data array and then put them into there own array so I can insert them into separate rows in a database. This is the provided array: $data[0] => VIN $data[1] => StockNumber ...(all the other number here) $data[23] => Image_URLs (comma seperated) $data[24] => Equipment // I need something like this (obviously doesn't work?!@#) $delimiter = ","; $img = explode($delimiter, $data[23]); foreach($img as $pic){ $sqlPic = "insert into class_prodimages (pid image rank) values('".$LastId['id']."', '$pic', '".rand(1,20)."')"; } Any help here? I have the following array structu Code: [Select] [0] => Array ( [id] => Array ( [$t] => http://www.google.com/mate/ ) [updated] => Array ( [$t] => 2011-08-31T11:43:05.942Z ) [category] => Array ( [0] => Array ( [scheme] => http://schemas.google.com/g/ [term] => http://schemas.google.com/contact/ ) ) [title] => Array ( [type] => text [$t] => Name ) [link] => Array ( [0] => Array ( [rel] => http://schemas.google.com/contacts/2008/rel#edit-photo [type] => image/* [href] => https://www.google.com/mate/feeds/photos/media/ ) [1] => Array ( [rel] => self [type] => application/atom+xml [href] => https://www.google.com/mate/feeds/contacts ) [2] => Array ( [rel] => edit [type] => application/atom+xml [href] => https://www.google.com/mate/feeds/ ) ) [gd$email] => Array ( [0] => Array ( [rel] => http://schemas.google.com/g/2005#other [address] => email_address@gmail.com [primary] => true ) ) ) I am tried to display name and email address. I am using following method, can anyone tell me is there any better way? Thank u 4u help. NAME $name=( $emp_det[0]['title'][t]); $email =( $emp_det[0]['gdemail'][0][address]); My code Code: [Select] <?php set_time_limit (0); include("config.php"); $data = "<td><a href='/hospitals-in/Alabama'>Alabama</a></td> <td><a href='/hospitals-in/District-of-Columbia'>District of Columbia</a></td> <td><a href='/hospitals-in/Kentucky'>Kentucky</a></td> <td><a href='/hospitals-in/Montana'>Montana</a></td> <td><a href='/hospitals-in/Ohio'>Ohio</a></td> <td><a href='/hospitals-in/Texas'>Texas</a></td> <td><a href='/hospitals-in/Alaska'>Alaska</a></td> <td><a href='/hospitals-in/Florida'>Florida</a></td> <td><a href='/hospitals-in/Louisiana'>Louisiana</a></td> <td><a href='/hospitals-in/Nebraska'>Nebraska</a></td> <td><a href='/hospitals-in/Oklahoma'>Oklahoma</a></td> <td><a href='/hospitals-in/Utah'>Utah</a></td> <td><a href='/hospitals-in/America-Samoa'>America Samoa</a></td> <td><a href='/hospitals-in/Georgia'>Georgia</a></td> <td><a href='/hospitals-in/Maine'>Maine</a></td> <td><a href='/hospitals-in/Nevada'>Nevada</a></td> <td><a href='/hospitals-in/Oregon'>Oregon</a></td> <td><a href='/hospitals-in/Vermont'>Vermont</a></td> <td><a href='/hospitals-in/Arizona'>Arizona</a></td> <td><a href='/hospitals-in/Hawaii'>Hawaii</a></td> <td><a href='/hospitals-in/Maryland'>Maryland</a></td> <td><a href='/hospitals-in/New-Hampshire'>New Hampshire</a></td> <td><a href='/hospitals-in/Pennsylvania'>Pennsylvania</a></td> <td><a href='/hospitals-in/Virgin-Islands'>Virgin Islands</a></td> <td><a href='/hospitals-in/Arkansas'>Arkansas</a></td> <td><a href='/hospitals-in/Idaho'>Idaho</a></td> <td><a href='/hospitals-in/Massachusetts'>Massachusetts</a></td> <td><a href='/hospitals-in/New-Jersey'>New Jersey</a></td> <td><a href='/hospitals-in/Puerto-Rico'>Puerto Rico</a></td> <td><a href='/hospitals-in/Virginia'>Virginia</a></td> <td><a href='/hospitals-in/California'>California</a></td> <td><a href='/hospitals-in/Illinois'>Illinois</a></td> <td><a href='/hospitals-in/Michigan'>Michigan</a></td> <td><a href='/hospitals-in/New-Mexico'>New Mexico</a></td> <td><a href='/hospitals-in/Rhode-Island'>Rhode Island</a></td> <td><a href='/hospitals-in/Washington'>Washington</a></td> <td><a href='/hospitals-in/Colorado'>Colorado</a></td> <td><a href='/hospitals-in/Indiana'>Indiana</a></td> <td><a href='/hospitals-in/Minnesota'>Minnesota</a></td> <td><a href='/hospitals-in/New-York'>New York</a></td> <td><a href='/hospitals-in/South-Carolina'>South Carolina</a></td> <td><a href='/hospitals-in/West-Virginia'>West Virginia</a></td> <td><a href='/hospitals-in/Connecticut'>Connecticut</a></td> <td><a href='/hospitals-in/Iowa'>Iowa</a></td> <td><a href='/hospitals-in/Mississippi'>Mississippi</a></td> <td><a href='/hospitals-in/North-Carolina'>North Carolina</a></td> <td><a href='/hospitals-in/South-Dakota'>South Dakota</a></td> <td><a href='/hospitals-in/Wisconsin'>Wisconsin</a></td> <td><a href='/hospitals-in/Delaware'>Delaware</a></td> <td><a href='/hospitals-in/Kansas'>Kansas</a></td> <td><a href='/hospitals-in/Missouri'>Missouri</a></td> <td><a href='/hospitals-in/North-Dakota'>North Dakota</a></td> <td><a href='/hospitals-in/Tennessee'>Tennessee</a></td> <td><a href='/hospitals-in/Wyoming'>Wyoming</a></td>"; preg_match_all("~<td><a\s+href='(.*?)'>(.*?)</a></td>~", $data, $link); echo '<pre>'; echo print_r($link); echo '</pre>' ; $countlink = count($link[1]); for($i=0 ; $i < $countlink; $i++) { if (is_array($link)) { $sitelink = "http://www.xxx.com".$link[1][$i]; $hospitallink = file_get_contents("$sitelink"); preg_match_all("~<td><a href=\"/hospital/(.*?)\">(.*?)</a></td>~", $hospitallink, $hospitalinfo); $city = $link[2][$i]; $countinfo = count($hospitalinfo[1]); for($j=0 ; $j < $countinfo ; $j++) { $infolink = "http://www.xxx.com/hospital/".$hospitalinfo[1][$j]; $getinfo = file_get_contents("$infolink"); $regex = "~<b>Name:</b>\s+(.*?)\s+</p>\s+<p>\s+<b>Address:</b>\s+(.*?)\s+</p>\s+<p>\s+<b>Phone:</b>\s+(.*?)\s+</p>\s+<p>\s+<b>Number\s+of\s+Beds:</b>\s+(.*?)\s+</p>\s+<p>\s+<b>Type:</b>\s+(.*?)\s+</p>\s+<p>\s+<b>System:</b>\s+(.*?)\s+</p>\s+<p>\s+<b>Website:</b>\s+<a href=\"(.*?)\">(.*?)</a>\s+</p>\s+<p>\s+(.*?)</p>~s"; preg_match_all($regex, $getinfo, $critinfo); preg_match_all("~<li>\s+(.*?)</li>~s", $getinfo, $servinfo); preg_match_all("~<h4>Hospital\s+Quality\s+and\s+Rating\s+information</h4>\s+<p>Data\s+based\s+on\s+2010\s+Health\s+Quality\s+Alliance\s+database</p>\s+<p>\s+<b>(.*?)</b><br>\s+(.*?)</p>~s", $getinfo, $mortality); preg_match_all("/(\d+)?\.?(\d+)?%/", $mortality[2][0], $number); $name = $critinfo[1][0]; $address = preg_replace('/\s\s+/', ' ', $address); $number = implode(",", $number[0]); $servinfo = implode(",", $servinfo[1]); $sql = "INSERT INTO hospital (name, address, servinfo, mortality) VALUES ('$name', '$address', '$servinfo', '$number')"; $exec_sql = mysql_query($sql); } } } ?> print_r($link) shows this :- Code: [Select] Array ( [0] => Array ( [0] => Alabama [1] => District of Columbia [2] => Kentucky [3] => Montana [4] => Ohio [5] => Texas [6] => Alaska [7] => Florida [8] => Louisiana [9] => Nebraska [10] => Oklahoma [11] => Utah [12] => America Samoa [13] => Georgia [14] => Maine [15] => Nevada [16] => Oregon [17] => Vermont [18] => Arizona [19] => Hawaii [20] => Maryland [21] => New Hampshire [22] => Pennsylvania [23] => Virgin Islands [24] => Arkansas [25] => Idaho [26] => Massachusetts [27] => New Jersey [28] => Puerto Rico [29] => Virginia [30] => California [31] => Illinois [32] => Michigan [33] => New Mexico [34] => Rhode Island [35] => Washington [36] => Colorado [37] => Indiana [38] => Minnesota [39] => New York [40] => South Carolina [41] => West Virginia [42] => Connecticut [43] => Iowa [44] => Mississippi [45] => North Carolina [46] => South Dakota [47] => Wisconsin [48] => Delaware [49] => Kansas [50] => Missouri [51] => North Dakota [52] => Tennessee [53] => Wyoming ) [1] => Array ( [0] => /hospitals-in/Alabama [1] => /hospitals-in/District-of-Columbia [2] => /hospitals-in/Kentucky [3] => /hospitals-in/Montana [4] => /hospitals-in/Ohio [5] => /hospitals-in/Texas [6] => /hospitals-in/Alaska [7] => /hospitals-in/Florida [8] => /hospitals-in/Louisiana [9] => /hospitals-in/Nebraska [10] => /hospitals-in/Oklahoma [11] => /hospitals-in/Utah [12] => /hospitals-in/America-Samoa [13] => /hospitals-in/Georgia [14] => /hospitals-in/Maine [15] => /hospitals-in/Nevada [16] => /hospitals-in/Oregon [17] => /hospitals-in/Vermont [18] => /hospitals-in/Arizona [19] => /hospitals-in/Hawaii [20] => /hospitals-in/Maryland [21] => /hospitals-in/New-Hampshire [22] => /hospitals-in/Pennsylvania [23] => /hospitals-in/Virgin-Islands [24] => /hospitals-in/Arkansas [25] => /hospitals-in/Idaho [26] => /hospitals-in/Massachusetts [27] => /hospitals-in/New-Jersey [28] => /hospitals-in/Puerto-Rico [29] => /hospitals-in/Virginia [30] => /hospitals-in/California [31] => /hospitals-in/Illinois [32] => /hospitals-in/Michigan [33] => /hospitals-in/New-Mexico [34] => /hospitals-in/Rhode-Island [35] => /hospitals-in/Washington [36] => /hospitals-in/Colorado [37] => /hospitals-in/Indiana [38] => /hospitals-in/Minnesota [39] => /hospitals-in/New-York [40] => /hospitals-in/South-Carolina [41] => /hospitals-in/West-Virginia [42] => /hospitals-in/Connecticut [43] => /hospitals-in/Iowa [44] => /hospitals-in/Mississippi [45] => /hospitals-in/North-Carolina [46] => /hospitals-in/South-Dakota [47] => /hospitals-in/Wisconsin [48] => /hospitals-in/Delaware [49] => /hospitals-in/Kansas [50] => /hospitals-in/Missouri [51] => /hospitals-in/North-Dakota [52] => /hospitals-in/Tennessee [53] => /hospitals-in/Wyoming ) [2] => Array ( [0] => Alabama [1] => District of Columbia [2] => Kentucky [3] => Montana [4] => Ohio [5] => Texas [6] => Alaska [7] => Florida [8] => Louisiana [9] => Nebraska [10] => Oklahoma [11] => Utah [12] => America Samoa [13] => Georgia [14] => Maine [15] => Nevada [16] => Oregon [17] => Vermont [18] => Arizona [19] => Hawaii [20] => Maryland [21] => New Hampshire [22] => Pennsylvania [23] => Virgin Islands [24] => Arkansas [25] => Idaho [26] => Massachusetts [27] => New Jersey [28] => Puerto Rico [29] => Virginia [30] => California [31] => Illinois [32] => Michigan [33] => New Mexico [34] => Rhode Island [35] => Washington [36] => Colorado [37] => Indiana [38] => Minnesota [39] => New York [40] => South Carolina [41] => West Virginia [42] => Connecticut [43] => Iowa [44] => Mississippi [45] => North Carolina [46] => South Dakota [47] => Wisconsin [48] => Delaware [49] => Kansas [50] => Missouri [51] => North Dakota [52] => Tennessee [53] => Wyoming ) ) 1 Earlier it was giving an error without if (is_array($link)) { Code: [Select] Fatal error: Cannot use string offset as an array However after adding it, it wont go to /hospitals-in/District-of-Columbia which is $link[1][1]; Can someone please point me my mistake Hello there again!
I have the following construct of array now (schematics):
array[0] array[id] = "1" array[title] = "title" array[1] array[id] = "3" array[title] = "another title"Now what i want to do, is to assign the parent-array keys to the IDs of it's contents. This is what it should look like: array[1] array[id] = "1" array[title] = "title" array[3] array[id] = "3" array[title] = "another title"How do I do that again? I know I did this some years ago, but I can not remember how. |