PHP - Mysql - Importing Multiple Rows Of Data At Once
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! Similar TutorialsThis topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=351561.0 Hi, after banging my head against the wall for a while thinking this would be a simple task, I'm discovering that this is more complicated than I thought. Basically what I have is a link table linking together source_id and subject_id. For each subject there are multiple sources associated with each. I had created a basic listing of sources by subject... no problem. I now need a way of having a form to create an ordered list in a user-specified way. In other words, I can currently order by id or alphabetically (subject name lives on a different table), but I need the option of choosing the order in which they display. I added another row to this table called order_by. No problem again, and I can manage all of this in the database, however I want to create a basic form where I can view sources by subject and then enter a number that I can use for sorting. I started off looping through each of the entries and the database (with a where), and creating a foreach like so (with the subject_id being grabbed via GET from the URL on a previous script) Code: [Select] while($row = mysqli_fetch_array($rs)) { //update row order if (isset($_POST['submit'])) { //get variables, and assign order $subject_id = $_GET['subject_id']; $order_by = $_POST['order_by']; $source_id = $row['source_id']; //echo 'Order by entered as ' . $order_by . '<br />'; foreach ($_POST['order_by'] as $order_by) { $qorder = "UPDATE source_subject set order_by = '$order_by' WHERE source_id = '$source_id' AND subject_id = '$subject_id'"; mysqli_query($dbc, $qorder) or die ('could not insert order'); // echo $subject_id . ', ' . $order_by . ', ' . $source_id; // echo '<br />'; } } else { $subject_id = $_GET['subject_id']; $order_by = $row['order_by']; $source_id = $row['source_id']; } And have the line in the form like so: Code: [Select] echo '<input type="text" id="order_by" name="order_by[]" size="1" value="'. $order_by .'"/> (yes I know I didn't escape the input field... it's all stored in an htaccess protected directory; I will clean it up later once I get it to work) This, of course, results in every source_id getting the same "order_by" no matter what I put into each field. I'm thinking that I need to do some sort of foreach where I go through foreach source_id and have it update the "order_by" field for each one, but I must admit I'm not sure how to go about this (the flaws of being self-taught I suppose; I don't have anyone to go to on this). I'm hoping someone here can help? Thanks a ton in advance 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. 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. This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=344772.0 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 am trying to array data to database against same id.
Here is code.
form.php
<form name="users" method="post" action="order_submit.php" enctype="multipart/form-data" onSubmit="return validate();" id="inv_form"> <div class="formSep"> <select name="company" onChange="showSubcat(this);"> <option value="">Company</option> <?php $s1 = mysql_query("select * from leads where lead_customer='Lead' ") or die (mysql_error()); while($s2 = mysql_fetch_array($s1)) { ?> <option value="<?php echo $s2['id']; ?>"><?php echo $s2['company']; ?></option> <?php } ?> </select> </div> <div class="formSep"> <table class="table invE_table"> <thead> <tr> <th></th> <th>Item</th> <th>Unit</th> <th>Unit Cost ($)</th> <th>Qty</th> <th>Tax (%)</th> <th>Total ($)</th> </tr> </thead> <tbody> <tr class="inv_row"> <td class="inv_clone_row"><i class="icon-plus inv_clone_btn"></i></td> <td><input type="text" class="span12" name="invE_item[]" /></td> <td><input type="text" class="span12" name="invE_description[]" /></td> <td><input type="text" class="span12 jQinv_item_unit" name="invE_unit_cost[]" /></td> <td><input type="text" class="span12 jQinv_item_qty" name="invE_qty[]" /></td> <td><input type="text" class="span12 jQinv_item_tax" name="invE_tax[]" /></td> <td><input type="text" readonly class="span12 jQinv_item_total" name="invE_total[]" /></td> </tr> <tr class="last_row"> <td colspan="5"> </td> <td colspan="2"> <p class="clearfix">Subtotal: <span class="invE_subtotal">$<span>0.00</span></span></p> <p>Tax: <span class="invE_tax">$<span>0.00</span></span></p> <p>Discount: <span class="invE_discount">$<span>0.00</span></span></p> <p><strong>Balance: <span class="invE_balance">$<span>0.00</span></span></strong></p> </td> </tr> </tbody> </table> </div>Here invE_item[], invE_description[], invE_unit_cost[].... are the array , i mean dynamically one can add as many as items and its details. In my order_submit.php page <?php error_reporting(0); include("connect.php"); include("admin_auth.php"); if(isset($_POST['save'])) { $company = $_POST['company']; $contact_person = $_POST['contact_person']; $billing = $_POST['billing_address']; $shipping = $_POST['shipping_address']; $reference = $_POST['reference']; $t_c = $_POST['t_c']; $payment = $_POST['payment']; $ship_in = $_POST['ship_inst']; $validity = $_POST['validity']; $currency = $_POST['currency']; $order_for = $_POST['order_for']; $assigned_to = $_POST['assigned_to']; $item = $_POST['invE_item']; $unit = $_POST['invE_description']; $price = $_POST['invE_unit_cost']; $qty= $_POST['invE_qty']; $tax = $_POST['invE_tax']; $total = $_POST['invE_total']; $sql = mysql_query("insert into orders (order_id, company_id, contact_person, billing_address, shipping_address, reference, t_c, payment, shipping_inst, validity, order_for, currency, assigned_to, last_modified, order_quote) values ('', ".$company.", '".$contact_person."', '".$billing."', '".$shipping."', '".$reference."', '".$t_c."', '".$payment."', '".$ship_in."', ".$validity.", '".$order_for."', '".$currency."', '".$assigned_to."', NOW(), 'Order')"); $last_id = mysql_insert_id(); $msql = "insert into order_line_items (id, order_id, company_id, item, unit, unit_cost, quantity, tax, total) values ('', ".$last_id.", ".$company.", '".$item."', '".$unit."', ".$price.", ".$qty.", ".$tax.", ".$total.")"; $l1 = mysql_query($msql) or die (mysql_error()); }I want to insert each item in different row with $last_id , as in the attached image . Please somebody help me in this Attached Files db.PNG 11.01KB 4 downloads This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=327017.0 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 All, I'm hoping someone can help me. I'm looking to create a form that will submit multiple entries to a MySQL database depending on the options selected on the form. I am able to submit single entries, but the multiple entire is a bit of a mystery to me. I have attached an JPG image to show an example of how I would like the form to work. I have also added the description/explination below to this example: Example 1 The form was completed and three access types were selected. Thus Three entries, all with the Same Reference number were captured into the database Example 2 The form was completed and Two Access Types were selected. Thus Two entries, all with the Same Reference number were captured into the database Example 3 The form was completed and Four Access Types were selected. Thus Four entries, all with the Same Reference number were captured into the database 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. hello friend, I use these code for update my database with radio button checked or unchecked through array but my code could not update the server data please help me ::: my code is ::: <?php //include configuration file for connection include_once('config.php'); $sql = "select * from ATTENDANCE"; $result=mysql_query($sql); $count=mysql_num_rows($result); ?> <form name="form1" method="post" action="<? echo $_SERVER['REQUEST_URI']; ?>"> <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 ID</th> <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 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_ID']; ?><? echo $rows['STUDENT_ID']; ?> </td> <td class="table1"> <? echo $rows['STUDENT_NAME']; ?> </td> <td id="present"> <input type="radio" name="present<? echo $rows['STUDENT_ID']; ?>" checked="checked" value="PRESENT">Present </td> <td id="absent"> <input type="radio" name="present<? echo $rows['STUDENT_ID']; ?>" value="ABSENT">Absent </td> <td style="text-align: left; padding: 5px; border: 1px #000000 solid; height: 33px;"> <? echo $rows['COMMENT']; ?> </td> </tr> <?php }?> <tr> <td colspan="5" style="vertical-align:middle; text-align: center;"><br><br> <input id="Submit" type="submit" name="Submit" value="Submit" style="text-align: center; background-color: #000000; color: #ffffff; border: 1px #000000 solid;"> </td> </tr> </tbody> </table> </form> <?php if($_POST['$Submit']) { foreach($_POST['STUDENT_ID'] as $id) { $sql = "UPDATE ATTENDANCE SET STUDENT_PRESENT = '".$_POST["present".$id]."' WHERE STUDENT_ID = '".$id."' "; $result = mysql_query($sql); } } if($result) { print_r ($_POST); header("location:report.php"); } else { echo "Your entry is not completed at this time............."; } ?> Hi, I am having difficulty deleting rows in my table using check boxes. I have all the check boxes displaying for each row and a delete button below the table. However when i click on the delete button it isnt deleting the checked rows, i have displayed the code below that i am using; Code: [Select] <?php $result = mysql_query("SELECT * FROM contact ORDER BY msg_id ASC"); echo "<table border='1'> <tr> <th>Delete</th> <th>Message ID</th> <th>Name</th> <th>Email</th> <th>Message</th> </tr>"; while($row = mysql_fetch_array($result)) { ?> <td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $row['del_id']; ?>"></td> <?php echo "<td>" . $row['msg_id'] . "</td>"; echo "<td>" . $row['name'] . "</td>"; echo "<td>" . $row['email'] . "</td>"; echo "<td>" . $row['msg'] . "</td>"; echo "</tr>"; } echo "</table>"; ?> <td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td> </tr> <?php // Check if delete button active, start this if(isset($_GET['delete'])) { for($i=0;$i<$count;$i++){ $del_id = $checkbox[$i]; $sql = "DELETE FROM contact WHERE id=".$_GET['del_id']; $result = mysql_query($sql); } // if successful redirect to delete_multiple.php if($result){ } } mysql_close(); ?> Please help Thank you 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 i have 8 division (div), i want to display 4 rows in 4 division and the remain 4 rows in the next 4 division here is my code structure for carousel
<div class="nyie-outer"> second row third row
fourth row fifth row sixth row seven throw eighth row
</div><!--/.second four rows here-->
sql code
CREATE TABLE product( php code
<?php how can i echo that result in those rows
Hello,
I am trying to import a CSV file into an existing mysql table but it doesn't seem to work well.
Here is how my mysql is looking like:
1 a_id int(11) AUTO_INCREMENT 2 a_lobecoid int(7) 3 a_code varchar(30) utf8_general_ci 4 a_omschint varchar(60) utf8_general_ci 5 a_beveiligingniv int(5) 6 a_type varchar(5) utf8_general_ci 7 a_assortiment int(5) 8 a_discipline varchar(30) utf8_general_ci 9 a_brutoprijs varchar(50) utf8_general_ci 10 a_status varchar(5) utf8_general_ci 11 a_levcode varchar(10) utf8_general_ci 12 a_omschr_nl varchar(60) utf8_general_ci 13 a_omschr_fr varchar(60) utf8_general_cithese are some lines from my CSV file 16158|-H|Factory installed heater|10|S|400|CCTV|45.0|E| 1829|Factory installed heater|Factory installed heater 16159|-IR|Factory installed IR LED ring|10|S|400|CCTV|50.0|E| 1829|Factory installed IR LED ring|Factory installed IR LED ring 9001|00-SBN2|Smoke box niet geaspireerd,230VAC|10|S|267|BRAND|1587.03|D| 642|Smoke box niet geaspireerd,230VAC|Smoke box pas aspiré,230VCA 9003|00-TP1|Telescopische verlengstok voor Smoke box,2,4-4,6m|10|S|267|BRAND|644.09000000000003|D| 642|Telescopische verlengstok voor Smoke box,2,4-4,6m|Rallonge téléscopique pour Smoke box,2,4-4,6m 9004|00-TP2|Telescopische verlengstok voor Smoke box,2,4-9,2m|10|S|267|BRAND|944.64999999999998|D| 642|Telescopische verlengstok voor Smoke box,2,4-9,2m|Rallonge téléscopique pour Smoke box,2,4-9,2m 12161|001-0081|Thermistor probe,rood, high temp. 0-+150°C|10|S|52|INBRAAK|136.91|D| 1731|Thermistor probe,rood, high temp. 0-+150°C|Sonde température,rouge,high temp. 0-+150°CHere you have the code for the import: $upload_article_query = "LOAD DATA INFILE 'ARTIKELS.CSV' INTO TABLE artikelen FIELDS TERMINATED BY '|' LINES TERMINATED BY '\\r\\n' (a_lobecoid, a_code, a_omschint, a_beveiligingniv, a_type, a_assortiment, a_discipline, a_brutoprijs, a_status, a_levcode, a_omschr_nl, a_omschr_fr)"; $upload_article_stmt = $dbh->prepare($upload_article_query); $upload_article_stmt->execute();If i use the code then in the MYSQL table the first line is filled in but where the second line has to start it just writes it into the last column and doesn't start a new line. Also if i edit that first line it shows a lot of "?" (questionmarks) into a window symbol. Anyone has an idea what i am doing wrong? In attachment some printscreens of my table after the insert. Apologies for the Dutch language. Thanks in advance Attached Files pic1.jpg 6.13KB 0 downloads pic2.jpg 37.9KB 0 downloads Am trying to import a csv file into mysql. below is the code am using.
<?php //connect to the database include('mysql_connect.php');//select the table // if ($_FILES[csv][size] > 0) { //get the csv file $file = $_FILES[csv][tmp_name]; $handle = fopen($file,"r"); //loop through the csv file and insert into database do { if ($data[0]) { mysql_query("INSERT INTO requisition (department, contact_last, contact_email) VALUES ( '".addslashes($data[0])."', '".addslashes($data[1])."', '".addslashes($data[2])."' ) "); } } while ($data = fgetcsv($handle,1000,",","'")); // //redirect header('Location: import.php?success=1'); die; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR...nsitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Import a CSV File with PHP & MySQL</title> </head> <body> <?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?> <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1"> Choose your file: <br /> <input name="csv" type="file" id="csv" /> <input type="submit" name="Submit" value="Submit" /> </form> </body> </html> ........................................................................................................................................... On page load, it gives some erros Notice: Use of undefined constant csv - assumed 'csv' in C:\wamp\www\orango\upload_data.php on line 7 Notice: Use of undefined constant size - assumed 'size' in C:\wamp\www\orango\upload_data.php on line 7 Notice: Undefined index: csv in C:\wamp\www\orango\upload_data.php on line 7 Notice: Use of undefined constant success - assumed 'success' in C:\wamp\www\orango\upload_data.php on line 43 I try to ignore the errors to see if it would work but it didn't save in the DB. please help me out Hey guys! So I have this script to import a CSV file into my database:
<?php $databasehost = "localhost"; $databasename = "import"; $databasetable = "import"; $databaseusername="username"; $databasepassword = "password"; $fieldseparator = ","; $lineseparator = "\n"; $csvfile = "test.csv"; if(!file_exists($csvfile)) { die("File not found. Make sure you specified the correct path."); } try { $pdo = new PDO("mysql:host=$databasehost;dbname=$databasename", $databaseusername, $databasepassword, array( PDO::MYSQL_ATTR_LOCAL_INFILE => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ) ); } catch (PDOException $e) { die("database connection failed: ".$e->getMessage()); } $pdo->exec("TRUNCATE TABLE `$databasetable`"); $affectedRows = $pdo->exec(" LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." REPLACE INTO TABLE `$databasetable` FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)." LINES TERMINATED BY ".$pdo->quote($lineseparator)." IGNORE 1 LINES"); echo "Loaded a total of $affectedRows records from this csv file.\n"; ?>So that script basically imports a csv replacing all of the other data. The issue I am having is that the data inside one of the columns contains commas, they are wrapped in quotations. Here is an example: ,"1 Registered Keeper, Full Service History, Central Locking, Electric Windows, Electric Mirrors, ABS, Traction Control, Climate Control, Power Steering, Drivers Airbag, Passenger Airbag, Side Airbags, Cruise Control, Alarm, Immobiliser, Half Leather Interior, Alloy Wheels", How could I make the script determine the text within those quotation marks as a whole value instead of separating them into individual columns? Thanks any help on this would be great! Hi everyone, I am currently making a page for a friend to upload a bunch of photos at a time. I was quite pleased that after a bit of googling and trial and error, I figured out how to do this so that multiple records could be added to my table with one submit button. However, my form has 10 browse iconcs. A few tests have revealed that my problem is that if only one picture is uploaded, I still get 9 entries in my database, which I don't want. My question is how can I alter the code so that a row is only populated in the database if an image is uploaded. I guess something that sort of says : if($imgx!="") { populate that row in the table } else { don't } ...and the same for $imgx002 through to $imgx010 The current query is below. Any pointers are much appreciated. Code: [Select] $query = "INSERT INTO photo_uploads (date, photo_name)" . "VALUES (NOW(), '$imgx'), (NOW(), '$imgx002'), (NOW(), '$imgx003'), (NOW(), '$imgx004'), (NOW(), '$imgx005'), (NOW(), '$imgx006'), (NOW(), '$imgx007'), (NOW(), '$imgx008'), (NOW(), '$imgx009'), (NOW(), '$imgx010')"; |