PHP - Updating Multiple Rows In One Page.
Hi all,
I'm currently working on an admin page and I'm trying to figure out how I can make an update query where all information will be updated. The code below is where I extract all the Users and their status from the database and now I when the statuses are updated in the text fields they need to be send to the database. Does anyone know how this could be done? Thnx Ryflex <?php require_once('auth.php'); require_once('config.php'); $global_dbh = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Could not connect to database"); mysql_select_db(DB_DATABASE, $global_dbh) or die("Could not select database"); $user_query = "SELECT * FROM members"; $user_result = mysql_query($user_query); ?> <form ID="gotoresource" NAME="gotoresource" METHOD="POST" ACTION="admin_exec.php"> <table width="500" border="1" align="center" cellpadding="2" cellspacing="0"> <tr> <td><b>ID</b></td> <td><b>User</b></td> <td><b>Status</b></td> </tr> <?php while($row = mysql_fetch_assoc($user_result)) { echo "<tr>"; echo "<td>"; echo $row['member_id']; echo "</td>"; echo "<td>"; echo $row['login']; echo "</td>"; ?> <td> <input type="text" name="status" value="<?php echo $row['status'];?>" /> </td> <?php echo "</tr>"; } ?> <input type="image" src="/images/button.gif" alt="Submit button"> </form> <html> <head> <title>AdminPage</title> <link href="loginmodule.css" rel="stylesheet" type="text/css" /> </head> <body> </body> </html> Similar TutorialsHi All, Can't get this code working. the statement works fine directly on the table, just not when executed from the PHP file: Code: [Select] <strong>Multi Update</strong><br> <?php $host="localhost"; // Host name $username="user_name"; // Mysql username $password="Password"; // Mysql password $db_name="dbname"; // Database name $tbl_name="tablename"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT mik1vm_product.product_id, mik1vm_product.product_sku, mik1vm_product.product_name, mik1vm_product.product_in_stock, mik1vm_product.product_in_stock_cardiff FROM $tbl_name"; $result=mysql_query($sql); // Count table rows $count=mysql_num_rows($result); ?> <table width="500" border="0" cellspacing="1" cellpadding="0"> <form name="form1" method="post" action=""> <tr> <td> <table width="500" border="0" cellspacing="1" cellpadding="0"> <tr> <td align="center"><strong>Product Id</strong></td> <td align="center"><strong>SKU</strong></td> <td align="center"><strong>Name</strong></td> <td align="center"><strong>In Stock</strong></td> <td align="center"><strong>In Stock Cardiff</strong></td> </tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td align="center"><? $product_id[]=$rows['product_id']; ?><? echo $rows['product_id']; ?></td> <td align="center"><input name="product_sku[]" type="text" id="product_sku" value="<? echo $rows['product_sku']; ?>"></td> <td align="center"><input name="product_name[]" type="text" id="product_name" value="<? echo $rows['product_name']; ?>"></td> <td align="center"><input name="product_in_stock[]" type="text" id="product_in_stock" value="<? echo $rows['product_in_stock']; ?>"></td> <td align="center"><input name="product_in_stock_cardiff[]" type="text" id="product_in_stock_cardiff" value="<? echo $rows['product_in_stock_cardiff']; ?>"></td> </tr> <?php } ?> <tr> <td colspan="4" align="center"><input type="submit" name="Submit" value="Submit"></td> </tr> </table> </td> </tr> </form> </table> <?php // Check if button name "Submit" is active, do this if($Submit){ for($i=0;$i<$count;$i++){ $sql1="UPDATE $tbl_name SET product_sku='$product_sku[$i]', product_name='$product_name[$i]', product_in_stock='$product_in_stock[$i]' , product_in_stock_cardiff='$product_in_stock_cardiff[$i]' WHERE product_id='$product_id[$i]'"; $result1=mysql_query($sql1); } } if($result1){ header("location:test.php"); } mysql_close(); ?> The page loads fine, but just doesn't update the DB. Thanks in advance for any help. Hi, I've created an admin page that lists all piano sheet music that has been uploaded to my server. It displays the ID (autoincrement), Userid (user that uploaded sheet), Artist (name of the band) and Title (name of the song). On this page, I can either delete the row completely, or click on "Uploaded", which just sets it's uploaded column to 'yes'. Now I'm working on a button called "Uploaded All". This will set the uploaded column on all of the rows on the page to 'yes'. This way I don't have to click Uploaded for every single row. (view attached image if you are unsure what I am talking about) I'm not getting any errors when clicking "Uploaded All". When clicking it, it doesn't update the table rows in the database as it should. Take a look at my code: Tip: The area of the code that I'm currently having troubles with is here $usersids[$i] = $row['id']; $i++; } echo " <tr> <td align='center' width='10' colspan='6'><a href='uploadedsheets.php?confirm=all'>Uploaded All</a></td> </tr>"; if ($confirm=="all") { $i = 0; while($row = mysql_fetch_array($result)) { mysql_query('UPDATE `upload` SET `uploaded`="yes" WHERE id = ' . $usersids[$i]); $i++; } echo "<SCRIPT language='JavaScript'><!-- window.location='uploadedsheets.php';//--> </SCRIPT>"; } Inside the above code after the if statement, I tried echoing out $usersids, and it showed correctly. So the problem must be in the update query or the array. Full Code: <?php session_start(); include_once('../inc/connect.php'); include_once('../inc/admin.php'); if(!isset($_SESSION['sort_counter'])) {$_SESSION['sort_counter'] = 1;} if(($_SESSION['sort_counter']%2) == 0){ //test even value $sortcount = "DESC"; }else{ //odd value $sortcount = ""; } $result = mysql_query("SELECT * FROM upload WHERE uploaded='no' ORDER BY id"); $unconfirmedquery = mysql_query("SELECT uploaded FROM upload WHERE uploaded='no'"); $unconfirmedcount = mysql_num_rows($unconfirmedquery); $confirmedquery = mysql_query("SELECT uploaded FROM upload WHERE uploaded='yes'"); $confirmedcount = mysql_num_rows($confirmedquery); $sort = $_GET['sort']; $delete = $_GET['delete']; $confirm = $_GET['confirm']; ///////////////////////////////// if ($sort=='id'){ // $result = mysql_query("SELECT * FROM users ORDER BY id"); $result = mysql_query("SELECT * FROM upload WHERE uploaded='no' ORDER BY id $sortcount"); $_SESSION['sort_counter'] = $_SESSION['sort_counter'] + 1; //increment after every run } if ($sort=='userid'){ // $result = mysql_query("SELECT * FROM users ORDER BY username"); $result = mysql_query("SELECT * FROM upload WHERE uploaded='no' ORDER BY userid $sortcount"); $_SESSION['sort_counter'] = $_SESSION['sort_counter'] + 1; //increment after every run } if ($sort=='artist'){ // $result = mysql_query("SELECT * FROM users ORDER BY email"); $result = mysql_query("SELECT * FROM upload WHERE uploaded='no' ORDER BY artist $sortcount"); $_SESSION['sort_counter'] = $_SESSION['sort_counter'] + 1; //increment after every run } if ($sort=='title'){ // $result = mysql_query("SELECT * FROM users ORDER BY email"); $result = mysql_query("SELECT * FROM upload WHERE uploaded='no' ORDER BY title $sortcount"); $_SESSION['sort_counter'] = $_SESSION['sort_counter'] + 1; //increment after every run } if ($sort=='file'){ // $result = mysql_query("SELECT * FROM users ORDER BY email"); $result = mysql_query("SELECT * FROM upload WHERE uploaded='no' ORDER BY file $sortcount"); $_SESSION['sort_counter'] = $_SESSION['sort_counter'] + 1; //increment after every run } /// FIX THIS AREA if ($confirm=="true" && isset($_GET['id'])) { mysql_query('UPDATE `upload` SET `uploaded`="yes" WHERE id = ' . (int)$_GET['id']); echo "<SCRIPT language='JavaScript'><!-- window.location='uploadedsheets.php';//--> </SCRIPT>"; } if ($delete=="true" && isset($_GET['id'])) { mysql_query('DELETE FROM `upload` WHERE id = ' . (int)$_GET['id']); echo "<SCRIPT language='JavaScript'><!-- window.location='uploadedsheets.php';//--> </SCRIPT>"; } if ($delete=="false" && isset($_GET['id'])) { echo "<SCRIPT language='JavaScript'><!-- window.location='uploadedsheets.php';//--> </SCRIPT>"; } ///////////////////////////////// echo " <html> <head> <title>Uploaded Sheets</title> <style> a:link{ text-decoration: none; color: #519904; } a:visited{ text-decoration: none; color: #519904; } a:hover{ text-decoration: none; color: #4296ce; } #headcont{ width: 900px; height: 20px; margin-left: auto; margin-right: auto; } #unconfirmed{ width: 450px; text-align: center; float: left; background-color: #cccccc; } #confirmed{ width: 450px; text-align: center; float: left; background-color: #72A4D2; } </style> </head> <body> "; include_once('../inc/navadmin.php'); echo "<div style='font-size: 28px; text-align: center;'>Uploaded Sheets</div> <div id='headcont'> <div id='unconfirmed'>Not Uploaded Sheets: ".$unconfirmedcount."</div> <div id='confirmed'>Uploaded Sheets: ".$confirmedcount."</div> </div><br /> <table border='1' align='center'> <tr> <th bgcolor='#cccccc'><a href='uploadedsheets.php?sort=id'>ID</a></th> <th bgcolor='#cccccc'><a href='uploadedsheets.php?sort=userid'>UserID</a></th> <th bgcolor='#cccccc'><a href='uploadedsheets.php?sort=artist'>Artist</a></th> <th bgcolor='#cccccc'><a href='uploadedsheets.php?sort=title'>Title</a></th> <th bgcolor='#cccccc'><a href='uploadedsheets.php'>Uploaded</a></th> <th bgcolor='#cccccc'><a href='uploadedsheets.php'>Delete</a></th> </tr>"; echo "<script type='text/javascript'> function show_delete() { var r=confirm('Delete?'); if (r==true) { // Delete return true; } else { // Don't Delete return false; } } "; echo " function show_undelete() { var r=confirm('Undelete?'); if (r==true) { // Undelete return true; } else { // Don't Undelete return false; } } </script>"; $usersids = ""; $i = 0; while($row = mysql_fetch_array($result)) { // $active = $row['active']; $color = "#ffffff"; $deleted = "Delete"; if ($active=='no'){ $color = "#f43636"; $deleted = "Undelete"; $active = "false"; $alert = "show_undelete"; } else{ $active = "true"; $alert = "show_delete"; } // echo "<tr>"; echo "<td align='center' width='40' bgcolor='$color'>" .$row['id']. "</td>"; echo "<td align='center' width='40'>" .$row['userid']. "</td>"; echo "<td align='center' width='230'>".ucwords($row['artist'])."</td>"; echo "<td align='center' width='230'>".ucwords($row['title'])."</td>"; echo "<td align='center' width='10'><a href='uploadedsheets.php?confirm=true&id=" .$row['id'] . "'>Uploaded</a></td>"; echo "<td align='center' width='10'><a href='uploadedsheets.php?delete=$active&id=" .$row['id']. "' onclick='return $alert()'>$deleted</a></td>"; echo "</tr>"; $usersids[$i] = $row['id']; $i++; } echo " $usersids[0] <tr> <td align='center' width='10' colspan='6'><a href='uploadedsheets.php?confirm=all'>Uploaded All</a></td> </tr>"; if ($confirm=="all") { $i = 0; while($row = mysql_fetch_array($result)) { mysql_query('UPDATE `upload` SET `uploaded`="yes" WHERE id = ' . $usersids[$i]); $i++; } echo "<SCRIPT language='JavaScript'><!-- window.location='uploadedsheets.php';//--> </SCRIPT>"; } echo "</table>"; // Footer echo " </body> </html> "; ?> 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. Hi, I have a row called code in mysql data base now what I want to do is something like this $rand=rand(1111,9999); $code=mysql_query("UPDATE member SET code='$rand' WHERE clan_id='1'"); At the moment its updating the code row with the same random number. What I want to achieve is a unique number for each member. For instance Currently if the $rand=1289 lets suppose Every code row will become 1289 I want the code rows to be different to each other. I tried a few things up my sleeve but no luck. How can i do this? thanks any help much appreciated. 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............."; } ?> 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? Hey guys, I got another one that i could use some help on. I have a input form that utilizes a javascript that adds additional rows to my table. here is a look at what i got. Code: [Select] <script type="text/javascript"> function insertRow() { var x = document.getElementById('results_table').insertRow(-1); var a = x.insertCell(0); var b = x.insertCell(1); var c = x.insertCell(2); var d = x.insertCell(3); var e = x.insertCell(4); a.innerHTML="<input type=\"text\" name=\"id\">"; b.innerHTML="<input type=\"text\" name=\"place\">"; c.innerHTML="<input type=\"text\" name=\"username\">"; d.innerHTML="<input type=\"text\" name=\"earnings\">"; e.innerHTML="<input type=\"button\" value=\"delete\" onClick=\"deleteRow(this)\">"; } function deleteRow(r) { var i=r.parentNode.parentNode.rowIndex; document.getElementById('results_table').deleteRow(i); } </script> this is my code stored in the header of my page. basically just a button to add a new row and a button in each row to delete rows if needed. here is a look at my html table, pretty basic... Code: [Select] <table id="results_table"> <th>Event ID</th><th>Place</th><th>Username</th><th>Earnings</th> <tr> <td><input type="text" name="id"></td><td><input type="text" name="place"></td><td><input type="text" name="username"></td><td><input type="text" name="earnings"></td><td><input type="button" value="delete" onClick="deleteRow(this)"</td> </tr> </table> Now what I am hoping to acheive is once i submit all of these rows to the database i will insert each of these rows into their own row in the database. is this doable? the structure of my database is: ResultID (Primary Key) Place Earnings UserID (Foreign Key) EventID (Foreign Key) now i think the biggest problem i'm having with submitting data to the database is that in the original HTML form I am typing in the actual username and not the userID. so when it comes to processing I need to do a switch of these two things before I run my query. Should something like this work? Code: [Select] $username = $_POST['username']; $userID = "SELECT userID FROM users WHERE username="$username"; $query = mysql_query($userID); also i've never tried to submit multiple entries at a time. maybe i have to create an array somehow in order to capture each rows data. any thoughts? as always thanks for the help. Hi Forum I have this script below which i thought would update multiple rows in my database, but all it does is refresh and revert back to its original data. Im guessing my problem is in my update script but I cant seem to find where I have gone wrong. Any help would be greatly appreciated. <?php $host="*****"; $username="*****"; $password="*****"; $db_name="*****"; $tbl_name="*****"; // Connect to server and select databse. $db = new PDO('mysql:host=' . $host . ';dbname=' . $db_name, $username, $password); // If there is an update, process it. if (isset($_POST['submit'], $_POST['pageorder']) && is_array($_POST['pageorder'])) { $stmt = $db->prepare("UPDATE `$tbl_name` SET `pageorder`=:pageorder WHERE id=:id"); $stmt->bindParam(':id', $id, PDO::PARAM_INT); $stmt->bindParam(':pageorder', $pageorder, PDO::PARAM_STR); foreach ($_POST['pageorder'] as $id => $pageorder) { $stmt->execute(); } echo '<h1>Updated the records.</h1>'; } // Print the form. echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF']) . '" method="post">'; foreach ($db->query("SELECT `id`, `pageorder`, `pagetitle`, `linklabel` FROM `$tbl_name` ORDER BY `pageorder`") as $row) { echo '<input type="text" pageorder="pageorder[' . (int)$row['id'] . ']" value="'. htmlspecialchars($row['pageorder']) . '" />'; echo '<input type="text" pagetitle="pagetitle[' . (int)$row['id'] . ']" value="'. htmlspecialchars($row['pagetitle']) . '" />'; echo '<input type="text" linklabel="linklabel[' . (int)$row['id'] . ']" value="'. htmlspecialchars($row['linklabel']) . '" /><br />'; } echo '<input type="submit" name="submit" value="Update" /></form>'; ?> This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=351561.0 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. I want to echo out a few subcategories per main category. It should be a maximum of 20 entries per column At this stage I have the following... It echo's the results out in 4 columns and not what I want. Any suggestions? $query = "SELECT adsubcat.name AS subname, adsubcat.linkname AS sublink, adcat.clinkname AS clink FROM adsubcat JOIN adcat ON adcat.id=adsubcat.catid WHERE adsubcat.catid='$catid' ORDER BY adsubcat.name ASC"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)) { $count = 0; print '<table style="text-align:left;margin-left:0px;width:943px;">'."\n"; while ($row = mysql_fetch_assoc($result)){ $gal = '<a href="'.$root.'/'.$row['clink'].'/'.$row['sublink'].'">'.$row['subname'].'</a>'; if ($count == 0){ print '<tr>'; } ++$count; print '<td>'.$gal.'</td>'; if ($count == 4){ $count = 0; print'</tr>'."\n"; } } print'</table>'."\n"; } Hi,
I am trying to create an admin page for a local Gym Club to allow an Administrator to be able to update club prices which then show on different screens on the site.
I have been able to display the "Prices Admin" page which basically reads a MySQL database table (pricelist), display the description, member price and non-member price and allows the user to update any of these fields.
My problem is that when I try writing the data back to the database with the "UPDATE" statement it fails, what I mean is that nothing updates. I have at the moment commented out the actual update statement and put in a "file_put_contents" command" to try and work out what is in the various fields before the UPDATE is run. I find that the display/INPUT works perfectly well but when I do a foreach on the $record array variable I am getting strange results.
I may not have explained this very well but here are the relevant sections of my code;
// Display and Input section
<div id="admin-area"> I have a problem with an amend to an admin system I am trying to change. The shop stocks different colours of each product and the client wants to be able to update the stock levels of all colours of one product (which all share the same title) on one form. I have tried following some instructions on some sites and tried making my own and I can get it to display the form and the values correctly, but on submission it does nothing but direct me to a page without a title value in the address (e.g. www.example.com/example/stock_level_2.php?title=). I think it may be to do with the arrays I am using, has anyone got any ideas? Here is the code. Form: Code: [Select] <?php $pd_title = str_replace("_"," ",$_REQUEST["title"]); $pd_title = str_replace("%","&#37;",$pd_title); $pd_title = str_replace("/","&#47;",$pd_title); $lookupqueryc = mysql_query("SELECT * FROM product WHERE pd_title = '".$pd_title."' ORDER BY pd_id DESC"); echo '<table><tr><th align="center" class="bodytext">Product<br />ID</th><th align="center" class="bodytext">Product Name</th><th align="center" class="bodytext">Stock Level</th></tr>'; $form = '<form name="frmAmendStock" method="post" action="stock_level_2.php?title="'; $form .= $_GET["title"]; $form .= '" enctype="multipart/form-data">'; echo $form; echo '<input name="submitted" type="hidden" value="true">'; $count=mysql_num_rows($lookupqueryc); echo '<input name="count" type="hidden" value="'; echo $count; echo '">'; while($lookupresultc = mysql_fetch_array($lookupqueryc)){ echo '<tr><td align="center" class="bodytext">'; $id[]=$lookupresultc["pd_id"]; echo $lookupresultc["pd_id"]; echo '</td><td class="bodytext">'; echo $lookupresultc["pd_title"]; if (isset($lookupresultc["pd_colour"]) && $lookupresultc["pd_colour"] !="") { echo " ("; echo $lookupresultc["pd_colour"]; echo ')'; } if ($lookupresultc["pd_stock"] <= 5) { echo '</td><td align="center" class="bodytext" style="border: 2px solid red;">'; echo '<input name="stock[]" type="text" id="stock" value="'; echo $lookupresultc["pd_stock"]; echo '"style="width: 50px;" />'; echo "</td></tr>"; }else{ echo '</td><td align="center" class="bodytext">'; echo '<input name="stock[]" type="text" id="stock" value="'; echo $lookupresultc["pd_stock"]; echo '"style="width: 50px;" />'; echo "</td></tr>"; } } ?> <tr> <td> </td> <td height="35"><a href="javascript: " onClick="javascript:document.forms.frmAmendStock.submit()" class="bodytext"><strong>click here to amend your stock </strong></a></td> </tr> </form> </table> And here is the code it should run on submission: Code: [Select] <?php if (isset($_POST["submitted"])) { for($i=0;$i<$_POST["count"];$i++){ mysql_query("UPDATE product SET pd_stock='$stock[$i]' WHERE pd_id='$id[$i]'"); } } ?>
Hi Guys, <?php $host="xxx"; // Host name $username="xxx"; // Mysql username $password="xxx"; // Mysql password $db_name="xxx"; // Database name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM attendance"; $result=mysql_query($sql); // Count table rows $count=mysql_num_rows($result); ?> <html> <head> <title>Registers</title> </head> <body> <?php include 'Navigation.php';?> <table width="500" border="0" cellspacing="1" cellpadding="0"> <form name="form1" method="post" action=""> <table border="0" cellspacing="1" cellpadding="0" style="width: 1461px; height: 105px"> <tr> <td align="center"><strong>Id</strong></td> <td align="center"><strong>Last Name</strong></td> <td align="center"><strong>First Name</strong></td> <td align="center"><strong>Form</strong></td> <td align="center"><strong>Year Group </strong></td> <td align="center"><strong>Date</strong></td> <td align="center"><strong>Attendance</strong></td> </tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td align="center"><? $Student_id[]=$rows['Student_id']; ?><? echo $rows['Student_id']; ?></td> <td align="center"><? $firstname[]=$rows['firstname']; ?><? echo $rows['firstname']; ?></td> <td align="center"><? $lastname[]=$rows['lastname']; ?><? echo $rows['lastname']; ?></td> <td align="center"><? $Form_Group[]=$rows['Form_Group']; ?><? echo $rows['Form_Group']; ?></td> <td align="center"><? $Year_Group[]=$rows['Year_Group']; ?><? echo $rows['Year_Group']; ?></td> <td align="center"><? $Att_Date[]=$rows['Att_Date']; ?><? echo $rows['Att_Date']; ?></td> <td align="center"><input name="Presence[]" type="text" id="Presence" value="<? echo $rows['Presence']; ?>"></td> </tr> <?php } ?> <tr> <td colspan="7" align="center"><input type="submit" name="Submit" value="Submit Register"></td> </tr> </table> </form> </table> <?php // Check if button name "Submit" is active, do this if($Submit){ for($i=0;$i<$count;$i++){ $sql1="UPDATE attendance SET Presence='$Presence[$i]' WHERE Student_id='$Student_id[$i]'"; $result1=mysql_query($sql1); } } if($result1){ header("location:Registers.php"); } mysql_close(); ?>
I know how to pull data from sql table and limit down the results, what i wanted to do is pull data from a sql table 'finished' and list data that has paid='0' this is then limited to show the amount of rows set by variable 'maxPay' here is my list what im pulling atm; <h2>Payment </h2> <?php if($userType[user_type]==28){ $queryPay = mysql_query("SELECT * FROM finished WHERE paid='0'&&method!='FALSE'&&method!='credit';") or die(mysql_error()); $queryAdmin = mysql_query("SELECT maxPay FROM `admin`;") or die(mysql_error()); $row = mysql_num_rows($queryPay); //echo $row."row<br />"; $rowsArray = mysql_fetch_assoc($queryAdmin); $rows = $rowsArray[maxPay]; //echo $rows."rows<br />"; if($rows>$row){ $r=$row; } else{ $r=$rows; } $s=0; while($s<$r){ if($_POST[complete]==TRUE){ mysql_query("UPDATE `finished` SET `paid`='$_POST[paid]' WHERE `auctionID`='$_POST[aid]';"); $_POST[complete] = FALSE; } $s++; } $t=0; while($t<$r){ $queryuser = mysql_query("SELECT * FROM finished WHERE paid='0'&&method!='FALSE'&&method!='credit';") or die(mysql_error()); $user = mysql_result($queryuser, $t, "username"); //echo $user; $item = mysql_result($queryuser, $t, "itemName"); //echo $item; $value = mysql_result($queryuser, $t, "marketPrice"); //echo $value; $method = mysql_result($queryuser, $t, "method"); //echo $method; $id = mysql_result($queryuser, $t, "auctionID"); //echo $id; //echo $method; if($method=='isk'){ ?> <FORM method="post" action="pay.php"> <input type="hidden" name=complete value="TRUE" /> <input type="hidden" name=paid value="YES" /> <input type="hidden" name=username value="<? echo $user; ?>" /> <input type="hidden" name=aid value="<? echo $id; ?>" /> <input type="submit" value="Paid" /><? echo $user." won a ".$item." he selected to receive ".$value."ISK."; echo "<br />"; ?></FORM><? } elseif($method=='ship'){ ?> <FORM method="post" action="pay.php"> <input type="hidden" name=complete value="TRUE" /> <input type="hidden" name=paid value="YES" /> <input type="hidden" name=username value="<? echo $user; ?>" /> <input type="hidden" name=aid value="<? echo $id; ?>" /> <input type="submit" value="Paid" /><? echo $user." won a ".$item." he selected to receive the ship."; echo "<br />"; ?></FORM><? } else{ } $t++; } } else{ echo "You are not an Admin."; } ?> and pay.php: <?php header('Location: /admin.php'); include "connect.php"; echo $_POST[aid]; if($_POST[complete]==TRUE){ $tempID = (($_POST[aid])+1); mysql_query("UPDATE `finished` SET `paid`='$_POST[paid]' WHERE `auctionID`='$tempID';") or die(mysql_error()); $_POST[complete] = FALSE; } ?> at the moment i am listing all my data, and processing it using pay.php, each dataset has a "paid" button, i want to change this to using a checkbox at end of each data row, and a submit button at the bottom. this way i can select which rows to update and tick the checkbox, then click submit and those rows will then be updated the value '0' in db to a value of 'YES'. hope i explained myself clearly enough for some help. im a relative php noob still in training. As I am new to all this php, I need some help and/or ideas on how to code this little idea of mine: I have a database with a members table, I would like to create some Teams, and so I want too create a new table with the info for these teams. My problem is to set what team a member belongs too. My idea short Add a new column in the members area to hold the Id of the team this member belongs too. So if member 1000 sends a "join team link" too member 2000 the script needs to get the team id from member 1000 and add this id to member 2000. select teamid from members where id=1000 update teamid='same id as member 1000' where id='membersid' I hope this all makes sense, cause I am having a hard time trying to explain it. hello guys moving on from inserting multiple records im now stuck with updating multiple records. i can get most of the details nailed but i need it to match the id's for the table the code i have in the sql part are Code: [Select] if (isset($_POST['submit'])) { //Assign each array to a variable $StaffMember = $_POST['StaffMember']; $referrer = $_POST['referrer']; $referred = $_POST['referred']; $SentOut = $_POST['SentOut']; $today = date("y.m.d H:i:s"); $user_id = $_SESSION['user_id']; $IssueNum = $_POST['Referrerid']; $limit = count($StaffMember); $values = array(); // initialize an empty array to hold the values for($k=0;$k<$limit;$k++){ $msg[] = "$limit New KPI's Added"; $values[$k] = "( '{$StaffMember[$k]}', '{$referrer[$k]}', '{$referred[$k]}', '{$SentOut[$k]}', '{$today}', '{$user_id}' )"; // build the array of values for the query string } $query = "UPDATE `Referrer` (StaffMember, referer, referred, SentOut, SentOutDate, SentOutBy) VALUES " . implode( ', ', $values ) . " WHERE IssueNum= '{$IssueNum[$k]}'"; echo $query; } i obviously want the records updating where the issuenumber is the same and if the check box in the form is ticked help with this one? This is the form that I'm using and it populates just fine but when you make the changes I can't figure out how to get it to update each record in my database. Code: [Select] <table width="100%" cellspacing="1" cellpadding="2" border="0"> <form action="<?php echo $_SERVER["PHP_SELF"] . "?update=1"; ?>" method="post"> <tr> <td><b>Category Name</b></td> <td><b>Category Description</b></td> <td><b>Order</b></td> <td align="right"><input type="submit" value="Update"></td> </tr> <?php read_cat_list($cat); for ($i = 0; $i < $cat["count"]; $i++) { echo "<tr>\n"; echo "<td width=\"30%\" valign=\"top\"><input type=\"text\" name=\"cat_name_" . safe_string($cat[$i]["cat_id"]) . "\" size=\"30\" maxlength=\"250\" value=\"" . safe_string($cat[$i]["cat_name"]) . "\"></td>\n"; echo "<td width=\"36%\" valign=\"top\"><textarea name=\"cat_desc_" . safe_string($cat[$i]["cat_id"]) . "\" rows=\"2\" cols=\"30\">" . safe_string($cat[$i]["cat_desc"]) . "</textarea></td>\n"; echo "<td width=\"10%\" valign=\"top\"><input type=\"text\" name=\"cat_order_" . safe_string($cat[$i]["cat_id"]) . "\" size=\"3\" maxlength=\"3\" value=\"" . safe_string($cat[$i]["cat_order"]) . "\"></td>\n"; echo "<td width=\"24%\" valign=\"top\">[ <a href=\"#\" onmouseover=\"window.status = 'Delete " . safe_string($cat[$i]["cat_name"]) . "'; return true;\" onmouseout=\"window.status = ''; return true;\" onclick=\"javascript:del_cat(" . $cat[$i]["cat_id"] . ", '" . safe_string($cat[$i]["cat_name"]) . "'); return false;\">Delete</a> ]</td>\n"; echo "</tr>\n"; } ?> <tr> <td colspan="4" align="right"><input type="submit" value="Update"></td> </tr> </form> </table> the safe_string function just cleans up the output/input from the database, This next block is my form processor for this form. Code: [Select] <?php function update_cats($vars) { $err = ""; #if ($SESSION["level"] != ADMIN) { # $err = ERR_NOT_ENOUGH_ACCESS; #} else { $temp = array_keys($vars); for ($i = 0; $i < count($temp); $i++) { if (substr($temp[$i], 0, 9) == "cat_name_") { if ($vars[$temp[$i]] == "") { $err = "Category names cannot be blank."; break; } else { $name_query["cat_name"] .= substr($temp[$i], 9) . ", "; } } } for ($i = 0; $i < count($temp); $i++) { if (substr($temp[$i], 0, 9) == "cat_desc_") { $desc_query["cat_desc"] .= substr($temp[$i], 9) . ", "; } } for ($i = 0; $i < count($temp); $i++) { if (substr($temp[$i], 0, 10) == "cat_order_") { if ($vars[$temp[$i]] == "") { $err = "Category orders cannot be blank."; break; } else { $order_query["cat_order"] .= substr($temp[$i], 10) . ", "; } } } #} if (!$err) { if ($name_query["cat_name"]) { $update_name_query = "update category"; $update_name_query .= " set cat_name = '" . $name_query["cat_name"] . "'"; $update_name_query .= " where cat_id in (" . substr($name_query["cat_name"], 0, -2) . ")"; update_db($update_name_query); } if ($desc_query["cat_desc"]) { $update_desc_query = "update category"; $update_desc_query .= " set cat_desc = '" . $name_query["cat_desc"] . "'"; $update_desc_query .= " where cat_id in (" . substr($desc_query["cat_desc"], 0, -2) . ")"; update_db($update_desc_query); } if ($order_query["cat_order"]) { $update_order_query = "update category"; $update_order_query .= " set cat_order = '" . $name_query["cat_order"] . "'"; $update_order_query .= " where cat_id in (" . substr($order_query["cat_order"], 0, -2) . ")"; update_db($update_order_query); } } return $err; } ?> update_db is my database caller, if you need any of the functions that I use that are not here please post back and tell me. now when I process the form all my fields change to this: cat_name: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, cat_desc: cat_id: 0 for all the records in the database table, I'm just trying to update each record with the values it needs Here is my database table with the data. Code: [Select] CREATE TABLE `category` ( `cat_id` int(11) NOT NULL AUTO_INCREMENT, `cat_name` varchar(255) NOT NULL, `cat_desc` text NOT NULL, `cat_order` int(11) NOT NULL, PRIMARY KEY (`cat_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ; -- -- Dumping data for table `category` -- INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(1, 'Hand Tossed Pizza', '', 1); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(2, 'Hand Tossed Specialty Pizzas', '', 2); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(3, 'Chicago Style Deep Dish', '', 3); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(4, 'Specialty Chicago Style Deep Dish', '', 4); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(5, 'Chicken Wings & Tenderloins', '', 5); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(6, 'Hot Sides', '', 6); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(7, 'Hot Sandwiches', '', 7); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(8, 'Cold Sandwiches', '', 8); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(9, 'Pastas', '', 9); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(10, 'Fresh Salads', '', 10); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(11, 'Fresh Breads', '', 11); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(12, 'Soups', '', 12); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(13, 'Kids Menu', '', 13); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(14, 'Drinks', '', 14); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(15, 'Desserts', '', 15); Hope I have provided plenty of info on what I got and what I need for it todo Thanks I have problem that only last text field is updated, how should I fix this? Here's the code <?php if(isset($_POST["update"])){ mysql_query("UPDATE categories SET name_category = '".$_POST['category']."' WHERE ID= ".$_POST['currentCat']." ") or die(mysql_error()); mysql_query("UPDATE podkategorije SET name_subcategory = '".$_POST['subcategory']."' WHERE id_subCat= ".$_POST['currentSubCat']." ") or die(mysql_error()); } ?> <form action="" method="post" > <?php //creating texfields from db $query = "SELECT k.ID, k.name_category, pk.name_subcategory, pk.id_subCat FROM `categories` AS k JOIN `subcategories` AS pk ON pk.id_mainCat = k.ID"; $result = mysql_query($query) or die(mysql_error()); $currentCat = false; while($row = mysql_fetch_array($result)) { //so it doesn't repeat itself if($currentCat != $row['ID']) { //display of main Categories ?> <ul> <li> <br/><input name="categories" type="text" value="<?php echo $row['name_category']; ?>" /> </li> </ul> <? $currentCat = $row['ID']; } //display subcategories ?> <input name="subcategories" type="text" value="<?php echo $row['name_category']; ?>" /><br/> <input type="hidden" name="currentCat" value="<?php echo $row['ID']; ?>" /> <input type="hidden" name="currentSubCat" value="<?php echo $row['id_subCat']; ?>" /> <? } ?> <br /> <input type="button" value="Back" onClick="history.go(-1);return true;"> <input type="submit" value="Update" name="update"/> </form> Am currently trying to develop a SaaS, where each user gets their own subdomain with their application. Am wondering, though, with installation and subsequent updates:
What is the best way to initiate an installation? The project is currently in a git repository. Is it better to simply pull the master branch per installation; or is zipping up the master branch, copying it to the new subdomain, then running the installation a better (secure?) method?
What is the best way to initiate an update of code? If using the git repo, hat would deal with updated code, but not updated MySQL tables.
Should the user be allowed to choose to update (so much like W$, a popup shows up that says there's an update; user can choose to update or ignore); or should all updates be forced (such as at a certain time)?
I haven't seen much online with my searches, but I may be blind at this point. Any thoughts/comments appreciated!
|