PHP - Php/mysql Foreach To Increment A Value
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); ?> Similar Tutorials
hi, i’m currently facing a new problem (i managed to use array_unique function successfully but i face this problem)with my php loop. i couldn’t seem to increment in my foreach loop to get the value of an array. $update_id1=Array ( [0] => 398 [1] => 397 [2] => 393 [3] => 391 [8] => ); //$i=0; foreach ($update_id1 as $i => $v) { $ex= explode(",", $v); $unique=array_unique($ex); //f$ketch username from update table in db and inject it to the feed query. $imp_id= implode(',', $ids); //$id1=$ids[$i]; // $x=0; // for($x=0;$x<count(unique);$x++){ echo 'ids:- '.$i; print_r($unique[$i]); echo '<br>'; //} $totalUpdates=$project->totalUpdates($ids[$i],$_SESSION['uname'] ,$unique[$i],$load); //$i++; } i tried every method nothing seems to work can anyone help me in this regard please. Edited December 25, 2019 by narutofanHi Guys Ever had the feeling your being a spoon and can't see the wood for the trees? Well, that's how I feel today. All I am trying to to is implement a variable in a "foreach" loop that increments by one through each iteration of the loop. I know how to do it in a "for" loop but can't for the life of me get it to work here. Here is the code: foreach ($cart as $prodcode => $qty) { $item = get_product_details($prodcode); echo '<input type="hidden" name="item_name_'.[b]$needavariablehere[/b].'" value="'.$item['description'].$_SESSION['finish'][$prodcode].$_SESSION['handles'][$prodcode].'" />' . "\n"; } Where I have highlighted $needavariablehere is where I want a number to appear i.e. if there is one item available and the foreach loop iterates once I want the number 1 here. If there are two items and the foreach loop iterates twice I want the output to have number 1 in the first line and number 2 the second time around and so on. How many times the foreach loop iterates is based on the $cart array which contains items in a shopping cart. Thanks for any help you can give guys. hi .. i am working on chat system ..there are two types of user one are register and other are guest and i have to add guest user..in to database as temporary so they can chat with each other the problem i am facing is with there names i want name like this (Guest1,Guest2,Guest3,Guest4,...so on..)..i am trying but it is not working on live server .. i have tested it on my local server using xampp server.. it worked but not on live server... here is the code which i am using if(isset($_SESSION['Guest'])) { $_SESSION['Guest']=$_SESSION['Guest']+1; } else { $_SESSION['Guest']=1; and one more thing how i can delete Guest users who are not online.. Hi, I have come up with the following code, I need it to get the details of several scattered products and echo the results, the trick is I don't want it to echo the results one after the other... I want to have the products scattered between unique text on the page but don't want to run the query several times for performance reasons. E.g.- PAGE to look like this: $Product_1 unique text/images $Product_2 $Product_3 unique text/images $Product_4 Current Code: Code: [Select] <? $result = mysql_query("SELECT * FROM products where Product_ID IN (475, 465, 234, 567, 845)"); while($row = mysql_fetch_array($result)) { $x = "1"; while ($x<=3) { echo $x; $Product = "Product_"; $Product = $Product.$x; echo $Product; $Product = $row['Product_ID']; echo $Product; $x++; echo $x; } } At the moment it returns the following results: Quote 1 Product_1 465 2 2 Product_2 465 3 3 Product_3 465 4 1 Product_1 475 2 2 Product_2 475 3 3 Product_3 475 4 A few problems... In Blue... it duplicates for product 465 In Red... It repeats again for 475 Also.... it starts with 465, but I want it to go in order as how it appears - $result = mysql_query("SELECT * FROM products where Product_ID IN (475, 465, 234, 567, 845)"); so should start with 475 I want to get the following result: Quote 1 Product_1 475 2 2 Product_2 465 3 3 Product_3 234 4 4 Product_4 567 4 (and so on.....) If anyone could provide me assistance with my troubled 'while loop' statement that would be much appreciated! I'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 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(); ?> 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...? 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? Now i use a very complex normal for, how i can use a foreach? 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 believe it's called increment. Either way, I cannot figure out how to simply count up beginning at 1 (in red in the div below) ... function wp_rss( $url, $num_items = -1 ) { if ( $rss = fetch_rss( $url ) ) { echo '<div id="charts">'; if ( $num_items !== -1 ) { $rss->items = array_slice( $rss->items, 0, $num_items ); } foreach ( (array) $rss->items as $item ) { printf( '<div id="chart_lt">1</div><div id="chart_rt">%3$s</div>', esc_url( $item['link'] ), esc_attr( strip_tags( $item['description'] ) ), htmlentities( $item['title'] ) ); } echo '</div>'; } else { _e( 'An error has occurred, which probably means the feed is down. Try again later.' ); } } Code: [Select] $db->query('UPDATE users set actions=actions+1|'.time().' where id = '.$pun_user['id'].''); im trying to do set actions=actions+1, then put a | atfter +1ing it, then add my time stamp to it so I can explode it later. so it will look like this 2|unixtimestamphere how would i achieve this? or do I need to make another seperate row? seems dumb must be v easy to answer for many here but i dont know how to do it how can i use for loop to print values between any range but with increment of 0.5 0 0.5 1 1.5 2 2.5 3 ........till n I have tables in my MySQL database called "games", "wins" and "losses". I'm attempting to write SQL queries that will increment or decrement a value depending on what link is clicked from the main page. My SQL queries are as follows: <?php require_once('config.php'); if ( !isset($_SESSION['user']) ) { include('login.php'); exit; } $sql = 'select * from `teams` WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; $res = mysql_query($sql); //if ( mysql_num_rows($res) == 0 ) { include('index.php'); exit; } $row_team = mysql_fetch_array($res); if ( isset($_GET['addgame']) ) { $sql = 'UPDATE `teams` SET `games` = `games` + 1 WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; mysql_query($sql); } if ( isset($_GET['subtractgame']) ) { $sql = 'UPDATE `teams` SET `games` = `games` - 1 WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; mysql_query($sql); } if ( isset($_GET['addwin']) ) { $sql = 'UPDATE `teams` SET `wins` = `wins` + 1 WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; mysql_query($sql); } if ( isset($_GET['subtractwin']) ) { $sql = 'UPDATE `teams` SET `wins` = `wins` - 1 WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; mysql_query($sql); } if ( isset($_GET['addloss']) ) { $sql = 'UPDATE `teams` SET `losses` = `losses` + 1 WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; mysql_query($sql); } if ( isset($_GET['subtractloss']) ) { $sql = 'UPDATE `teams` SET `losses` = `losses` - 1 WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; mysql_query($sql); } $sql = 'select * from `teams` WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; $res = mysql_query($sql); $row_team = mysql_fetch_array($res); ?> For some reason, I can increment the amount of games, wins or losses as many times as I want.. it'll be updated in the database and the changes will be reflected on the page. However, when I go to subtract a game, win or loss, it seems to leave null values as if there are no games, wins or losses at all. For example, say the site outputs the Yankees have 10 wins and 2 losses. When "[Add Win]" is clicked, the win total will increase to 11 and such changes will be displayed on the site. But, when "[Deduct Win]" is clicked, it seems to cancel out every value for the number of games, wins and losses and just outputs nothing.. Is there a reason for this? My addition is working fine, it's the subtraction that's messed up.. but it should work based on what I see. Thanks. Hey, In my table, I have 773 rows like this: 10800 ... 772 ... 771 ... 770 ... 769 ... etc ... When I insert a new row, it will have an ID of 10801 and not 773. I delete row 10800 and I want to insert a new row that has an ID of 773. Is there a code I can use also so that it creates the IDs in order? 1, 2, 3 etc no missing numbers. Thanks. I'm wanting to increment usernames in ONLY the lowercase a-z for example if a user enters "abc" it will automatically be given "abc1" and the next user if entering the same username will automatically be given "abc2", the next "abc3" and so on. The base login and register script I'm using can be found on http://evolt.org/node/60265/ The database.php and register.php pages are below, but excluding the amendments I am seeking. I have created a MySQL database with 2 tables, 1 table named 'Users' with 3 columns named (1) 'userid' primary key, auto increment, (2) 'username' (3) 'password'. The other table is named 'UserCount' with 2 columns named (1) 'username' (2) 'count'. Can someone provide the PHP coding for the following process? When a new user registers a new username firstly PHP to check the characters are in lowercase a-z only and no other characters, and reject if they do not match, then for PHP to check to see if that username exists in the 'UserCount' table. If it doesn't exist, PHP to insert the new username into the 'username' column and also set the value of the 'count' column to 1. If the username does exist, PHP to add that username to the 'username' column and increment the value of the 'count' column by 1. Then in the 'Users' table PHP to insert a record with 'Users.username = UserCount.username + count' and PHP to inform the new user of their complete username including the integer that has been added to their first entered username. It would also help if I could be provided a link to a website on where I can better understand how to collate coding of this kind, coz I have tried to formulate this coding but as I'm playing around in the dark I have no idea if it is the right process in particular considering security factors. database.php Code: [Select] <?php /** * Connect to the mysql database. */ $conn = mysql_connect("localhost", "your_username", "your_password") or die(mysql_error()); mysql_select_db('your_database', $conn) or die(mysql_error()); ?> register.php Code: [Select] <?php session_start(); include("database.php"); /** * Returns true if the username has been taken * by another user, false otherwise. */ function usernameTaken($username){ global $conn; if(!get_magic_quotes_gpc()){ $username = addslashes($username); } $q = "select username from Users where username = '$username'"; $result = mysql_query($q,$conn); return (mysql_numrows($result) > 0); } /** * Inserts the given (username, password) pair * into the database. Returns true on success, * false otherwise. */ function addNewUser($username, $password){ global $conn; $q = "INSERT INTO Users VALUES ('$username', '$password')"; return mysql_query($q,$conn); } /** * Displays the appropriate message to the user * after the registration attempt. It displays a * success or failure status depending on a * session variable set during registration. */ function displayStatus(){ $uname = $_SESSION['reguname']; if($_SESSION['regresult']){ ?> <h1>Registered!</h1> <p>Thank you <b><?php echo $uname; ?></b>, your information has been added to the database, you may now <a href="main.php" title="Login">log in</a>.</p> <?php } else{ ?> <h1>Registration Failed</h1> <p>We're sorry, but an error has occurred and your registration for the username <b><?php echo $uname; ?></b>, could not be completed.<br> Please try again at a later time.</p> <?php } unset($_SESSION['reguname']); unset($_SESSION['registered']); unset($_SESSION['regresult']); } if(isset($_SESSION['registered'])){ /** * This is the page that will be displayed after the * registration has been attempted. */ ?> <html> <title>Registration Page</title> <body> <?php displayStatus(); ?> </body> </html> <?php return; } /** * Determines whether or not to show to sign-up form * based on whether the form has been submitted, if it * has, check the database for consistency and create * the new account. */ if(isset($_POST['subjoin'])){ /* Make sure all fields were entered */ if(!$_POST['user'] || !$_POST['pass']){ die('You didn\'t fill in a required field.'); } /* Spruce up username, check length */ $_POST['user'] = trim($_POST['user']); if(strlen($_POST['user']) > 30){ die("Sorry, the username is longer than 30 characters, please shorten it."); } /* Check if username is already in use */ if(usernameTaken($_POST['user'])){ $use = $_POST['user']; die("Sorry, the username: <strong>$use</strong> is already taken, please pick another one."); } /* Add the new account to the database */ $md5pass = md5($_POST['pass']); $_SESSION['reguname'] = $_POST['user']; $_SESSION['regresult'] = addNewUser($_POST['user'], $md5pass); $_SESSION['registered'] = true; echo "<meta http-equiv=\"Refresh\" content=\"0;url=$HTTP_SERVER_VARS[PHP_SELF]\">"; return; } else{ /** * This is the page with the sign-up form, the names * of the input fields are important and should not * be changed. */ ?> <html> <title>Registration Page</title> <body> <h1>Register</h1> <form action="<?php echo $HTTP_SERVER_VARS['PHP_SELF']; ?>" method="post"> <table align="left" border="0" cellspacing="0" cellpadding="3"> <tr><td>Username:</td><td><input type="text" name="user" maxlength="30"></td></tr> <tr><td>Password:</td><td><input type="password" name="pass" maxlength="30"></td></tr> <tr><td colspan="2" align="right"><input type="submit" name="subjoin" value="Join!"></td></tr> </table> </form> </body> </html> <?php } ?> Hi there! Hoping someone can help me with this very specific issue I have a string that looks like this: Code: [Select] var1 var2 X var3 var4 X var5 I need to find the highest number next to var (in this case 5), and to replace X with the following number (in this case var6). So after the replace, the string would look like this: Code: [Select] var1 var2 var6 (this x has been replaced for var6) var3 var4 var7 (this x has been replaced for var7) var5 Any ideas!? Thanks! |