PHP - Using Foreach With Mysql (i Think)
Hi, I am new to php, mysql and have made some progress, but recently ran into a wall. I hope someone can help me. I am building a simple links script that has categories and a list of links with website name, url and a brief description. I have two tables-categories and links.
I have gotten the back end finished and can add, edit and delete links and categories. The problem is in the front end. I have the script set up so that when I click on a category name a page is dynamically created using ?id=idnumber. and the category name is echoed on the page. But I can't seem to find the solution I need to get the links that have a matching category name to display. I have tried using JOIN, LEFT JOIN, INNER JOIN, and RIGHT JOIN and get the same result, ALL the links in the links table are displayed. I think I need to create a new array and use the foreach loop to accomplish this, but I am not sure. Nor am I sure how to use the foreach even though I have read several tutorials on it. Here is the code I have so far. Any help would be appreciated. Thanks in advance. Code: [Select] <? include "db.php" ?> <?php $id = intval($_GET['id']); // force user input to an int if(!empty($id)) // if the user input is not empty or 0 { $query = "SELECT * FROM categories WHERE id = $id LIMIT 1"; // attempt to select the row for the given id $result = mysql_query($query) or die(mysql_error()); if(mysql_num_rows($result) > 0) // if the categorie was found { $row = mysql_fetch_assoc($result); // fetch the resultset to an array called $row echo $row['categories']; // echo the categories field from the row // etc. } else { die('Error: Bad ID'); // the categories was not found } } else { die('Error: Bad ID'); // the id given was not valid } mysql_close(); ?> <? include "db.php" ?> <?php $sql="SELECT * FROM links,categories ORDER BY links.categories LIMIT 10"; $result=mysql_query($sql); ?> <table width="80%" align="center" border="0" cellspacing="1" cellpadding="0"> <tr> <td> <table width="100%" border="1" cellspacing="0" cellpadding="3"> <tr> <td colspan="3"><strong>List data from mysql </strong> </td> </tr> <tr> <td align="center"><strong>Name</strong></td> <td align="center"><strong>URL</strong></td> <td align="center"><strong>Content</strong></td> </tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td><? echo $rows['name']; ?></td> <td><a href="<? echo $rows['url']; ?>"><? echo $rows['url']; ?></a></td> <td><? echo $rows['content']; ?></td> </tr> <?php } ?> </table> </td> </tr> </table> <?php mysql_close(); ?> Similar TutorialsI'm trying to get a foreach loop to one variable that I can insert into MySQL - I've tried a number of things but can't get it working. How do I create one single variable that is created from the foreach? Thanks! Jason ok this may not be able to be done .... but here goes nothing ... i have a roster that displays member names as a link to thier profile using a form and onclick submit() now what i didnt realize is that the form name will have to increment for each record returned from the query. i am by no means a guru with php so i need some help adding the foreach statement and setting the form name to increment each time what i need: I need this to automatically go +1 for each record returned Code: [Select] <form name="view3" action="./viewinfo.php" method="post"> <a href="#" onclick="document['view3'].submit()"> and i need the correct way to use the foreach statement ... i have read the manual and it just confuzzeled me . here is what i have so far. <?php include './clan_new/config.php'; include './clan_new/access.php'; $db = mysql_connect ($hostname, $username, $password) or die ('Failed to connect to database: ' . mysql_error()); mysql_select_db($database); $query = "SELECT * FROM $member_table WHERE $member_table.rank = 6 ORDER BY $member_table.name ASC"; $result = mysql_query($query) or die ('Failed to query ' . mysql_error()); while ($row = mysql_fetch_assoc($result)) { $steamid = $row['authid']; $name = $row['name']; $email = $row['email']; $fid = $row['fid']; $avatar = $row['avatar']; echo "<tr>"; if ($avatar==""){ echo "<td> </td>"; } else{ echo "<td><img height='35' width='35' src='./clan_new/avatars/$avatar'></td>"; } ?> <form name="view3" action="./viewinfo.php" method="post"> <input type="hidden" id="authid" name="authid" value="<?php echo "$steamid" ; ?>" /> </form> <td align="center"><a href="#" onclick="document['view3'].submit()"> <?php echo "$name" ; ?></a></td> <?php echo "<td align=\"center\"><a class=\"style2\" href=\"mailto:$email\" class=\"style2\">$email</a></td>"; if ($fid==""){ echo ""; } else{ echo "<td align=\"center\">+<a class=\"style2\" href=\"steam://friends/add/$fid\">Friend</a></td>"; } echo "</tr>"; } mysql_free_result($result); mysql_close($db); ?> I have a checkbox when it is checked i garb its value ---meaning the id i take that id and i would like to use it in my where mysql_query statement then I would like to insert the array from the other foreach one after another with a prov meaning provider here is my code print "<select name='prov[]'>"; print '<option value=""></option>'; mysql_connect("localhost", "root", "root") or die(mysql_error()); mysql_select_db("db1") or die(mysql_error()); $query2 = "SELECT * FROM admin"; $result2 = mysql_query($query2) or die(mysql_error()); while($row2 = mysql_fetch_array($result2)) { if ($row2['priv']==prov){print '<option value="'.$row2['user'].'">'.$row2['user'].'</option>';} } print '</select>'; print '</div>'; <?php if (!empty($_POST[submitdeletetic])) { foreach ($_POST["delete"] as $key => $id) foreach ($_POST["prov"] as $prov) { mysql_query("UPDATE tickets SET prov='$prov' WHERE id='".(int)$id."'") or die(mysql_error()); } } ?> Hi. The idea: I want to pull a client record and simply place all the row columns into editable form field text boxes. Once the user reviews and edits a submit button will update the record. What I have: Code: [Select] $Query01 = "SELECT * FROM `CustomerSignups` WHERE `Id` = '$_GET[Id]'"; $Result01 = mysql_query($Query01) or die("Error 01: " . mysql_error()); while ($get_info = mysql_fetch_row($Result01)) { foreach ($get_info as $field) echo "<p>$field</p>"; It displays as expected, a line for each field. How can I get this to pull the field names also and then I can use those as text box input fields...? Now i use a very complex normal for, how i can use a foreach? Ok, this may be just because I have been programming all day and my mind has gone blank (happens alot), but this is my PHP script: Code: [Select] <?php $query_distinct_item_types = mysql_query("SELECT DISTINCT name FROM item_types"); while($item_types = mysql_fetch_array($query_distinct_item_types)){ $distinct_item_types[] = $item_types['name']; } foreach($distinct_item_types as $item){ $query_item_total = mysql_query("SELECT item_type, SUM(price) WHERE item_type='$item' FROM costs GROUP BY item_type"); while($item_total = mysql_fetch_array($query_total_price)){ $item_totals[] = $item_total['SUM(price)']; } } $item_summery = $item_totals; ?> $item_summery which is = to $item_totals is returning null, any idea's? I have a table called "playlists", and a table called "musics". In the musics table, there is a column playlist_id which references the playlist that each music is contained.
I'm using api calls to display information on the site with JavaScript, so I need to return a JSON.
I need the json with the following structu
[
Playlists: [
{
Name: "etc",
musics: [
{
name: "teste.mp3" }, { name: "test2.mp3" } ] }, ... ] ] And this is my code: $query = $con->prepare("SELECT * FROM playlists WHERE user_id = :id"); Hi All, First time posting here. I've googled the problem, but can't seem to find a response that's the same. All I want to do is have a list of id numbers and for each id number in the array, submit a MySQL query to retrieve information relating to the id number. When I execute the code below however, I end up with only the last item in the array being printed in the echo statement. Any clues? Thanks, Code: [Select] // get array of ids $ids = getIDs($ids); // loop through input list foreach ($ids as &$id) { getVarDetails($id); } function getVarDetails($local) { $con = mysql_connect('localhost:3306', 'root', '********'); if (!$con) { die('Could not connect: ' . mysql_error()); } // set database as Ensembl mysql_select_db("Ensembl", $con); $result = mysql_query("SELECT * FROM variations WHERE name = '$local' LIMIT 1"); $row = mysql_fetch_array($result) while($row = mysql_fetch_array($result)) { echo $row['name'] . " " . $row['id']; echo "<br />"; } // close connection mysql_close($con); } This topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=355772.0 I'm not sure if the title explains it very well, but here is an image of it. I am trying to figure out how to access the option selected (equal, not equal, etc.), along with its input box, for each column (the checkboxes on the right) selected. The purpose of this is to allow a non-programming administrator user to create a custom query to access information. I can find out which checkboxes are selected no problem, but finding the accompanying drop-down option and input box is difficult for me. How do I do this? If you have a suggestion on how to change it, I'm very open. Thank you in advance! Code: [Select] if(!isset($_POST['submit'])) { echo " <form method='post'> <table> <tr> <td valign='top'>SELECT</td> <td valign='top'> <table>"; // LIST ALL COLUMNS IN A TABLE $result = mysql_query("SELECT * FROM table_name") or die(mysql_error()); $rowcount=mysql_num_rows($result); $y=mysql_num_fields($result); for ($x=0; $x<$y; $x++) { echo " <tr> <td> <input type='checkbox' name='fields[]' value='".mysql_field_name($result, $x)."'>".mysql_field_name($result, $x)." </td> </tr>"; } echo " </table> </td> <td valign='top'>FROM allocations</td> <td valign='top'>WHERE</td> <td> <table>"; // LIST ALL COLUMNS IN A TABLE $result = mysql_query("SELECT * FROM table_name") or die(mysql_error()); $rowcount=mysql_num_rows($result); $y=mysql_num_fields($result); for ($x=0; $x<$y; $x++) { echo " <tr> <td> <input type='checkbox' name='column[]' value='".mysql_field_name($result, $x)."'>".mysql_field_name($result, $x)." </td> <td> <select name='operator[]'> <option value='='>equals</option> <option value='<>'>does not equal</option> <option value='>'>greater than</option> <option value='<'>less than</option> <option value='>='>greater than or equal to</option> <option value='<='>less than or equal to</option> <option value='LIKE'>is like</option> </select> </td> <td><input type='text' name='criteria[]'></td> </tr>"; } echo " </table> </td> <td valign='top'><input type='submit' value='Process Query' name='submit' class='submit'></td> </tr> </table> </form>"; } else { echo "<b>Fields to edit:</b> "; foreach ($_POST['fields'] as $fields) { echo $fields,", "; } echo "<br><br>"; echo "<b>Columns to query:</b> "; foreach ($_POST['column'] as $columns) { echo $columns," HERE IS THE SPOT, "; } } Noob question. I've learned so much in the last couple of weeks that I've actually found two ways of doing the same thing! I was wondering which was the better method, if there is any difference. They are being used to print somewhere between 10 and 200 lines of text. Either: $categories_count= (count($categories[1])) -1; for ($u=0; $u < $categories_count; $u++) {echo "<li>".$categories[1][$u]."</li>";} Or: foreach ($categories[1] as $line => $cat) {echo "<li>".$cat."</li>";}; I am trying to develop a calendar. I have code to determine the number of days for each month. I want to cycle through each day and spit out code for each day. Something like the following: Code: [Select] <?php $month = "December"; $days = 31; foreach($days){ echo "<div id='day_block'> ".$days." </div>"; } ?> i think i need to use a counter but don't know how, any help would be awesome! I'm trying to figure out why its saying Warning: Invalid argument supplied for foreach() in /home/content/y/a/n/yankeefaninkc/html/defiant/efedmanager/forms/booking.php on line 17. I thought I did the foreach loop right so far. $eventid = $_GET['id']; $query = "SELECT CONCAT_WS(' ', eventnames.eventname, events.label) AS event, DATE_FORMAT(events.bookingdate, '%M %d, %Y') AS bookingdate, events.nummatches AS nummatches FROM events, eventnames WHERE events.event_id = eventnames.id AND events.id = '" . $eventid . "'"; $result = mysqli_query ( $dbc, $query ); // Run The Query foreach ($nummatches as $matchnum) { echo "Match # $matchnum"; echo "<select class=dropdown name=matchtype id=matchtype title=Match Type>"; echo "<option value=0>- Select -</option>"; $query = 'SELECT id, matchtypename FROM matchtypes'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['matchtypename']."</option>\r"; } } Hi can any one help please im still very new but hard trying The problem is that i only get 1 result back from the database i need it to loop any ideas please Code: [Select] $query = mysql_query("SELECT * FROM categorys, sub_categorys WHERE categorys.cat_id = sub_categorys.cat_id"); echo "<ul>"; $row[] = mysql_fetch_array($query); foreach($row as $category){ echo "<li>"; echo $category['category']; foreach($row as $sub_category){ if($category['cat_id'] == $sub_category["cat_id"]){ echo "<ul><li>".$sub_category["sub_category"]."</li></ul>"; } } echo "</li>"; } echo "</ul>"; today i programmed my own weight calculator. one thing i am having a problem is with trying to make it so if a weight is over a certain number, then the shipping price will increase by X. shipping prices are charged in 20000 gram blocks, so if I have something that is 22000 grams then that will be two blocks. what i need to do is something like (this is a big guess) Quote $row3 = 50; $weighttotal = 22000; if ($weighttotal > 20000) { foreach (20000) { $row3 += $row3;} } } } can it be done on php?? Hi All, I essentially am trying to figure out how to print out all of the zip codes that are associated with a search that I am doing, but not list the same zip code more than once. My current foreach statement is as follows and prints out the zip code for each property that is associated with the search: <ul> <?php foreach($properties as $property) { ?> <li><?=$property->$zipcode?></li> <?php } ?> </ul> How would I modify this to print out 1 occurrence of each zip code that is in the search, even if, for example 20 properties have the same zip code? Thanks in advance! P.S. - Tried using an array to work with it but pretty sure my logic was incorrect when putting it together and couldn't get past the errors. Anyways, thanks in advance for the help! Hi i am trying to pass values from a cart to a database using foreach. This is my code: Code: [Select] $columns = array('order_id', 'order_item_id', 'order_product_name', 'order_product_dimensions', 'order_product_options', 'order_product_quantity', 'order_product_price', 'order_product_subtotal', 'order_product_vat', 'order_product_delivery','order_product_total','order_product_sku','order_product_image_name','order_product_image_type','order_product_image_path','order_product_image_size','order_product_artwork_link','order_product_artwork_name','order_product_artwork_type','order_product_artwork_path','order_product_artwork_size','order_firstname','order_lastname','order_companyname','order_email','order_tel','order_billing_address','order_billing_address2','order_billing_town','order_billing_county','order_billing_postcode','order_shipping_address','order_shipping_address2','order_shipping_town','order_shipping_county','order_shipping_postcode','order_status','order_username'); $data = array_fill_keys($columns, 'NULL'); foreach($data as $key => $value) { $data[$key] = empty($_POST[$key]) ? 'NULL' : "'".mysql_escape_string($_POST[$key])."'"; $query = "INSERT INTO orders (id, order_created_at, ".implode(", ",$columns).") VALUES (null, NOW(), ".implode(",",$data).')'; } Problem is posting 2 or more products into the database. How do i split the values so it enters each product into the database? public function update($data, $table, $where) { foreach ($data as $column => $value) { $sql = "UPDATE $table SET $column = $value WHERE $where"; print "table: ".$table." column: ".$column." whe ".$where; mysql_query($sql) or die(mysql_error()); } return true; } $data: $data = array( "username" => "Jack", "email" => "jack.gmail@gmail.com" ); $db->update($data, "users", 'id=1'); Working on this code that updates a column from a class. Everything is fine except for one issue. As of right now $column is set to "Jack" which outputs an error, instead of what it should be as "username". I'm sure it's something really simple, so any assistance is appreciated. Any ideas? Problem area is listed in red. Hi guys, Having a bit of trouble getting this to work. I should say before I start that im a rookie at PHP. Basically this is the code I have {counter start=0 print=false name=competcount} {foreach item=compet from=$person.competition} <img src="./bargraph/bar.php?value={$person.lineup[$compet.id].titular}&max={$club.matchsplayed[$compet.id].nummatchs}&info" /> The problem lies with the $club array not being defined Code: [Select] $club.matchsplayed[$competition.id].nummatchs How do I set up multiple arrays with foreach? Am I even in the right ball park with this? I appear to be having a simple simon day! my foreach is only displaying the last result in the table as opposed to each row $num_rows = mysql_num_rows($query); echo "There are $num_rows records.<br>"; while($row = mysql_fetch_row($query)) foreach ($row as $field) { echo '<div class="results">'; echo $field; echo '<br></div>'; } And the source Code: [Select] <link href="../styles/clientbox.css" rel="stylesheet" type="text/css"> <body><br> <h3>My Services</h3> <div class="text"> You currently have the following services with us: </div> There are 2 records.<br><div class="results">test1<br></div> </body> </html> My table has 2 rows which the 1st one has a package of test and the second a package of test1 Can anyone help? Thanks |