PHP - Update Array Isn't Sending Entire Array To Row
I've used a lot of solutions from this site, however, this is my first post, so go easy on me :-)
I've created a product form the successfully INSERTS data to a mysql table. I can successfully query the data so that product information can be updated. When I click submit to UPDATE the rows, everything updates except for 2 fields that are arrays. Here is my product form that populates data to be edited. Code: [Select] <?php session_start(); require("config.php"); require("db.php"); require("functions.php"); if(isset($_SESSION['SESS_ADMINLOGGEDIN']) == FALSE) { header("Location: " . $config_basedir); } if(isset($_GET['func']) == TRUE) { if($_GET['func'] != "conf") { header("Location: " . $config_basedir); } $validid = pf_validate_number($_GET['id'], "redirect", $config_basedir); header("Location: " . $config_basedir . "adminedit.php"); } else { require("header.php"); $sql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";"; $query = mysql_query($sql); while ($prodrow = mysql_fetch_array($query)){ $id = $prodrow['id']; $active=$prodrow['active']; $cat_id=$prodrow['cat_id']; $name=$prodrow['name']; $description=$prodrow['description']; $details=$prodrow['details']; $price=$prodrow['price']; $price2=$prodrow['price2']; $price3=$prodrow['price3']; $price4=$prodrow['price4']; $price5=$prodrow['price5']; $price6=$prodrow['price6']; $minimum=$prodrow['minimum']; $price7=$prodrow['price7']; $price8=$prodrow['price8']; $price9=$prodrow['price9']; $image=$prodrow['image']; } ?> <form action="adminprodupdate.php" method="post"> <table width="500" border="1" cellpadding="10"> <tr> <td>ID:</td> <td><input type="hidden" value="<? echo $id; ?>" name="id" /></td> </tr> <tr> <td>Active:</td> <td><input name="active" type="radio" value="0" <?php echo ($active=='0')? 'checked':'';?> />Yes<br /> <input name="active" type="radio" value="1" <?php echo ($active=='1')? 'checked':'';?> />No</td> </tr> <tr> <td>Category:</td> <td><input name="cat_id" type="radio" value="1" <?php echo ($cat_id=='1')? 'checked':'';?> />Hats<br /> <input name="cat_id" type="radio" value="2" <?php echo ($cat_id=='2')? 'checked':'';?> />Shirts<br /> <input name="cat_id" type="radio" value="3" <?php echo ($cat_id=='3')? 'checked':'';?> />Promotional Items</td> </tr> <tr> <td>Product ID: </td> <td><input type="text" name="name" value="<? echo $name; ?>"></td> </tr> <tr> <td>Short Description: </td> <td><input type="text" name="description" value="<? echo $description; ?>"></td> </tr> <tr> <td>Details:</td> <td><textarea name="details" cols="50" rows="10" ><? echo $details; ?></textarea></td> </tr> <tr> <td>Price for S-XL:<br /> <br /><strong><div id="redfont">**Shirts**<br />&<br />**Hats**</div></strong></td> <td>1-23: <input type="text" name="price" value="<? echo $price; ?>"><br><br> 24-47: <input type="text" name="price2" value="<? echo $price2; ?>"><br><br> 48+: <input type="text" name="price3" value="<? echo $price3; ?>"><br><br> </td> </tr> <tr> <td>Price for 2XL - 5XL:<br /> <br /><strong><div id="redfont">**Shirts ONLY!**</div></strong></td> <td>1-23: <input type="text" name="price4" value="<? echo $price4; ?>"><br><br> 24-47: <input type="text" name="price5" value="<? echo $price5; ?>"><br><br> 48+: <input type="text" name="price6" value="<? echo $price6; ?>"><br><br> </td> </tr> <tr> <td>Minimum QTY: </td> <td><input type="text" name="minimum" value="<? echo $minimum; ?>"></td> </tr> <tr> <td>Sizes:</td> <td><? echo ''; $result = mysql_query("SELECT * FROM sizes"); while ($row = mysql_fetch_assoc($result)) { $selected = ''; $result2 = mysql_query("SELECT * FROM productoptions WHERE productid = '" . $_GET['id'] . "' AND sizeid = '" . $row['id'] . "'"); if ($row2 = mysql_fetch_assoc($result2)) { $selected = 'checked '; } echo '<input type="checkbox" name="size[]" value="' . $row['id'] . '" ' . $selected . '/> ' . $row['size'] . '<br />'; } ?> </td> </tr> <tr> <td>Colors:</td> <td><? $result = mysql_query("SELECT * FROM colors"); while ($row = mysql_fetch_assoc($result)) { $selected = ''; $result2 = mysql_query("SELECT * FROM productoptions WHERE productid = '" . $_GET['id'] . "' AND colorid = '" . $row['id'] . "'"); if ($row2 = mysql_fetch_assoc($result2)) { $selected = 'checked '; } echo '<input type="checkbox" name="color[]" value="' . $row['id'] . '" ' . $selected . '/> ' . $row['color'] . '<br />'; } ?> </td> </tr> <tr> <td> </td> <td><input type="Submit" value="Update this product"></td> </tr> </form> </table> <?php } require("footer.php"); ?> Here is my script: Code: [Select] <?php include("config.php"); include("db.php"); $id=$_POST['id']; $active=$_POST['active']; $cat_id=$_POST['cat_id']; $name=$_POST['name']; $description=$_POST['description']; $details=$_POST['details']; $price=$_POST['price']; $price2=$_POST['price2']; $price3=$_POST['price3']; $price4=$_POST['price4']; $price5=$_POST['price5']; $price6=$_POST['price6']; $minimum=$_POST['minimum']; $arrsizes = $_POST['size']; $arrcolors = $_POST['color']; $image=$_POST['image']; $sql="UPDATE products SET active = '$active', cat_id = '$cat_id', name = '$name', description = '$description', details = '$details', price = '$price', price2 = '$price2', price3 = '$price3', price4 = '$price4', price5 = '$price5', price6 = '$price6', minimum = '$minimum', image = '$image' WHERE id = '$id'"; $result = mysql_query("SELECT id FROM products ORDER BY id DESC LIMIT 0,1"); if ($row = mysql_fetch_assoc($result)) { $productid = $row['id']; } foreach ($arrsizes as $sizevalue) { foreach ($arrcolors as $colorvalue) { $sql2="UPDATE productoptions SET sizeid = '$sizevalue', colorid = '$colorvalue' WHERE productid='$id' "; } } mysql_query($sql) or die ("Error: ".mysql_error()); mysql_query($sql2) or die ("Error: ".mysql_error()); echo $sql; echo $sql2; header("Location: " . $config_basedir . "adminhome.php"); ?> And here is what is echo'd after submit: Code: [Select] UPDATE products SET active = '0', cat_id = '2', name = 'Test Edit Prod', description = 'just a simple test', details = 'just a simple testjust a simple testjust a simple testjust a simple testjust a simple testjust a simple test', price = '1', price2 = '2', price3 = '3', price4 = '4', price5 = '5', price6 = '6', minimum = '127', image = '' WHERE id = '41'UPDATE productoptions SET sizeid = '6', colorid = '5' WHERE productid='41' This part of the code: UPDATE productoptions SET sizeid = '6', colorid = '5' WHERE productid='41' , is supposed to be updating sizes and colors, however, it is only updating the last size/color selected in the check box. Thanks in advance for any support! Similar Tutorialshi i am trying to make a payroll calculator script that takes employee info, calculates pay, displays submitted info in a table, stores info in an array, and updates the array when new info is submitted. i have most of these accomplished, i am having trouble with the "store into an array, and update the array when new info is submitted" parts of the project. i am still not very fluent in php so there may be easier ways to achieve what i have so far. any pointers would be a great help, this part has got me stumped. I have an array containing webpages. $results = array(www.google.com, www.phpfreaks.com); echo file_get_contents($results[0]); echo file_get_contents($results[1]); Is there anyway to just echo get_file_contents without putting in the position in the array as I have hundreds of variables in it? I hate array... 😞 So I had a block of code inside my photo-gallery.php script that took the path to my photos directory, and went to that directory, and then read all of the photo filenames into an array. Then in my HTML, I iterate through this array to display all of the photos for my gallery. Now I would like to move that code to an included file so multiple scripts can access it and always be working with the same array. It seems to me that I need to encapsulate my code inside a function? Then I could call my getPhotoFilesArray back to my callings cript, and use that array for whatever. I haven't coded PHP in like 4 years and I am struggling to return the entire array back to my caling script. This is what I have so far... function getPhotoFilesArray($photoPath){ $photoFiles = array(); <code to find corresponding files> $photoFiles gets populated in a loop return $photoFiles; }
Then in my calling script, I have... <?php require_once('../../../secure_outside_webroot/config.php'); require_once(WEB_ROOT . 'utilities/functions.php'); getPhotoFilesArray($photoPath); var_dump($photoFiles);
I get some error...
Notice: Undefined variable: phtoFiles in photo-gallery.php line 133 (which is my var_dump).
<br> Would appreciate help getting this to work!
Edited December 6, 2019 by SaranacLake I have a form that allows a user to select from several dropdowns, employees who will receive an email message. The email script works fine, however if an employee is selected more than once (which is not a rare) then the employee will receive as many email messages as their name appears. I would like for each employee to only receive the email once. For example: I am the submitter of the form and I am also the coordinator for this particular job. Therefore, my name & email are in the array twice and I will receive two emails on submit. Here is my email script: Code: [Select] $submitter = get_employee_email($user_id); $project_manager = get_employee_email($pm_id); $accountant = get_employee_email($a_id); $coordinator = get_employee_email($pc_id); $contractor = get_employee_email($contractor_id); $director = get_employee_email($dr_id); $to = array($submitter, $project_manager, $accountant, $coordinator, $contractor, $director); foreach ($to as $t){ $headers["From"] = "TEST <TEST@gmail.com>"; $headers["To"] = $t; $headers["Subject"] = "TESTING FOR JOB ID $job_id"; $text = "TESTING. Please review!"; $html = "<html><body>TESTING. Please review!</body></html>"; $file_path = "./$file"; $crlf = "\n"; $name = "TEST.csv"; $smtp_info["host"] = "TEST@gmail.com"; $smtp_info["port"] = "40"; $mime = new Mail_mime($crlf); $mime->setTXTBody($text); $mime->setHTMLBody($html); $content_type = "text/csv"; $mime->addAttachment($file_path, $content_type, $name); $body = $mime->get(); $hdrs = $mime->headers($headers); $SMTP = Mail::factory('smtp',$smtp_info); $mail = $SMTP->send($t, $hdrs, $body); } Hello, i need to send emails to users according to the category they have selected everything works fine except for the mail function which tells me that i cannot parse an array variable. the error code is: Warning: mail() expects parameter 1 to be string, array given in C:\wamp\www\newsletter.php on line 25 can any1 tell me how i can send the mail so that it accepts that variable? my code is: Code: [Select] <?php $db_hostname="localhost"; $db_username="root"; $db_password=""; $db = mysql_connect($db_hostname,$db_username,$db_password); if (!$db) { die("Could not connect: " . mysql_error()); } mysql_select_db("newsletter", $db); if (isset($_POST['categories'])) { //make the checkmarks with name categories[] foreach ($_POST['categories'] as $cat) { $email_query = mysql_query("SELECT email FROM members WHERE `category` = '" . $cat . "'"); if (mysql_num_rows($email_query)) { while ($email = mysql_fetch_array($email_query)) { ini_set('SMTP','smtp.gmail.com'); if (mail($email, 'Subject','Message Goes Here', "From: <noreply@domain.com>")) { echo "Message Sent"; } else { echo "Message Not Sent"; } }//end while }// end if } } ?> How can I use php to update a dynamic amount of input fields and tell mysql which ones to update respectively? Essentially I have a list of occupations and if someone wants to update one of them I don't know how to tell php which one they've changed in a dynamic way. Code: [Select] <?php if(!empty($occupations)) { ?> <h3 id="job_function">Job Functions</h3> <?php $i = 0; foreach($occupations as $occupation) { ?> <div class="formElement"> <div class="formFieldLabel "> <label for="occupation_<?php echo $i; ?>"><?php echo $occupation['companyname']; ?></label> </div> <div class="formField"> <input id="occupation_<?php echo $i; ?>" type="text" name="occupation_<?php echo $i; ?>" value="<?php echo $occupation['function']; ?>" /> </div> </div> <?php $i++; } } ?> Hi all, I'm trying to figure out how to update values I have in an array. I'm a bit stuck and hope someone can advise. I've read about all sorts of bits but I'm stuck, I dont really understand associative so thought I'd post an example of my code for someone to hopefully assist.. so, if I have a table $fees, which is filled from a select, for example.. select * from `cases_fees`. "contains fields for id, type, amount and others now I want to do is foreach through that table and update a field called `amount`. but I cant understand the foreach >= as key part. what is a key and what isn't ? (I know what the keys of the db table arem but that's not the same eh?) I'm fine with normal foreach, but I cant update back to the array so I need to find out how to be able to set valus back into $fees[`amount`] hope someone can point me in the right direction please... Ted hey guys im really stuck and need help with this. im trying to update a mysql table from an array. basically i have 12 records what are pulled using a query. each record has its own ID to distinguish it from the rest. i then have 2 tick boxes for the user to select one for accept and one for deny. what i need is for the query to look at each record on the table and insert the selection boxes value if ticked. my code is below but i have altered it to the hilt and cannot get it to work so please help Code: [Select] <?php $path = $_SERVER['DOCUMENT_ROOT']; $path .= "/Apollo/dbc.php"; include_once($path); $rs_results = mysql_query("SELECT * FROM off WHERE IsItAuthorised='0' and isitsick='0' ORDER BY DayOff"); ?> <html> <head> <title>Administration Main Page</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <?php if (isset($_POST['submit'])) { //Assign each array to a variable $id = $_POST['id']; $approve = $_POST['approve']; $deny = $_POST['deny']; $limit = count($id); $values = array(); // initialize an empty array to hold the values for($k=0;$k<$limit;$k++){ $msg[] = "$limit Holidays Updated"; $id[k] = $id; $approve[k] = $approve; $deny[k] = $deny; $id = implode($id); $approve = implode( $approve); $deny = implode( $deny); $query = "UPDATE off SET Authorised = $approve , Deny = $deny WHERE OffID = $id " ; } $Event = "INSERT INTO events (UserName, Event ) VALUES ('$_SESSION[user_name]', 'Entered New KPI' )"; echo $query; if (!mysql_query($query,$link)){ die('Error: ' . mysql_error()); } else { mysql_query($Event); echo "<div class=\"msg\">" . $msg[0] . "</div>"; } } ?> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="14%" valign="top"><?php ?> </td> <td width="74%" valign="top" style="padding: 10px;"> <p><?php if(!empty($msg)) { echo $msg[0]; } ?></p> <p> <?php $cond = ''; $sql = "select * from off "; $rs_total = mysql_query($sql) or die(mysql_error()); $total = mysql_num_rows($rs_total); ?> <p> <form name "searchform" action="/Apollo/Admin/HolidayRequests.php" method="post"> <table width="100%" border="0" align="center" cellpadding="2" cellspacing="0"> <tr class="mytables"> <td width="4%"><font color="white"><strong>ID</font></strong></td> <td width="4%"> <font color="white"><strong>Staff Member</font></strong></td> <td width="10%"><font color="white"><strong>Day Off</font></strong></div></td> <td width="10%"><font color="white"><strong>Is It Authorized</font></strong></div></td> <td width="15%"> </td> </tr> <tr> <td> </td> <td width="10%"> </td> <td width="17%"><div align="center"></div></td> <td> </td> </tr> <?php while ($rrows = mysql_fetch_array($rs_results)) {?> <tr> <td><input name="id[]" id="id[]" size="4" value="<?php echo $rrows['OffID'];?>" /></td> <td><?php echo $rrows['StaffMember']; ?></td> <td><?php echo date('d/m/Y', strtotime($rrows['DayOff']));?></div></td> <td> <span id="approve<?php echo $rrows['id']; ?>"> <?php if(!$rrows['IsItAuthorised']) { echo "Pending"; } else {echo "Authorized"; }?> </span> </td> <td> <input type="hidden" name="approve[]" id="approve[]" value="0"> <input type="checkbox" name="approve[]" id="approve[]" value="1"> Approve <input type="hidden" name="deny[]" id="deny[]" value="0"> <input type="checkbox" name="deny[]" id="deny[]" value="1"> Deny </td> </tr> <?php } ?> </table> <input name="submit" type="submit" id="submit" value="Submit"> </form> </p> <?php ?> <p> </p> <p> </p> <p> </p> <p> </p></td> <td width="12%"> </td> </tr> </table> </body> </html> Hi all, Im having some trouble trying to update my table using an array, It processes and doesnt throw up any errors so im at a loss as to whats happening as its not updating my table? my page is Code: [Select] mysql_select_db($database_saucy_connection, $saucy_connection); $query_allphotos = "SELECT * FROM model_login, model_pictures WHERE model_pictures.user_id=model_login.id"; $allphotos = mysql_query($query_allphotos, $saucy_connection) or die(mysql_error()); $row_allphotos = mysql_fetch_assoc($allphotos); $totalRows_allphotos = mysql_num_rows($allphotos); ?><!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> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> </head> <body> <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>Id</strong></td> <td align="center">Picture Name</td> <td align="center">Upload Date</td> <td align="center"><strong>No Downloads</strong></td> <td align="center"> Approved? </td> <td align="center"> Hunnies Gallery </td> <td align="center"> Hunks Gallery </td> <td align="center"> Default Pic </td> <td align="center"> Theme Pic </td> <td align="center"> Homepage Pic </td> </tr> <?php while($rows=mysql_fetch_array($allphotos)){ ?> <tr> <td align="center"><? $id[]=$rows['id']; ?><? echo $rows['id']; ?></td> <td align="center"><? $user_picture[]=$rows['user_picture']; ?><?php echo $rows['user_picture']; ?></td> <td align="center"><? $user_picture_date[]=$rows['user_picture_date']; ?><?php echo $rows['user_picture_date']; ?></td> <td align="center"><? $picture_downloads[]=$rows['picture_downloads']; ?><?php echo $rows['picture_downloads']; ?></td> <td align="center"><? $user_pic_approval[]=$rows['user_pic_approval']; ?><?php echo $rows['user_pic_approval']; ?> </td> <td align="center"><? $hotties_gallery[]=$rows['hotties_gallery']; ?><?php echo $rows['hotties_gallery']; ?> </td> <td align="center"><? $hunks_gallery[]=$rows['hunks_gallery']; ?><?php echo $rows['hunks_gallery']; ?> </td> <td align="center"><? $default_pic[]=$rows['default_pic']; ?><?php echo $rows['default_pic']; ?> </td> <td align="center"><? $theme_gallery[]=$rows['theme_gallery']; ?><?php echo $rows['theme_gallery']; ?> </td> <td align="center"><? $homepage=$rows['homepage_pic']; ?><?php echo $rows['homepage_pic']; ?> </td> </tr> <?php } ?> <tr> <td colspan="5" 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 $model_pictures SET user_pic_approval='$user_pic_approval[$i]', hotties_gallery='$hotties_gallery[$i]', hunks_gallery='$hunks_gallery[$i]', default_pic='$default_pic[$i]', theme_gallery='$theme_gallery[$i]', homepage_pic='$homepage_pic[$i]' WHERE id='$id[$i]'"; $result1=mysql_query($sql1); } } Hi, Ok, so I'm making a registration form system, where I can create new registration forms for the users to pick a date etc. In my form I can add and remove text fields via Javascript - to add additional dates etc. so I don't know if I'll be submitting 3 fields or 15. The could look like this: <input type="hidden" name="session_id[]" value="<?php echo $session_id; ?>"> <input type="text" name="picked_date[]"> <input type="text" name="picked_room[]"> They are put in a big array: De bliver smidt i et stort array: $n=0; foreach ($session_id as $_session_id) { $bigar[$n][1] = $_session_id; $n++; } $n=0; foreach ($picked_date as $_picked_date) { $bigar[$n][2] = $_picked_date; $n++; } $n=0; foreach ($picked_room as $_picked_room) { $bigar[$n][3] = $_picked_room; $n++; } $n=0; which is then updated in the database using: foreach ($bigar as $part) { mysql_query("UPDATE... } Right - so far so good. The updating works fine with existing fields, but if I remove some of the fields (via JS) it obviously only updates the remaining in the array. The left out will be ignored. On the same note I would like to add fields as well, so - the bottom line - I want to: - UPDATE rows, where the ID is in the array - DELETE existing rows, WHERE the ID is NOT in the array - CREATE new rows for the new fields in the array (not having an ID) How can this be achieved? Hope someone can help... Hi there. I have a page that lists the records of a table. On this page I want to be able to edit/update two attributes of these records by a checkbox - e.g., being able to update multiple records at once. I thought the smartest way to achieve this would be by using arrays. I've implemented one checkbox array and have two fields. Currently when I change both fields and hit submit, the height value changes and the name value is changed to the last record displayed in the table. E.g. Height - 170 -> 160 -> UPDATED TO 160 Name - Test1 -> Test2 -> UPDATED TO VICTORY (last record listed in table; displayed alphabetically) My code is as follows: <?php include("connection.php"); $conn = oci_connect($UName,$PWord,$DB) or die("Database Error - Contact Admin - sjrei5@student.monash.edu"); if (empty($_POST["check"])) { $query = "SELECT * FROM HORSE ORDER BY HORSE_NAME"; $stmt = oci_parse($conn,$query); oci_execute($stmt); $Horses = oci_fetch_array ($stmt); ?> <form method="post" action="horse_multi.php"> <table border="1" id="customers"> <tr> <th>ID</th> <th>EDIT</th> <th>NAME</th> <th>HEIGHT</th> </tr> <?php while ($Horses = oci_fetch_array ($stmt)) { ?> <tr> <td><?php echo $Horses["HORSE_ID"]; ?></td> <td align="center"><input type="checkbox" name="check[]" value="<?php echo $Horses["HORSE_ID"]; ?>"></td> <td align="center"><input type="text" size="5" name="<?php echo $Horses["HORSE_ID"]; ?>" value="<?php echo $Horses["HORSE_HEIGHT"]; ?>"></td> <td align="center"><input type="text" size="20" name="HORSE_NAME" value="<?php echo $Horses['HORSE_NAME']; ?>"></td> </tr> <?php } ?> </table><p /> <h4><input type="submit" value="Update Selected Horses"></h4> </form> <?php oci_free_statement($stmt); } else { foreach($_POST["check"] as $horse_id) { $query = "UPDATE HORSE SET HORSE_NAME= '$_POST[HORSE_NAME]', HORSE_HEIGHT = ".$_POST[$horse_id]." WHERE HORSE_ID ='".$horse_id."'"; $stmt = oci_parse($conn,$query); oci_execute($stmt); } } ?> </body> </html> Any ideas? I have the below code: Code: [Select] <div> <table width="100%" border="0" cellspacing="0" cellpadding="4"> <tr> <td colspan="7" valign="top"> <form enctype="multipart/form-data" action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <?php if (isset($submit)) { // UPDATE QUERY CODE WHEN SUBMIT IS ENTERED $str = implode(';',$_POST['checks']); $insert = "UPDATE members SET settings='$str' WHERE member_id='$_SESSION[SESS_MEMBER_ID]'"; if (@mysql_query($insert)) { ?> <script type="text/javascript"> document.location.replace('settings-tests.php'); </script> <?php } else { echo('Error in you submission:' . mysql_error() . "<br /><br />" . $sql); } } ?> <?php { $result=mysql_query("SELECT * FROM members WHERE member_id = '$_SESSION[SESS_MEMBER_ID]'"); $row = mysql_fetch_array($result); $arr = array(); $arr = explode(';',$row['settings']); $member_id = $row['member_id']; $firstname = $row['firstname']; $lastname = $row['lastname']; $email = $row['email']; $membership = $row['membership']; $roles = $row['roles']; $login = $row['login']; ?> <table width="100%" border="0" cellspacing="0" cellpadding="4"> <tr> <td colspan="2"><h3>Test Results Settings</h3></td> <td width="25%"> </td> <td width="25%"><?php echo $_SESSION['SESS_MEMBER_ID']; ?></td> </tr> <tr> <td colspan="4"><em>To turn off individual results gloablly across the site please use the following sliders (all results already added will also be made invisable)<br /> <br /> </em></td> </tr> <tr> <td width="25%"><div align='right'><strong><em>Salinity:</em></strong></div></td> <td width="25%"><input type="checkbox" value="test1" name="checks[]2" <?php echo (in_array("test1",$arr) ? "checked" : ''); ?>/></td> <td><div align='right'><strong><em>Phosphate:</em></strong></div></td> <td><input type="checkbox" value="test9" name="checks[]10" <?php echo (in_array("test9",$arr) ? "checked" : ''); ?>/></td> </tr> <tr> <td><div align='right'><strong><em>PH:</em></strong></div></td> <td><input type="checkbox" value="test2" name="checks[]3" <?php echo (in_array("test2",$arr) ? "checked" : ''); ?>/></td> <td><div align='right'><strong><em>potassium:</em></strong></div></td> <td><input type="checkbox" value="test10" name="checks[]11" <?php echo (in_array("test10",$arr) ? "checked" : ''); ?>/></td> </tr> <tr> <td><div align='right'><strong><em>Ammonia:</em></strong></div></td> <td><input type="checkbox" value="test3" name="checks[]4" <?php echo (in_array("test3",$arr) ? "checked" : ''); ?>/></td> <td><div align='right'><strong><em>Iodine:</em></strong></div></td> <td><input type="checkbox" value="test11" name="checks[]12" <?php echo (in_array("test11",$arr) ? "checked" : ''); ?>/></td> </tr> <tr> <td><div align='right'><strong><em>Nitrite:</em></strong></div></td> <td><input type="checkbox" value="test4" name="checks[]5" <?php echo (in_array("test4",$arr) ? "checked" : ''); ?>/></td> <td><div align='right'><strong><em>Strontium:</em></strong></div></td> <td><input type="checkbox" value="test12" name="checks[]13" <?php echo (in_array("test12",$arr) ? "checked" : ''); ?>/></td> </tr> <tr> <td><div align='right'><strong><em>Nitrate:</em></strong></div></td> <td><input type="checkbox" value="test5" name="checks[]6" <?php echo (in_array("test5",$arr) ? "checked" : ''); ?>/></td> <td><div align='right'><strong><em>Silica:</em></strong></div></td> <td><input type="checkbox" value="test13" name="checks[]14" <?php echo (in_array("test13",$arr) ? "checked" : ''); ?>/></td> </tr> <tr> <td><div align='right'><strong><em>Calcium:</em></strong></div></td> <td><input type="checkbox" value="test6" name="checks[]7" <?php echo (in_array("test6",$arr) ? "checked" : ''); ?>/></td> <td><div align='right'><strong><em>Temperatu </em></strong></div></td> <td><input type="checkbox" value="test14" name="checks[]" <?php echo (in_array("test14",$arr) ? "checked" : ''); ?>/></td> </tr> <tr> <td><div align='right'><strong><em>Magnesium:</em></strong></div></td> <td><input type="checkbox" value="test7" name="checks[]8" <?php echo (in_array("test7",$arr) ? "checked" : ''); ?>/></td> <td></td> <td></td> </tr> <tr> <td><div align='right'><strong><em>Alkalinity:</em></strong></div></td> <td><input type="checkbox" value="test8" name="checks[]9" <?php echo (in_array("test8",$arr) ? "checked" : ''); ?>/></td> <td colspan="2" align="right"></td> </tr> <tr> <td colspan="4" align="right"><table border="0" cellspacing="0" cellpadding="8"> <tr> <td><input class="Button" type="submit" name="submit" value="Submit" /></td> <td><input class="Button-alt" type="reset" name="reset" value="Reset" /></td> </tr> </table></td> </tr> </table> <br /> </form><?php } ?> </td> </tr> </table> </p> </div> This pulls data in array from database for example: test1;test9;test2;test3;test4;test5;test6;test14;test7;test8 The SELECT query works fine if i manually edit the array in the database to make the boxes checked or not. Problem seems to be when i click submit, its not updating the DATABASE?! i recently upgraded to PHP5 eventually and it seems it stopped working arond then. any help please. Hi, I have the following code which basically checks an array of input textboxes and inserts them into a database table: public function insertAuthor($authArray, $PCorder=0) { $query = sprintf('SELECT Pid, Pname FROM People WHERE Pname IN(\'%s\') ORDER BY Pid ASC', implode('\',\'', $authArray)); $result = mysql_query($query); $maxquery = "SELECT MAX(CPid) as max FROM ConfPaper WHERE CPRid = ".$_GET['CPRid']; $maxresult = mysql_query($maxquery); $max = mysql_fetch_array($maxresult); $CPid = $max['max']; if($result && mysql_num_rows($result) > 0) { $sqlValues = array(); while(list($PId, $PName) = mysql_fetch_row($result)) { if(in_array($PName, $authArray)) { $sqlValues[] = sprintf("(%d, 1, ".$CPid.", %d, now(), 0)", $PId , $PCorder++ ); // Author already exists within the Pname table // remove user from $authArray $key = array_search($PName, $authArray); unset($authArray[$key]); } } $sql = "INSERT INTO PeopleCon(Person_id, PCHid, Pid, PCorder, PCdateadded, PCdeleted) VALUES \n"; $sql .= implode(",\n", $sqlValues); $result = mysql_query($sql); } // If there are Authors left within the $authArray // Add them to the Pname table if(count($authArray) > 0) { People::insertPersons($authArray); // call insertPersons method for remaining authors $this->insertAuthor($authArray, $PCorder); // insert the remaining auhtors into PeopleCon } } insertPersons method is as such: public function insertPersons($PName) { $query = "INSERT INTO People (Pname) VALUES ('" . implode("'), ('", $PName) . "')"; $result = mysql_query($query); } The logic works by firstly checking to see if an Author exists, if so they are inserted into PeopleCon, if not they are inserted into People AND PeopleCon. This all works perfectly.. But now what i need to do is build an update method where users can edit the authors also. The logic would be more or less the same, but i wouldn't neeed an insertpersons method, i would need to change it, and also the script would edit the existing authors, and if anymore are added apply the same method as above. Can anyone help me out as to how i should go about tackling this? Thanks Kind regards Billy Code: [Select] //Update the ranks if (isset($_POST['update'])){ $ids = implode(",", array_map('intval', $_POST['m'])); $ranks = implode(",", array_map('intval', $_POST['ranks'])); if ($ids < 1) message("Incorrect Data"); if ($ranks < 0) message("Incorrect Data"); foreach ($_POST['ranks'] as $muffins){ $db->query('UPDATE friends set rank = '.$muffins.' WHERE friend_id = '.$_POST['m'].' AND user_id = '.$pun_user['id'].'') or error('Unable to remove users from online list', __FILE__, __LINE__, $db->error()); } redirect("s.php?section=Friends","Thanks, Ranks Updated"); } friend_id = becomes blank? the $muffins work and each rank is showed respectivaly, but how can I join in another array in the loop? I tried another foreach in the loop, but it just made me run double the queries. Any idea? $muffins is working fine and $_POST['m'] is giving no results i need to have 2 dynamic arrays in that forloop, the $ranks and the $ids As you can see, this array is setting each colorvalue to each idvalue. Code: [Select] <?php include("config.php"); include("db.php"); $arrid=$_POST['id']; $arrcolor=$_POST['color']; foreach ($arrid as $idvalue) { foreach ($arrcolor as $colorvalue) { $sql = "UPDATE colors SET color='$colorvalue' WHERE id = '$idvalue'"; mysql_query($sql) or die("Error: ".mysql_error()); echo $sql; } } header("Location: " . $config_basedir . "adminhome.php"); ?> Now, here's what I'm trying to do:
First, I have a file filled with data like such:
title
tag
1
2
Title
Description
Etc
Next, I upload that file to my site which then proceeds to make an array with said data and then inserts it into my database. But this is not the intended behavior. Right now, if I upload the same file again, it will re-insert everything and duplicate all entries.
What I want to do is check if the data in the file has already been added, do nothing. If it's been modified, I want to update the database where changes have been made and not duplicate anything.
Currently, my code does all that except one thing whre I'm really stuck: it won't update the changes from the file to the database. I've tried echoing everything and it's to be working except for the query so I take it the error is in there but I can't find it... I'm still learning PHP and MySQL so I thought maybe somebody could help indicate where or what I'm doing wrong in the query. Thanks in advance !
Here's my attempt at doing so:
$register_ep_data = array( 'show' => $name, 'season' => $srNum, 'ep' => $epNum, 'app_name' => $epName, 'tag' => $tag, 'app_about' => $desc, 'app_website' => $imdb, 'app_release' => $release, 'type' => $type, 'app_code' => $Frame ); array_walk($register_ep_data, 'array_fu'); $fields = '`' . implode('`, `', array_keys($register_ep_data)) . '`'; $data = '\'' . implode('\', \'', $register_ep_data) . '\''; $epFound = false; $id = 0; while ($ep_list_data = mysql_fetch_array($turtle)) { $id = $ep_list_data['app_id']; $currentNAME = $ep_list_data['app_name']; $SERIES = $ep_list_data['show']; if ($SERIES == $name) { if ($currentNAME == $epName) { $epFound = true; break; } } } if ($epFound) { mysql_query("UPDATE `games` SET ($fields) VALUES ($data) WHERE `app_id` = '$id'"); } else { mysql_query("INSERT INTO `games` ($fields) VALUES ($data)"); }A few explanations: $fields would equal to something like: `show`, `season`, `ep`, etc... and $data to 'example', '1', '2', 'etc' Hello all, im new to this forum, im a noobie, just started coding about 3 weeks ago, don't be too hard on me.
My question is I wan't to check for challenges a user's team posted that have not been excepted after 1 day, then auto refund the user's team back there credits, and then also delete all the challenges. So far here is my code.
//Delete all matches not accepted after 1 day $arrayin = array(); $autorefund = mysql_query("SELECT * FROM `challenges` WHERE `a` = " . $team['id'] . " " . "AND `accepted` = 0 AND `completed` = 0 AND `chtype` = 1 AND (`expires` < " . ((int) time()) . ")"); if (mysql_num_rows($autorefund) > 0) { while ($autorefund = mysql_fetch_assoc($autorefund)) { $arrayin[] = $autorefund['id']; mysql_query("UPDATE `teams` SET `balance` = `balance` + " . $autorefund['credits'] . " " . "WHERE `id` IN (" . mysql_real_escape_string(implode(',', $arrayin)) . ")"); mysql_query("DELETE FROM `challenges` WHERE `a` IN " . "(" . mysql_real_escape_string(implode(',', $arrayin)) . ") " . "AND `accepted` = 0 AND `completed` = 0 AND `chtype` = 1 " . "AND (`expires` < " . ((int) time()) . ")"); } }FYI here is the code i had, it works fine, however it will only delete 1 challenge per team, not all of there challenges. $autorefund = mysql_query("SELECT * FROM `challenges` WHERE `a` = " . $team['id'] . " AND `accepted` = 0 AND `completed` = 0 AND `chtype` = 1 AND (`expires` < ".((int)time()).")"); if (mysql_num_rows($autorefund) > 0) { while ($autorefund = mysql_fetch_assoc($autorefund)) { if ($autorefund['accepted'] == 0 and $autorefund['expires'] < time()) { mysql_query("UPDATE `teams` SET `balance` = `balance` + " . $autorefund['credits'] . " WHERE `id` = " . $team['id'] . ""); mysql_query("DELETE FROM `challenges` WHERE `a` = " . $team['id'] . " AND `accepted` = 0 AND `completed` = 0 AND `chtype` = 1 AND (`expires` < ".((int)time()).")); } } }I inherited this script, its using deprecated statements, i know im not skilled to rewrite the entire site to use prepared statements. I am pulling 5 addresses and I am wanting to store these 5 addresses in columns in a separate table. On the query string I put LIMIT 5. How can I store the results of each of the 5 loops into columns in a separate table? The columns are A1(for name), A2(for address), A3 (for city), A4 (for state), A5 (for zip), A6 (for phone), A7 (for miles), .... then I also have B1-B7, C1-C7, D1-D7, and E1-E7. I am basically wanting to store up to 5 addresses in an array and then update them into a mysql table. Code: [Select] foreach ($zips as $key => $value) { $result = mysql_query("SELECT State FROM extreme WHERE Zip = '$key' AND Type='store' AND `InStore` <> 'NO' LIMIT 5", $db); $num_rows = mysql_num_rows($result); while($myrow = mysql_fetch_array ($result)) { $Dealer=$myrow['Dealer']; $Address=$myrow['Address']; $City=$myrow['City']; $State=$myrow['State']; $Zip=$myrow['Zip']; $Phone=$myrow['Phone']; $Miles = $value; } } I am using a WordPress theme that uses some of its own functions besides WP functions. Let me make clear from the start that when I say "Multiple Checkboxes" in the paragraphs below I am NOT talking about checkboxes that each hold a single value. I am talking about one Checkbox field that allows multiple values to be selected and puts those values into an array with one Name value and stores the output in a string in a single mysql table field. Right up front, what I need during the Edit Ad functions is the inbuilt function that will Delete the previous Array of values in any multiple checkbox when the ad is updated. Right now updating the ad works for every situation except NO values selected or for Unchecking all previously selected values in a Multiple Checkbox. If I have, for example, 4 checkboxes selected and unselect all of them before submitting the edited ad it will return the last saved array of values but not an Empty array with no checkboxes selected. This theme has a Form Builder with a Custom fields builder used by the admin to create forms for a classified ads website. According to which category of ad the Ad creation procedure will show different forms, with different fields. I had to manually create the capability to generate multiple checkboxes...so that the different multiple checkboxes when selected and updated to the mysql table might hold a variety of values in a comma-delimited array. That works fine. When the Ad is edited on its own page, (outside of the Wordpress admin dashboard) the problem is that if a user would uncheck all checkboxes in a particular multiple checkbox then the unselected state does not overwrite the previous array of values. What returns after editing is the previous selected values. I have tried jquery functions but none of them are working the way I had hoped. so one type of checkbox might have a hypothetical value like this "name="cp_checkbox_help[]" and if three options are selected then on submit the value could be--- name="cp_checkbox_help[Sunday,Monday,Tuesday]" I use implode and explode to store the array as comma separated and retrieve the array for editing or display. I guess I need to create a Null or empty value as a default that only changes when selections are made. But, since I use implode and explode to make the array "pretty" I don't know if simply specifying nothing will erase a whole array on update. Here is some of the code used to see how I get what I get-- This displays the checkboxes that I create and name and fill with different values-- case 'checkbox': ?> <?php $options = explode(',', $result->field_values); echo '<div id="checkboxes"><table width="100%" border="0" cellspacing="0" cellpadding="5"> <tr> <th colspan="2" scope="col">' . $result->field_label. '</th> </tr>'; $myvals= explode(',', $post_meta_val); foreach ($options as $option) { { ?> <tr> <td width="4%"><input style="display:inline-block; float:left;" type="<?php echo $result->field_type; ?>" name="<?php echo $result->field_name; ?>[]" class="checkbox<?php if($result->field_req) echo ' required'?>" id="<?php echo $field_label; ?>" value="<?php echo $option; ?>" <?php foreach ($myvals as $myval) { if (in_array($myval, array($option), true)) {echo 'checked="yes"';}}?>/></td> <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" ><?php echo $option . '</td> </tr> ' ?> <?php } } echo ' </tr> </table></div><div class="clr"></div>'; break; Following is the main part of the code that updates the Ad form-- // update the ad and return the ad id $post_id = wp_update_post($update_ad); if($post_id) { // now update all the custom fields foreach($_POST as $meta_key => $meta_value) { if (cp_str_starts_with($meta_key, 'cp_')) if (cp_str_starts_with($meta_key, 'cp_checkbox_charley')) $meta_value= implode(',', $_POST['cp_checkbox_charley']); if (cp_str_starts_with($meta_key, 'cp_checkbox_help')) $meta_value = implode(',', $_POST['cp_checkbox_help']); if (cp_str_starts_with($meta_key, 'cp_checkbox_hello')) $meta_value= implode(',', $_POST['cp_checkbox_hello']); //echo $meta_key . ' <--metakey <br/>' . $meta_value . ' <--metavalue<br/><br/>'; // for debugging update_post_meta($post_id, $meta_key, $meta_value); } $errmsg = '<div class="box-yellow"><b>' . __('Your ad has been successfully updated.','cp') . '</b> <a href="' . CP_DASHBOARD_URL . '">' . __('Return to my dashboard','cp') . '</a></div>'; } else { // the ad wasn't updated so throw an error $errmsg = '<div class="box-red"><b>' . __('There was an error trying to update your ad.','cp') . '</b></div>'; } return $errmsg; } Back on the Edit Ad page this is the Submit <p class="submit center"> <input type="button" class="btn_orange" onclick="window.location.href='<?php echo CP_DASHBOARD_URL ?>'" value="<?php _e('Cancel', 'cp')?>" /> <input type="submit" class="btn_orange" value="<?php _e('Update Ad »','cp') ?>" name="submit" /> I have a feeling what I need is just a couple of lines to detect no posted values and then... but if one checkbox array has 6 values in it and another checkbox array has only 3 values, for example, do I need to count each specific checkbox for number of values and then overwrite or will one function completely delete the previous array and its commas? I would really appreciate some expert assistance here! Hi all, I have the following MySQL insert query: Code: [Select] $insert= mysql_query ("INSERT INTO tablename (column1,`".$EXPfields."`) VALUES ('$something','".$EXPvalues."')"); where $EXPfields is an array of table-field-names and $EXPvalues is an array of table-field-values. Now I want to write an equivalent query, but using UPDATE instead of INSERT INTO, but I don't want to write out all the field names/values separately, but again want to use $EXPfields and $EXPvalues. So something like this: Code: [Select] $update = mysql_query ("UPDATE tablename SET (column1,`".$EXPfields."`) = ('$something','".$EXPvalues."') WHERE .... "); Is this possible? If so, what is the proper syntax? Thanks! |