PHP - Updating Multiple Rows With Different Values
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. Similar Tutorials
Table Issue - Multiple Location Values For User Pushes Values Out Of Row Instead Of Wrapping In Cell
Hi 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> "; ?> 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> 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. 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............."; } ?> Apologies... I'm a noob trying to reverse engineer code. I have a script that can retrieve values from a MySQL database (based on a session login that recognizes which user you are) and places those values into the text fields of a form, pre-populating the form. Code: [Select] <?php mysql_connect('localhost', 'db', 'password'); mysql_select_db('users'); $id = mysql_real_escape_string($_SESSION['userid']); $select = "SELECT * FROM user_info WHERE md5(Member_No) = '$id';"; $query = mysql_query($select); if ($row = mysql_fetch_array($query)) { ?> <form> FIRST name: <input type="text" name="First" value="<?php echo stripslashes($row['First']); ?>" LAST name: <input type="text" name="Last" value="<?php echo stripslashes($row['Last']); ?>" > Birthday: <input type="text" name="Birthday" value="<?php echo stripslashes($row['Birthday']); ?>" <input type="submit" value="Submit"> </form> <?php } ?> I want to be able to connect to that same database and update ALL the values (3 in the example above) with the single click of the form button. I think I was told some time ago that it's not possible to update all the values at once? Thanks, ~Wayne Hello, I am trying to update my database with multiple array values like this. if (isset($_POST['submit_multiple'])) { $id=$_POST['selector']; $class=$_POST['class']; $section=$_POST['section']; $N = count($id); for($i=0;$i<$N;$i++) { echo "update table1 set transfer_status='yes',transfer_date='".date('Y-m-d')."',class='".$class[$i]."',section='".$section[$i]."' where enroll_no='".$id[$i]."'"; }and in the form <form action="transfer_mul_student.php" method="post"><select name="class[]"> <option value="">--SELECT CLASS--</option> <option value="Nursery">Nursery</option> <option value="LKG">LKG</option> <option value="UKG">UKG</option> <option value="I">I</option> <option value="II">II</option> <option value="III">III</option> <option value="IV">IV</option> </select> <select name="section[]"><option value="">--SELECT SECTION--</option> <option value="A">A</option> <option value="B">B</option> <option value="C">C</option> </select><input name="selector[]" id="selector" type="checkbox" value="<?php echo $row['enroll_no']; ?>" /> <input type="submit" class="delete_multiple" value="Transer" name="submit_multiple" />Here $row['enroll_no']is from table student. I have attached the screenshot for the page display with form err1.PNG 12.04KB 0 downloads, In that If i select checkbox1, checkbox2 checkbox3.. it takes the value for class and section properly, but if i select checkbox1, checkbox3, it takes value for 1st record properly and for 2nd one it takes blank value for class and section. How to overcome this? Please suggest 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, My company has 240+ locations and as such some users (general managers) cover multiple sites. When I run a query to pull user information, when the user has multiple sites to his or her name, its adds the second / third sites to the next columns, rather than wrapping it inside the same table cell. It also works the opposite way, if a piece of data is missing in the database and is blank, its pull the following columns in. Both cases mess up the table and formatting. I'm extremely new to any kind of programming and maybe this isn't the forum for this question but figured I'd give it a chance since I'm stuck. The HTML/PHP code is below: <table id="datatables-column-search-select-inputs" class="table table-striped" style="width:100%"> <thead> <tr> <th>ID</th> <th>FirstName</th> <th>LastName</th> <th>Username</th> <th>Phone #</th> <th>Location</th> <th>Title</th> <th>Role</th> <th>Actions</th> </tr> </thead> <tbody> <?php //QUERY TO SELECT ALL USERS FROM DATABASE $query = "SELECT * FROM users"; $select_users = mysqli_query($connection,$query);
// SET VARIABLE TO ARRAY FROM QUERY while($row = mysqli_fetch_assoc($select_users)) { $user_id = $row['user_id']; $user_firstname = $row['user_firstname']; $user_lastname = $row['user_lastname']; $username = $row['username']; $user_phone = $row['user_phone']; $user_image = $row['user_image']; $user_title_id = $row['user_title_id']; $user_role_id = $row['user_role_id'];
// POPULATES DATA INTO THE TABLE echo "<tr>"; echo "<td>{$user_id}</td>"; echo "<td>{$user_firstname}</td>"; echo "<td>{$user_lastname}</td>"; echo "<td>{$username}</td>"; echo "<td>{$user_phone}</td>";
//PULL SITE STATUS BASED ON SITE STATUS ID $query = "SELECT * FROM sites WHERE site_manager_id = {$user_id} "; $select_site = mysqli_query($connection, $query); while($row = mysqli_fetch_assoc($select_site)) { $site_name = $row['site_name']; echo "<td>{$site_name}</td>"; } echo "<td>{$user_title_id}</td>"; echo "<td>{$user_role_id}</td>"; echo "<td class='table-action'> <a href='#'><i class='align-middle' data-feather='edit-2'></i></a> <a href='#'><i class='align-middle' data-feather='trash'></i></a> </td>"; //echo "<td><a href='users.php?source=edit_user&p_id={$user_id}'>Edit</a></td>"; echo "</tr>"; } ?>
<tr> <td>ID</td> <td>FirstName</td> <td>LastName</td> <td>Username</td> <td>Phone #</td> <td>Location</td> <td>Title</td> <td>Role</td> <td class="table-action"> <a href="#"><i class="align-middle" data-feather="edit-2"></i></a> <a href="#"><i class="align-middle" data-feather="trash"></i></a> </td> </tr> </tbody> <tfoot> <tr> <th>ID</th> <th>FirstName</th> <th>LastName</th> <th>Username</th> <th>Phone #</th> <th>Location</th> <th>Title</th> <th>Role</th> </tr> </tfoot> </table>
I am currently trying to make a line graph out of data using php and javascript. How do I add up the values of a column and separate them by month. For example the database has 74 amount of rows. Then the values from the "views" column get added up and then displayed by month. Code: [Select] <table width="70%" class="linechart"> <thead> <tr> <td></td> <th scope="col">Jan</th> <th scope="col">Feb</th> <th scope="col">Mar</th> <th scope="col">Apr</th> <th scope="col">May</th> <th scope="col">Jun</th> </tr> </thead> <tbody> <tr> <th scope="row">Post Views</th> <td>24324</td> <td>29634</td> <td>15435</td> <td>56545</td> <td>23543</td> <td>2123</td> </tr> </tbody> </table>
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 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,
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"> Hey, Im needing some help with an update form that I have created using PHP/MySQL. Basically the form is working great (updating records, retrieving records and showing errors) but there is a problem with the errors. If there are no errors and I edit the existing text input values, the database updates fine. However if I edit the existing text input values and there is an error, the edited input values dont save, they revert back to the values of the database. I understand why this is happening, its because the text inputs are set to show the values of the database so if i edit the existing values and an error occurs or the page is refreshed, the values revert back to the database values. However id like it so that if any text in the text field have been edited and an error occurs, the text stays to how it is until the user by passes any errors and then the database is updated. Hopefully this makes sense. I have attached the php page just incase anybody wants to look into it but any help would be much appreciated! Also, im not looking for someone to just to fix this for me but if someone knows my problem and can guide me in the right direction, that would be great. Hello,
I am trying to check whether the values in rows are equal or same?
I have two tables orders and line_items. I will store more than 1 line items in line_items table with the same order_id getting from orders table. In line items if i have 3 line items for same order_id, when each line items gets dispatched i will set the status to 'Dispatched' in line_items table. When all the 3 becomes 'Dispatched', i will update the order status as 'Completed' in orders table.
Now i am not getting how to check whether all the 3 line items status id 'Dispatched'.
I tried doing like this
$q1 = "select orders.order_id, orders.item_status as istatus, orders.status as ostatus, orders.authorise, line_items.order_id, line_items.status as bstatus, COUNT(line_items.id) as bid from orders inner join line_items on orders.order_id=line_items.order_id where line_items.order_id=".$id." AND line_items.id<>'Dispatched'"; $q2 = mysql_query($q1); while($q3 = mysql_fetch_array($q2)) { echo $q3['bstatus']; if($q3['bstatus']==''); { echo "HELLLOOOO"; } }But its not working. It goes into if loop even if a single value is 'Dispatched' Please help me. 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. |