PHP - Count Distinct Multiple Mysql Rows Query
I insert data in mysql table row using multiple method : 1#2#3 . 1 is ID of country, 2 is Id of state, 3 is ID of town . now i have this table for real estate listings. for each list(home) i have country/state/town (1#2#3). in country table i have list of country - in country table i have list of state - in country table i have list of town. i need to The number of houses in country / state / town . my mean is :
Code: [Select] USA [ 13 ] <!-- This Is equal of alabama+alaska+arizona --> ----Alabama [8] <!-- This Is equal of Adamsville+Addison+Akron --> -------Adamsville [2] -------Addison[5] -------Akron[1] ......(list of other City) ----Alaska [ 3 ] -------Avondale[3] ......(list of other City) ----Arizona [ 2 ] -------College[2] ......(list of other City) Lisintg Table : Code: [Select] ID -- NAME -- LOCATION -- DATEJOIN -- ACTIVE 1 -- TEST -- 1#2#3 -- 20110101 -- 1 2 -- TEST1 -- 1#2#3 -- 20110101 -- 1 3 -- TEST2 -- 1#3#5 -- 20110101 -- 1 4 -- TEST3 -- 1#7#6 -- 20110101 -- 1 Country Table : Code: [Select] id -- name 1 -- USA stats Table : Code: [Select] id -- countryid -- name 1 -- 1 -- albama 2 -- 1 -- alaska 3 -- 1 -- akron town Table : Code: [Select] id -- countryid -- statsid -- name 1 -- 1 -- 1 -- adamsville 2 -- 1 -- 1 -- addison 3 -- 1 -- 1 -- akron Thanks For Any Help. Similar TutorialsHello folks,
In trying to improve the user experience for my first WebApp I have decided to create two new tables - one a master file to contain a list of all stores, and the second a master file to contain a list of all products that are normally purchased - and I would like to use the values from these two tables as lookup values in dropdown listboxes, to which the user can also add new entries.
As it turns out, I'm stuck on the very first objective i.e. to lookup/pull-in the distinct values from the master tables.
The problem I'm having is that the query seems to return no rows at all...in spite of the fact that there a records in the table, and the exact same query (when run within the MySQL environment) returns all the rows correctly.
Is there something wrong with my code, or how can I debug to see whether or not the query is being executed?
Objective # 2, which is to allow new values to be entered into the dropdown listbox, and then inserted into the respective table is certainly waaay beyond my beginner skills, and I'll most certainly need to some help with that as well..so if I can get some code/directions in that regard it will be most appreciated.
Thank you.
<?php $sql = "SELECT DISTINCT store_name FROM store_master ORDER BY store_name ASC"; $statement = $conn->prepare($sql); $statement->execute(); $count = $statement->rowCount(); echo $count; // fetch ALL results pertaining to the query $result = $statement->fetchAll(); echo "<select name=\"store_name\">"; echo '<option value="">Please select...</option>'; foreach($result as $row) { echo "<option value='" . $row['store_name'] . "'></option>"; } echo "</select>"; ?> Given the below 3 database tables I am trying to construct a SQL query that will give me the following result: customer_favourites.cust_id customer_favourites.prod_id OR product.id product.code product.product_name product.hidden product_ section.section_id (MUST BE ONLY THE ROW WITH THE LOWEST SECTION ID, I.E. ROW ID #44108) product_ section.catpage (MUST BE ONLY THE ROW WITH THE LOWEST SECTION ID, I.E. ROW ID #44108) product_ section.relative_order (MUST BE ONLY THE ROW WITH THE LOWEST SECTION ID, I.E. ROW ID #44108) I currently have.... SELECT customer_favourites.cust_id, customer_favourites.prod_id, product.code, product.product_name, product.hidden, product_section.section_id, product_section.relative_order, product_section.catpage FROM customer _favourites INNER JOIN product ON customer_favourites.prod_id = product.id INNER JOIN product_section ON product_section.product_code = product.code WHERE `cust_id` = '17' AND `hidden` = '0' GROUP BY `code` ORDER BY `section_id` ASC, `relative_order` ASC, `catpage` ASC LIMIT 0,30 This gives me what I want but only sometimes, at other times it randomly selects any row from the product_section table. I was hoping that by having the row I want as the last row (most recent added) in the product_section table then it would select that row by default but it is not consistent. Somehow, I need to be able to specify which row to return in the product_section table, it needs to be the row with the lowest section_id value or it should by the last row (most recent). Pulling my hair out so any help is gratefully received. customer_favourites id cust_id prod_id 70 4 469 product id code product_name hidden 469 ABC123 My Product 0 product_section id section_id catpage product_code relative_order recommended 44105 19 232 ABC123 260 1 44106 3 125 ABC123 87 1 44107 2 98 ABC123 128 1 44108 1 156 ABC123 58 0 Hi I'm not at all good at PHP and haven't really played with it for some years, so bare with me if code examples are old I'm looking for a simple solution to count rows (MySQL), without using multiple queries. The below code is quite simple, counting rows where 'Department' is 'Sales': $sql ="SELECT * FROM DB WHERE Department ='Sales'"; $result=mysqli_query($con,$sql); $rowcount=mysqli_num_rows($result); But what If I need to count the rows for the different departments?: $sql ="SELECT * FROM DB WHERE Department ='Sales'"; $result=mysqli_query($con,$sql); $rowcount=mysqli_num_rows($result); $sql ="SELECT * FROM DB WHERE Department ='Support'"; $result=mysqli_query($con,$sql); $rowcount=mysqli_num_rows($result); $sql ="SELECT * FROM DB WHERE Department ='Online'"; $result=mysqli_query($con,$sql); $rowcount=mysqli_num_rows($result); There must be a better / simpler way to this with a single query? Hope for someone to show me the light
PS. Once this is resolved, I'll probably need further help, to accomplish my final result. Hi Everyone, I am working on implementing a blog comment system using the query below to display comments. My question is what is the best way to do a row count for the id column with this query or do I need to do a second db query to accomplish this? The purpose of this is to echo out the number of comments for that post, before displaying them. Any help is appreciated. Thanks in advance, kaiman <?php // get url variables $post_id = mysql_real_escape_string($_GET['id']); include ("../../scripts/includes/nl2p.inc.php"); // connects to server and selects database include ("../../scripts/includes/dbconnect.inc.php"); // table name $tbl_name3="blog_comments"; // select info from comments database $result3 = mysql_query ("SELECT count(*) FROM $table_name3 WHERE id='$post_id' ORDER BY id DESC LIMIT 1") or trigger_error("A mysql error has occurred!"); if (mysql_num_rows($result3) > 0 ) { while($row = mysql_fetch_array($result3)) { extract($row); // display number of comments // display date $row_date = strtotime($row['date']); putenv("TZ=America/Denver"); echo "<p class=\post\">On ".date('F, jS, Y', $row_date)." "; // display commenter name if($row['url'] == "") { echo $row['name']." wrote:</p>\n"; } else { echo "<a href=\"".$row['url']."\" target=\"_blank\">".$row['name']."</a> wrote:</p>\n"; } // display content $comments = $row['comment']; echo nl2p($comments); } } else { echo "<p class=\"large_spacer\">No Comments</p>"; } ?> It's late and I'm not thinking straight. I'm posting this question. Hopefully I get a reply in the morning. I have two tables. TABLE 1 - PRODUCTS TABLE 2 - LIKES I am a User who has posted these products. I want to find out ALL the Likes I have received for all my products. Here is my code. $find_products = $db->prepare("SELECT product_id FROM products WHERE user_id = :user_id"); $find_products->bindParam(':user_id', $my_user_id); $find_products->execute(); $result_products = $find_products->fetchAll(PDO::FETCH_ASSOC); if(count($result_products) > 0) { foreach($result_products as $row) { $product_id = $row['product_id']; $find_likes = $db->prepare("SELECT like_id FROM product_likes WHERE product_id = :product_id"); $find_likes->bindParam(':product_id', $product_id); $find_likes->execute(); $result_likes = $find_likes->fetchAll(PDO::FETCH_ASSOC); if(count($result_likes) > 0) { $get_likes = 0; foreach($result_likes as $row) { $get_likes++; } } } } The issue with the above code is that It only shows the Likes if I echo inside the foreach loop. And it'll show combined Likes from each of my products. But I want to actually combine ALL the Likes from ALL the products and be able show them as a single number, outside of the foreach loop. How do I do that? Edited August 17, 2019 by imgroootmonth a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 a17 a18 a19 a20 a21 a22 a23 a24 a25 a26 a27 a28 a29 a30 a31 1 puudu 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 [20] [21] 22 23 24 25 [26] 27 28 29 30 31 2 puudu 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 3 puudu 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 4 puudu 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 5 puudu 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 6 puudu 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 7 puudu 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 8 puudu 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 9 puudu 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 10 puudu 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 11 puudu 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 12 puudu 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ; i need help .. with calculating how many days are between example: january = 1 ; day =23 to feb =2; day 23 in php ... how can i do that This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=351561.0 The following works, but I don't want to have to write 50 query statements for 50 states. How can I just write one query (using a variable I presume) and then echo the variable count each time for each state? I'm just trying to list the total number of rows for each state, that exist in the db. <? $result = mysql_query("SELECT * FROM mytable WHERE source = 'alabama'") or die(mysql_error()); $num_rows = mysql_num_rows($result); ?> href="/state/alabama/">alabama</a> (<?php echo("$num_rows");?>) <br> <? $result = mysql_query("SELECT * FROM mytable WHERE source = 'alaska'") or die(mysql_error()); $num_rows = mysql_num_rows($result); ?> href="/state/alaska/">alaska</a> (<?php echo("$num_rows");?>) <br> The above would give output such as: alabama (122) alaska (212) Ok I'm trying to insert multiple rows by using a while loop but having problems. At the same time, need to open a new mysql connection while running the insert query, close it then open the previous mysql connection. I managed to insert multiple queries before using a loop, but for this time, the loop does not work? I think it is because I am opening another connection... yh that would make sense actually? Here is the code: $users = safe_query("SELECT * FROM ".PREFIX."user"); while($dp=mysql_fetch_array($users)) { $username = $dp['username']; $nickname = $dp['nickname']; $pwd1 = $dp['password']; $mail = $dp['email']; $ip_add = $dp['ip']; $wsID = $dp['userID']; $registerdate = $dp['registerdate']; $birthday = $dp['birthday']; $avatar = $dp['avatar']; $icq = $dp['icq']; $hp = $dp['homepage']; echo $username." = 1 username only? :("; // ----- Forum Bridge user insert ----- $result = safe_query("SELECT * FROM `".PREFIX."forum`"); $ds=mysql_fetch_array($result); $forum_prefix = $ds['prefix']; define(PREFIX_FORUM, $forum_prefix); define(FORUMREG_DEBUG, 0); $con = mysql_connect($ds['host'], $ds['user'], $ds['password']) or system_error('ERROR: Can not connect to MySQL-Server'); $condb = mysql_select_db($ds['db'], $con) or system_error('ERROR: Can not connect to database "'.$ds['db'].'"'); include('../_phpbb_func.php'); $phpbbpass = phpbb_hash($pwd1); $phpbbmailhash = phpbb_email_hash($mail); $phpbbsalt = unique_id(); safe_query("INSERT INTO `".PREFIX_FORUM."users` (`username`, `username_clean`, `user_password`, `user_pass_convert`, `user_email`, `user_email_hash`, `group_id`, `user_type`, `user_regdate`, `user_passchg`, `user_lastvisit`, `user_lastmark`, `user_new`, `user_options`, `user_form_salt`, `user_ip`, `wsID`, `user_birthday`, `user_avatar`, `user_icq`, `user_website`) VALUES ('$username', '$username', '$phpbbpass', '0', '$mail', '$phpbbmailhash', '2', '0', '$registerdate', '$registerdate', '$registerdate', '$registerdate', '1', '230271', '$phpbbsalt', '$ip_add', '$wsID', '$birthday', '$avatar', '$icq', '$hp')"); if (FORUMREG_DEBUG == '1') { echo "<p><b>-- DEBUG -- : User added: ".mysql_affected_rows($con)."<br />"; echo "<br />-- DEBUG -- : Query used: ".end($_mysql_querys)."</b></p><br />"; $result = safe_query("SELECT user_id from ".PREFIX_FORUM."users WHERE username = '$username'"); $phpbbid = mysql_fetch_row($result); safe_query("INSERT INTO `".PREFIX_FORUM."user_group` (`group_id`, `user_id`, `group_leader`, `user_pending`) VALUES ('2', '$phpbbid[0]', '0', '0')"); safe_query("INSERT INTO `".PREFIX_FORUM."user_group` (`group_id`, `user_id`, `group_leader`, `user_pending`) VALUES ('7', '$phpbbid[0]', '0', '0')"); mysql_close($con); } include('../_mysql.php'); mysql_connect($host, $user, $pwd) or system_error('ERROR: Can not connect to MySQL-Server'); mysql_select_db($db) or system_error('ERROR: Can not connect to database "'.$db.'"'); } So I need to be able to insert these rows using the while loop.. how can I do this? I really appreciate any help. This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=330871.0 i have 12 distinct albums displaying 8 per page $number rows echo's out to be 1 so to me says my query is wrong how to count only distinct albums Code: [Select] $sql = "SELECT COUNT(DISTINCT album) FROM belsgallery GROUP BY album"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); $r = mysql_fetch_row($result); $numrows = $r['0']; echo $numrows; // RETURNS 1 $rowsperpage = 8; $totalpages = ceil($numrows / $rowsperpage); Ok so I am pretty good with mysql and performing queries to get the data that I need. However, I have a question for any of you gurus out there that may be able to help me with an issue that I always run into with certain types of queries. Say I have 2 tables like this: Galleries id name 1 My Photos Gallery Photos id gallery_id photo 1 1 photo1.jpg 2 1 photo2.jpg 3 1 photo3.jpg Now usually when I pull this info from the database I have to do 2 separate queries in order to get the data and then link them so I would do something like. <?php //make the gallery query $query = "SELECT * FROM galleries"; $results = mysql_query($query); //setup an array for the galleries data $gallery_data = array(); //loop through the galleries for($i=0;$i<mysql_num_rows($results);$i++){ //add the gallery info to the gallery data array $gallery_data[$i] = mysql_fetch_array($results); //make the photos query with the gallery id $photo_query = "SELECT * FROM gallery_photos WHERE gallery_id='".mysql_real_escape_string($gallery_data[$i]['id'])."'"; $photo_results = mysql_query($photo_query); //setup the photos array $photo_data = array(); //put the photos in the array for($n=0;$n<mysql_num_rows($photo_results);$n++){ $photo_data[$n] = mysql_fetch_array($photo_results); } //add the photos to the gallery array $gallery_data[$i]['photos'] = $photo_data; } //now to display it is like this if(is_array($gallery_data)){ foreach($gallery_data as $gallery){ echo $gallery['name']; //show the photos if(is_array($gallery['photos'])){ foreach($gallery['photos'] as $photo){ echo $photo['photo']; } } } } ?> So my question is there a way to get all of this data at one time. I know how to do multiple queries in one and to do joins but they can only return one row as far as I know of. The only other way that I know how to do this is by ordering them by name and selecting them directly from the photos table and then just getting the gallery name like this: SELECT *,(SELECT name FROM galleries WHERE id=gallery_photos.id) AS gallery_name FROM gallery_photos ORDER BY gallery_id Then I could just do one loop and see if the name has changed and if so to output the new name. But I would like to know if there is a way to get a second set of results as an array from a query so I could just select the galleries and photos all in one query. Any help is appreciated. Hey, I was wondering if there is a way to pull multiple rows at once using a list of unique identifiers. For example, I want to pull the rows with the IDs of 4,13,91 and 252 I know the WHERE part of this query is incorrect, but I'm putting it to hopefully help you guys understand what I'm looking for. $result = mysql_query("SELECT * FROM $table WHERE id='4' OR '13' OR '91' OR '252'"); while($row = mysql_fetch_array($result)) { echo($row['name']); } Or is the best way simply to do it one query at a time without a while statement? There could be as many as a few dozen records being pulled per page. Hello there, i'm not sure if this goes to mysql, or this section, but since it's PHP based, i would say here. So, here's the thing, i have full set up table that reads from mysql database and display it as table. Everything is working just fine, even "order" buttons that i made, now i would like to have below the table some counts, for example: My table name "canonkickoff" has column named "Prevoz" which contain only Yes and No answers, i would like to see below the table how much "Yes" answers are inside the column. Also i have other column called "VelicinaMajice", which contain 6 different answers ( XS, S, M, L, XL, XXL ), i would like to see (again, below the table) how much of every has been answered. Like: There a XS = 6 S = 1 M = 2 L = 3 And 32 answered with Yes. Could anyone help me out? Here's the full php table: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>CanonKickOff 2012 Tabela.</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link rel="stylesheet" href="table.css" type="text/css"> </head> <body style="margin: 0 0 0 0;"> <? include("passwd.php"); @$start = $_GET["start"]; if($start =='') $start =0; include("lib.php"); $link = mysql_connect($host,$username,$password); if (!$link) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db($db, $link); if (!$db_selected) { die ("Can't use $db : " . mysql_error()); } //total number of records in the table $orderBy = array('Kompanija', 'id', 'ImePrezime', 'Email', 'Prevoz', 'VelicinaMajice', 'SlazemSe'); $order = 'id'; if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) { $order = $_GET['orderBy']; } $res = mysql_query("SELECT * from `$table` ORDER BY '.$order"); $res2 = mysql_query("SELECT * from `$table` "); @$rows = mysql_num_rows ($res2); $result = mysql_query("SELECT * from `$table` ORDER BY $order limit $start,40"); if (!$result) { die('Invalid query: ' . mysql_error()); } echo 'Sortiraj Po: <br>'; echo '<a href="?orderBy=id">ID:</a> '; echo '<a href="?orderBy=ImePrezime">Ime i Prezime:</a> '; echo '<a href="?orderBy=Kompanija">Kompanija:</a> '; echo '<a href="?orderBy=email">Email adresi:</a> '; echo '<a href="?orderBy=Prevoz">Prevoz:</a> '; echo '<a href="?orderBy=VelicinaMajice">Velicina majice:</a> '; echo '<a href="?orderBy=SlazemSe">Slazu se:</a> '; echo "<p align=center class = 'menu'> Ocitana tabela: $table </p>"; $cols = mysql_num_fields($result); $records = mysql_num_rows ($result); echo "<table align='center' width='1200' >"; echo "<tr bgcolor='BBCCDD' class='menu'>"; for ($i = 0; $i < $cols;$i++) { echo "<td align='center'>".mysql_field_name($result,$i)."</td>"; } echo "</tr>"; while ($row = mysql_fetch_array($result, MYSQL_NUM)) { echo "<tr bgcolor='F6F6F6' class='normal'>"; foreach ($row as $value) { echo "<td align='center'>".$value ."</td>"; } echo "</tr>"; } $end = $start + $records; echo "<tr align = 'center' bgcolor = 'BBCCDD' class='menu'><td colspan=$cols> $start do $end od ukupno: $rows </td></tr>"; echo "<tr align = 'center' class='mylink'><td colspan=$cols> "; if($start != 0) { $prev = $start - 40; echo "<a href='tabela.php?start=$prev'> Prethodna </a> "; } if($start<$rows-10) { $next = $start + 40; echo "<a href = 'tabela.php?start=$next'>Sledeca</a> "; } echo "</td></tr>"; echo "</table>"; ?> </body> </html> This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=312690.0 I'm trying to write a php page that displays data from a JOIN query for a specific ID table view brandinfo ID, brand, discounttype 1, antioni, no discount brandproducts brandID, producttype, price 1, Tshirt, 20.00 1, Pants, 30.00 1, Shoe, 40.00 the returned result is 1 antioni, no discount, Tshirt, 20.00, 2 antioni, no discount, Pants, 30.00 3 antioni, no discount, Shoe 40.00 The way I want the page to be displayed is ------------------ Antioni (at the top) Table 1. Tshirt 20.00 2. Pants 30.00 3. Shoe 40.00 no discount (at the bottom) ---------------------------- How should I construct the PHP page from the result since they're retrieved as rows? Hello everyone, Once again i need your help this time i want to know that, if I inserting multiple row by single insert query with the help of foreach (loop) then how to insert another cell value according to the name wise so that's way i send my hole code to you. <?php //include configuration file for connection include_once('config.php'); $sql = "select * from CLASS_STUDENT ORDER BY STUDENT_NAME ASC "; $result=mysql_query($sql); $count=mysql_num_rows($result); ?> <form name="form1" method="post" action=""> <table style="text-align: left; padding: 5px;" cellpadding="0px" cellspacing="0px"> <tbody> <tr> <th style="text-align: center; padding: 5px; border: 1px #000000 solid;">Student Name</th> <th style="text-align: center; padding: 5px; border: 1px #000000 solid;">Student Class</th> <th style="text-align: center; padding: 5px; border: 1px #000000 solid;">Student Section</th> <th style="text-align: center; padding: 5px; border: 1px #000000 solid;">Current Date</th> <th style="text-align: center; padding: 5px; border: 1px #000000 solid;">Student Present</th> <th style="text-align: center; padding: 5px; border: 1px #000000 solid;">Student Absent</th> <th style="text-align: center; padding: 5px; border: 1px #000000 solid;">Comment</th> </tr> <?php while($rows=mysql_fetch_array($result)) { ?> <tr> <td class="table1"> <? $id[] = $rows['STUDENT_NAME']; ?><? echo $rows['STUDENT_NAME'];?> </td> <td class="table1"> <input name="class[<? echo $rows['STUDENT_NAME']; ?>]" type="text" value="<? echo $rows['STUDENT_CLASS']; ?>"> </td> <td class="table1"> <input name="section[<? echo $rows['STUDENT_NAME']; ?>]" type="text" value="<? echo $rows['STUDENT_SECTION']; ?>"> </td> <td class="table1"> <input name="date[<? echo $rows['STUDENT_NAME']; ?>]" type="text" value="<? echo $rows['PRESENT_DATE']; ?>"> </td> <td id="present"> <input type="radio" name="present[<? echo $rows['STUDENT_NAME']; ?>]" checked="checked" value="PRESENT">Present </td> <td id="absent"> <input type="radio" name="present[<? echo $rows['STUDENT_NAME']; ?>]" value="ABSENT">Absent </td> <td style="text-align: left; padding: 5px; border: 1px #000000 solid; height: 33px;"> <input name="comment[<? echo $rows['STUDENT_NAME']; ?>]" type="text" value="<? echo $rows['COMMENT'];?>"> </td> </tr> <?php }?> <tr> <td colspan="7" style="vertical-align:middle; text-align: center;"><br><br> <input id="Submit" type="submit" name="Submit" value="Insert" style="text-align: center; background-color: #000000; color: #ffffff; border: 1px #000000 solid;"> </td> </tr> </tbody> </table> </form> <?php if(isset($_POST['Submit'])) { foreach($_POST['present'] as $id => $value) { $class=$_POST['class']; $section=$_POST['section']; $date=$_POST['date']; $comment=$_POST['comment']; $sql = "INSERT INTO ATTENDANCE(STUDENT_NAME, STUDENT_CLASS, STUDENT_SECTION, PRESENT_DATE, STUDENT_PRESENT, COMMENT) VALUES ('".$id."', '$class[$value]', '$section[$value]', '$date[$value]', '".$value."', '$comment[$value]') "; $result = mysql_query($sql); } } if($result) { header("location:Tea_home.php"); } else { //print_r ($_POST); echo "Your entry is not completed at this time............."; } ?> My result is comming just like that STUDENT_ID || STUDENT_NAME || STUDENT_CLASS || STUDENT_SECTION || PRESENT_DATE || STUDENT_PRESENT ||COMMENT 231 || PRASHANT KUMAR || || || 1/1/0001 12:00:00 AM || ABSENT || 230 || JYOTI NANDA || || || 1/1/0001 12:00:00 AM || PRESENT || 229 || TARUN NANDA || || || 1/1/0001 12:00:00 AM || PRESENT || 228 || RAVI KUMAR || || || 1/1/0001 12:00:00 AM || PRESENT || 227 || RAJIV KUMAR || || || 1/1/0001 12:00:00 AM || PRESENT || 226 || PRASHANT KUMAR || || || 1/1/0001 12:00:00 AM || ABSENT || 225 || JYOTI NANDA || || || 1/1/0001 12:00:00 AM || PRESENT || can you help me where i am writing wrong code I am trying to update multiple rows in a mysql db through php but I am getting an error message in this line: $size = count($_POST['uid']); My db field names are uid (which autoincrements and does not need to be updated), fname, lname and email fields. Here is a link for the project I need to develophttp://users.cis.fiu.edu/~vagelis/classes/COP5725/project.htm Here is the content for the first page: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <style type="text/css"> body { margin:50px 0px; padding:0px; text-align:center; font:13px Tahoma,Geneva,sans-serif } #content { width:1000px; margin:0px auto; text-align:left; padding:15px; border:1px dashed #333; background-color:#eee; } </style> <link rel="icon" href="http://www.mysite.com/favicon.ico" type="image/vnd.microsoft.icon" /> </head> <body> <div id='content'><h3><center>Update Information</center></h3> <?php //create a connection $connection = mysql_connect("localhost","root","r2d2c3po"); //test the connection if (!$connection) { die("Database connection failed: " . mysql_error()); } //select database to use mysql_select_db("music_social_network", $connection); //setup query $sql = "SELECT * FROM `user` ORDER BY uid"; //get results from query or die $result = mysql_query($sql, $connection) or die(mysql_error()); //fetch rows from query $rows = mysql_fetch_assoc($result); ?> <?php // find out how many records there are to update $size = count($_POST['uid']); // start a counter in order to number the input fields for each record $i = 0; print "<table width='100%' border='0' cellspacing='1' cellpadding='0'><tr><td>"; // open a form print "<form name='namestoupdate' method='post' action='update.php'> <table width='100%' border='0' cellspacing='1' cellpadding='1'><tr> <td align='center'><strong>User ID</strong></td> <td align='center'><strong>First Name</strong></td> <td align='center'><strong>Last Name</strong></td> <td align='center'><strong>Email</strong></td> </tr>\n"; // start a loop to print all of the users with their information // the mysql_fetch_array function puts each record into an array. each time it is called, it moves the array counter up until there are no more records left while ($Update = mysql_fetch_array($result)) { print "</tr>\n"; // assuming you have three important columns (the index (id), the course name (course), and the book info (bookinfo)) // start displaying the info; the most important part is to make the name an array (notice bookinfo[$i]) print "<td align='center'><p>{$Update['uid']}</p></td>\n"; print "<td align='center'><input type='text' fname='fname[$i]' value='{$Update['fname']}' /></td>"; print "<td align='center'><input type='text' size='40' lname='lname[$i]' value='{$Update['lname']}' /></td>\n"; print "<td align='center'><input type='text' size='40' email='email[$i]' value='{$Update['email']}' /></td>\n"; print "</tr>\n"; // add 1 to the count, close the loop, close the form, and the mysql connection ++$i; } print "<tr> <td colspan='4' align='center'><input type='submit' value='submit' />"; print "</td> </tr> </table> </td> </tr> </form> </table>"; mysql_close($connection); ?><br /><br /><div></body> </html> here is the content for the update.php page: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <style type="text/css"> body { margin:50px 0px; padding:0px; text-align:center; font:13px Tahoma,Geneva,sans-serif } #content { width:1000px; margin:0px auto; text-align:left; padding:15px; border:1px dashed #333; background-color:#eee; } </style> <link rel="icon" href="http://www.mysite.com/favicon.ico" type="image/vnd.microsoft.icon" /> </head> <body> <div id='content'><h3><center>Success! </center></h3> <table width='100%' border='0' cellspacing='1' cellpadding='0'><tr><td> <table width='100%' border='0' cellspacing='1' cellpadding='1'> <tr> <td align='center'><strong>User ID</strong></td> <td align='center'><strong>First Name</strong></td> <td align='center'><strong>Last Name</strong></td> <td align='center'><strong>Email</strong></td> </tr> <?php //create a connection $connection = mysql_connect("localhost","root","r2d2c3po"); //test the connection if (!$connection) { die("Database connection failed: " . mysql_error()); } //select database to use mysql_select_db("music_social_network", $connection); //setup query $sql = "SELECT * FROM `user` ORDER BY uid"; //get results from query or die $result = mysql_query($sql, $connection) or die(mysql_error()); //fetch rows from query $rows = mysql_fetch_assoc($result); // find out how many records there are to update $size = count($_POST['uid']); // start a loop in order to update each record $i = 0; while ($i < $size) { // define each variable $uid = $_POST['uid'][$i]; $fname = $_POST['fname'][$i]; $lname = $_POST['lname'][$i]; $email = $_POST['email'][$i]; // do the update and print out some info just to provide some visual feedback $query = "UPDATE `user` SET `fname` = '$fname', `lname` = '$lname', `email` = '$email' WHERE `uid` = '$uid' "; mysql_query($sql) or die ("Error in query: $query"); print " </tr> <td align='left'><p>$uid</p></td> <td align='left'>$fname</td> <td align='left'>$fname</td> <td align='left'>$lname</td> </tr> "; ++$i; } mysql_close($connection); ?> <tr> <td colspan='4' align='center'> </td> </tr> </table> </td> </tr> </table></div></body></html> Mod edit: [code] . . . [/code] tags added. I'm trying to echo multiple rows from a MySQL database with no luck. I've tried this code and many other combinations with it, but can't seem to get a result. Quote $query = "select email,mens,womens from newsletters"; $result = mysql_query($query); while ($row = mysql_fetch_assoc($result)) {foreach ($row as .$email. .$mens. .$womens.) {echo "$email - $mens - $womens<BR>";}} What am I doing wrong? Hi Guys Just need some advice to go in the right direction. I'm working on a csv upload script (part of a bigger thing i'm building), so i read in the csv to a multipdimensional array and then build a query that inputs all rows in one query - i read this is the most efficient way to import multiple rows of data at once(rather than multiple insert statements). Just for illustration here's the code i use to build the query so you understand what i'm on about: Code: [Select] $sql = "INSERT INTO teams (company, teamname, teamnum, amountraised, country, president) VALUES "; // $rows is a count of the rows in the csv for($i=1; $i<$rows; $i++){ $sql.="('{$myarray[$i][0]}','{$myarray[$i][1]}','{$myarray[$i][2]}','{$myarray[$i][3]}','{$myarray[$i][4]}','{$myarray[$i][5]}')"; echo $i . "<br/>"; if($i >= 1 && $i < $rows - 1) { $sql.= ","; } } Anyway, the issue is that one of the fields("teamnum") needs to be unique - so i've set this as unique on the table in mysql. But when i run my query it doesn't import anything if one of the records isn't unique. What i really want is for it to import the ones it can and catch the ones it cant import to present to the user. So my question is - to acheive the above would i need to rewrite the query so that it inserts each row one at a time, instead of all together? Or can someone point me in the right direction for a better solution? Probably something very simple i've missed i am sure... Thanks chaps! |